"use client"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { PieChart, Pie, Cell, ResponsiveContainer } from "recharts"
import { useGetServiceAppointments } from "@/lib/react-query/hooks/analytics"
import { Skeleton } from "@/components/ui/skeleton"
import { Calendar, TrendingUp, BarChart3 } from "lucide-react"
import { useTranslations } from "next-intl"

export function ServiceTab() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      <ServiceDistributionChart />
      <ServicePerformance />
    </div>
  )
}

const colorPalette = [
  "#2563eb", // blue-600
  "#22c55e", // green-500
  "#eab308", // yellow-500
  "#f43f5e", // rose-500
  "#8b5cf6", // violet-500
  "#06b6d4", // cyan-500
  "#f97316", // orange-500
  "#ec4899"  // pink-500
]

function EmptyServiceDistributionState() {
  const t = useTranslations()

  return (
    <div className="flex flex-col items-center justify-center py-12 text-center">
      <div className="w-16 h-16 bg-blue-50 rounded-full flex items-center justify-center mb-4">
        <BarChart3 className="w-8 h-8 text-blue-600" />
      </div>
      <h3 className="text-lg font-semibold text-gray-900 mb-2">{t("analytics.service.distribution.empty.title")}</h3>
      <p className="text-sm text-gray-500 mb-4 max-w-xs">
        {t("analytics.service.distribution.empty.description")}
      </p>
      <div className="flex items-center gap-2 text-xs text-gray-400">
        <TrendingUp className="w-4 h-4" />
        <span>{t("analytics.service.distribution.empty.subtitle")}</span>
      </div>
    </div>
  )
}

function EmptyServicePerformanceState() {
  const t = useTranslations()

  return (
    <div className="flex flex-col items-center justify-center py-12 text-center">
      <div className="w-16 h-16 bg-green-50 rounded-full flex items-center justify-center mb-4">
        <TrendingUp className="w-8 h-8 text-green-600" />
      </div>
      <h3 className="text-lg font-semibold text-gray-900 mb-2">{t("analytics.service.performance.empty.title")}</h3>
      <p className="text-sm text-gray-500 mb-4 max-w-xs">
        {t("analytics.service.performance.empty.description")}
      </p>
      <div className="flex items-center gap-2 text-xs text-gray-400">
        <TrendingUp className="w-4 h-4" />
        <span>{t("analytics.service.performance.empty.subtitle")}</span>
      </div>
    </div>
  )
}

function ServiceDistributionChart() {
  const { data: servicesData, isLoading } = useGetServiceAppointments()
  const t = useTranslations()

  // Transform API data for pie chart
  const chartData = servicesData?.map((service, index) => ({
    name: service.serviceName,
    value: service.totalAppointments,
    color: colorPalette[index % colorPalette.length]
  })) || []

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="font-medium text-primary-blue">{t("analytics.service.distribution.title")}</CardTitle>
          <CardDescription className="text-xs text-muted-foreground">{t("analytics.service.distribution.description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-[300px]">
            <Skeleton className="w-48 h-48 rounded-full" />
          </div>
          <div className="flex flex-wrap justify-center gap-x-6 gap-y-2 mt-4">
            {[1, 2, 3, 4].map((i) => (
              <div key={i} className="flex items-center gap-2 mb-2">
                <Skeleton className="w-3 h-3 rounded-full" />
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-8" />
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!servicesData || servicesData.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="font-medium text-primary-blue">{t("analytics.service.distribution.title")}</CardTitle>
          <CardDescription className="text-xs text-muted-foreground">{t("analytics.service.distribution.description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <EmptyServiceDistributionState />
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="font-medium text-primary-blue">{t("analytics.service.distribution.title")}</CardTitle>
        <CardDescription className="text-xs text-muted-foreground">{t("analytics.service.distribution.description")}</CardDescription>
      </CardHeader>

      <CardContent>
        <ResponsiveContainer width="100%" height={300}>
          <PieChart>
            <Pie
              data={chartData}
              dataKey="value"
              nameKey="name"
              cx="50%"
              cy="50%"
              outerRadius={90}
              innerRadius={60}
              label={({ name }) => name}
              labelLine={false}
              paddingAngle={2}
              isAnimationActive={true}
            >
              {chartData.map((entry, index) => (
                <Cell key={`cell-${index}`} fill={entry.color} />
              ))}
            </Pie>
          </PieChart>
        </ResponsiveContainer>
        <div className="flex flex-wrap justify-center gap-x-6 gap-y-2 mt-4">
          {chartData.map((entry, idx) => (
            <div key={entry.name + idx} className="flex items-center gap-2 mb-2">
              <span className="inline-block w-3 h-3 rounded-full" style={{ background: entry.color }} />
              <span className="text-sm text-foreground font-medium">{entry.name}</span>
              <span className="text-sm text-muted-foreground">{entry.value}</span>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}

function ServicePerformance() {
  const { data: servicesData, isLoading } = useGetServiceAppointments()
  const t = useTranslations()

  // Transform API data for performance display
  const performanceData = servicesData?.map((service, index) => ({
    name: service.serviceName,
    bookings: service.totalAppointments,
    revenue: service.totalSpent,
    color: colorPalette[index % colorPalette.length]
  })) || []

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="font-medium text-primary-blue">{t("analytics.service.performance.title")}</CardTitle>
          <CardDescription className="text-xs text-muted-foreground">{t("analytics.service.performance.description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="divide-y divide-border max-h-[370px] overflow-auto px-2">
            {[1, 2, 3, 4].map((i) => (
              <div key={i} className="flex items-center py-3 gap-4">
                <Skeleton className="w-3 h-3 rounded-full" />
                <Skeleton className="flex-1 h-4" />
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-12" />
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!servicesData || servicesData.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="font-medium text-primary-blue">{t("analytics.service.performance.title")}</CardTitle>
          <CardDescription className="text-xs text-muted-foreground">{t("analytics.service.performance.description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <EmptyServicePerformanceState />
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="font-medium text-primary-blue">{t("analytics.service.performance.title")}</CardTitle>
        <CardDescription className="text-xs text-muted-foreground">{t("analytics.service.performance.description")}</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="divide-y divide-border max-h-[370px] overflow-auto px-2">
          {performanceData.map(service => (
            <div key={service.name} className="flex items-center py-3 gap-4">
              <span className="inline-block w-3 h-3 rounded-full" style={{ background: service.color }} />
              <span className="flex-1 text-sm font-medium text-foreground">{service.name}</span>
              <span className="text-sm text-muted-foreground">{service.bookings} {service.bookings === 1 ? t("analytics.service.performance.booking") : t("analytics.service.performance.bookings")}</span>
              <span className="text-sm font-semibold text-blue-700">€{service?.revenue?.toLocaleString()}</span>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}
