import { useMemo, useState } from 'react'
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
  PieChart, Pie, Cell, ResponsiveContainer,
} from 'recharts'
import { Stethoscope, CheckCircle, ArrowLeftRight, Clock, Info } from 'lucide-react'
import { useGutachtenStatistik } from '@/hooks/useDashboard'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Tooltip as UiTooltip, TooltipContent, TooltipTrigger,
} from '@/components/ui/tooltip'

const CHART_COLORS = [
  'var(--chart-1)',
  'var(--chart-2)',
  'var(--chart-3)',
  'var(--chart-4)',
  'var(--chart-5)',
]

export function GutachtenStatistikPage() {
  const currentYear = new Date().getFullYear()
  const years = Array.from({ length: 5 }, (_, i) => currentYear - i)
  const [jahr, setJahr] = useState(currentYear)
  const { data, isLoading } = useGutachtenStatistik(jahr)

  // Filter out weeks with no data for cleaner charts
  const gutachtenWeekly = useMemo(() => {
    if (!data?.gutachten_weekly) return []
    return data.gutachten_weekly.filter((w) => w.bestaetigung > 0 || w.alternative > 0)
  }, [data])

  const therapieWeekly = useMemo(() => {
    if (!data?.therapie_weekly) return []
    return data.therapie_weekly.filter((w) => w.ta_ja > 0 || w.ta_nein > 0)
  }, [data])

  // Donut data for type distribution
  const typDonutData = useMemo(() => {
    if (!data?.kpis) return []
    const items = []
    if (data.kpis.bestaetigung > 0) items.push({ name: 'Bestätigung', value: data.kpis.bestaetigung })
    if (data.kpis.alternative > 0) items.push({ name: 'Alternative', value: data.kpis.alternative })
    if (data.kpis.uncodiert > 0) items.push({ name: 'Uncodiert', value: data.kpis.uncodiert })
    return items
  }, [data])

  // Horizontal bar data for therapy change reasons
  const reasonsData = useMemo(() => {
    if (!data?.kpis) return []
    return [
      { name: 'Diagnosekorrektur', value: data.kpis.diagnosekorrektur },
      { name: 'Unterversorgung', value: data.kpis.unterversorgung },
      { name: 'Übertherapie', value: data.kpis.uebertherapie },
    ].filter((r) => r.value > 0)
  }, [data])

  const reasonsMax = reasonsData.length > 0 ? Math.max(...reasonsData.map((r) => r.value)) : 1

  const tooltipStyle = {
    backgroundColor: 'var(--popover)',
    border: '1px solid var(--border)',
    borderRadius: '8px',
    color: 'var(--popover-foreground)',
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Gutachten-Statistik</h1>
        <Select value={String(jahr)} onValueChange={(v) => setJahr(Number(v))}>
          <SelectTrigger className="w-[140px]">
            <SelectValue placeholder="Jahr" />
          </SelectTrigger>
          <SelectContent>
            {years.map((y) => (
              <SelectItem key={y} value={String(y)}>{y}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* KPI Cards */}
      {isLoading ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <Card key={i}>
              <CardHeader className="pb-2"><Skeleton className="h-4 w-24" /></CardHeader>
              <CardContent><Skeleton className="h-8 w-16" /></CardContent>
            </Card>
          ))}
        </div>
      ) : data ? (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <KpiCard
            title="Gutachten gesamt"
            tooltip="Alle Fälle mit erstelltem Gutachten im gewählten Jahr"
            value={data.kpis.total_gutachten}
            icon={<Stethoscope className="size-5 text-muted-foreground" />}
          />
          <KpiCard
            title="Bestätigung"
            tooltip="Gutachten, die die Erstmeinung bestätigen"
            value={data.kpis.bestaetigung}
            icon={<CheckCircle className="size-5 text-green-600" />}
          />
          <KpiCard
            title="Alternative"
            tooltip="Gutachten mit abweichender Therapieempfehlung"
            value={data.kpis.alternative}
            icon={<ArrowLeftRight className="size-5 text-orange-500" />}
          />
          <KpiCard
            title="Uncodiert"
            tooltip="Gutachten, die noch nicht klassifiziert wurden"
            value={data.kpis.uncodiert}
            icon={<Clock className="size-5 text-muted-foreground" />}
          />
        </div>
      ) : (
        <p className="text-muted-foreground">Keine Daten verfügbar.</p>
      )}

      {/* Row 1: Gutachten type per KW + Donut */}
      {data && (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          {/* Stacked bar: Bestätigung vs Alternative per KW */}
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle>Gutachten-Typ pro Kalenderwoche</CardTitle>
              <p className="text-xs text-muted-foreground">Bestätigung und Alternative pro KW</p>
            </CardHeader>
            <CardContent>
              {gutachtenWeekly.length > 0 ? (
                <ResponsiveContainer width="100%" height={350}>
                  <BarChart data={gutachtenWeekly}>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                    <XAxis dataKey="kw" tickFormatter={(v) => `${v}`} className="text-xs" interval="preserveStartEnd" />
                    <YAxis className="text-xs" />
                    <Tooltip labelFormatter={(v) => `KW ${v}`} contentStyle={tooltipStyle} />
                    <Legend />
                    <Bar dataKey="bestaetigung" name="Bestätigung" stackId="a" fill="var(--chart-3)" radius={[0, 0, 0, 0]} />
                    <Bar dataKey="alternative" name="Alternative" stackId="a" fill="var(--chart-1)" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-muted-foreground text-center py-16">Noch keine codierten Gutachten vorhanden.</p>
              )}
            </CardContent>
          </Card>

          {/* Donut: Type distribution */}
          <Card>
            <CardHeader>
              <CardTitle>Typ-Verteilung</CardTitle>
              <p className="text-xs text-muted-foreground">Bestätigung, Alternative, Uncodiert</p>
            </CardHeader>
            <CardContent>
              {typDonutData.length > 0 ? (
                <ResponsiveContainer width="100%" height={350}>
                  <PieChart>
                    <Pie
                      data={typDonutData}
                      cx="50%"
                      cy="45%"
                      innerRadius={50}
                      outerRadius={85}
                      paddingAngle={3}
                      dataKey="value"
                      label={({ value }) => value}
                    >
                      {typDonutData.map((_, idx) => (
                        <Cell key={idx} fill={[
                          'var(--chart-3)',
                          'var(--chart-1)',
                          'var(--chart-4)',
                        ][idx % 3]} />
                      ))}
                    </Pie>
                    <Tooltip contentStyle={tooltipStyle} />
                    <Legend
                      verticalAlign="bottom"
                      iconType="circle"
                      iconSize={10}
                      formatter={(value: string) => (
                        <span style={{ color: 'var(--foreground)', fontSize: '13px' }}>{value}</span>
                      )}
                    />
                  </PieChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-muted-foreground text-center py-16">Keine Daten.</p>
              )}
            </CardContent>
          </Card>
        </div>
      )}

      {/* Row 2: Therapy changes per KW + Reasons */}
      {data && (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          {/* Grouped bar: TA Ja vs Nein per KW */}
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle>Therapieänderungen pro Kalenderwoche</CardTitle>
              <p className="text-xs text-muted-foreground">Fälle mit und ohne Therapieänderung pro KW</p>
            </CardHeader>
            <CardContent>
              {therapieWeekly.length > 0 ? (
                <ResponsiveContainer width="100%" height={350}>
                  <BarChart data={therapieWeekly}>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                    <XAxis dataKey="kw" tickFormatter={(v) => `${v}`} className="text-xs" interval="preserveStartEnd" />
                    <YAxis className="text-xs" />
                    <Tooltip labelFormatter={(v) => `KW ${v}`} contentStyle={tooltipStyle} />
                    <Legend />
                    <Bar dataKey="ta_ja" name="Therapieänderung Ja" fill="var(--chart-1)" radius={[4, 4, 0, 0]} />
                    <Bar dataKey="ta_nein" name="Therapieänderung Nein" fill="var(--chart-2)" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-muted-foreground text-center py-16">Noch keine Therapieänderungen codiert.</p>
              )}
            </CardContent>
          </Card>

          {/* Reasons for therapy change */}
          <Card>
            <CardHeader>
              <CardTitle>Gründe für Therapieänderung</CardTitle>
              <p className="text-xs text-muted-foreground">Gesamtanzahl im Jahr {jahr}</p>
            </CardHeader>
            <CardContent>
              {reasonsData.length > 0 ? (
                <div className="space-y-4 pt-4">
                  {reasonsData.map((item, idx) => (
                    <div key={item.name} className="space-y-1.5">
                      <div className="flex items-center justify-between text-sm">
                        <span className="font-medium">{item.name}</span>
                        <span className="text-muted-foreground tabular-nums">{item.value}</span>
                      </div>
                      <div className="h-3 w-full rounded-full bg-muted overflow-hidden">
                        <div
                          className="h-full rounded-full transition-all duration-300"
                          style={{
                            width: `${(item.value / reasonsMax) * 100}%`,
                            backgroundColor: CHART_COLORS[idx % CHART_COLORS.length],
                          }}
                        />
                      </div>
                    </div>
                  ))}

                  {/* Summary */}
                  {data && (
                    <div className="pt-4 border-t mt-4 space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Therapieänderung Ja</span>
                        <span className="font-medium tabular-nums">{data.kpis.ta_ja}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Therapieänderung Nein</span>
                        <span className="font-medium tabular-nums">{data.kpis.ta_nein}</span>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-muted-foreground text-center py-16">Keine Therapieänderungen erfasst.</p>
              )}
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  )
}

function KpiCard({ title, tooltip, value, icon }: { title: string; tooltip?: string; value: number; icon: React.ReactNode }) {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium">
          {tooltip ? (
            <UiTooltip>
              <TooltipTrigger asChild>
                <span className="inline-flex items-center gap-1 cursor-help">
                  {title}
                  <Info className="size-3 text-muted-foreground" />
                </span>
              </TooltipTrigger>
              <TooltipContent>{tooltip}</TooltipContent>
            </UiTooltip>
          ) : title}
        </CardTitle>
        {icon}
      </CardHeader>
      <CardContent>
        <div className="text-3xl font-bold">{value.toLocaleString('de-DE')}</div>
      </CardContent>
    </Card>
  )
}
