import { useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
  PieChart, Pie, Cell, ResponsiveContainer,
} from 'recharts'
import { FileText, Clock, Code, Stethoscope, Info, TrendingUp, TrendingDown, Minus } from 'lucide-react'
import { useAuth } from '@/context/AuthContext'
import { useDashboard, useYearlyComparison, useTopIcd, useTopGutachter } 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 FALLGRUPPEN_LABELS: Record<string, string> = {
  onko: 'Onkologie',
  kardio: 'Kardiologie',
  intensiv: 'Intensivmedizin',
  galle: 'Gallenblase',
  sd: 'Schilddrüse',
}

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

const YEAR_COLORS: Record<string, string> = {
  '2022': 'var(--chart-4)',
  '2023': 'var(--chart-5)',
  '2024': 'var(--chart-2)',
  '2025': 'var(--chart-3)',
  '2026': 'var(--chart-1)',
}

export function DashboardPage() {
  const currentYear = new Date().getFullYear()
  const [jahr, setJahr] = useState(currentYear)
  const { data, isLoading: loading } = useDashboard(jahr)
  const { data: comparisonData } = useYearlyComparison()
  const { data: topIcdData } = useTopIcd(jahr)
  const { isAdmin } = useAuth()
  const { data: topGutachterData } = useTopGutachter(jahr, isAdmin)

  // Extract year keys from comparison data (e.g. ["2022", "2023", ...])
  const comparisonYears = useMemo(() => {
    if (!comparisonData?.data?.[0]) return []
    return Object.keys(comparisonData.data[0])
      .filter((k) => k !== 'kw')
      .sort()
  }, [comparisonData])

  // Filter out KWs where all years are 0
  const filteredComparison = useMemo(() => {
    if (!comparisonData?.data) return []
    return comparisonData.data.filter((row) =>
      comparisonYears.some((yr) => (row[yr] ?? 0) > 0)
    )
  }, [comparisonData, comparisonYears])

  // Top ICD with max for progress bars
  const topIcdMax = topIcdData?.items?.[0]?.count ?? 1

  // Top Gutachter with max for progress bars (admin only)
  const topGutachterMax = topGutachterData?.items?.[0]?.count ?? 1

  // Abrechnungsstatus donut data (admin only)
  const abrechnungsData = data ? [
    { name: 'Abgerechnet', value: data.kpis.total_abgerechnet },
    { name: 'Offen', value: data.kpis.pending_abrechnung },
  ].filter(d => d.value > 0) : []

  const fallgruppenData = data
    ? Object.entries(data.kpis.fallgruppen)
        .filter(([, value]) => value > 0)
        .map(([key, value]) => ({
          name: FALLGRUPPEN_LABELS[key] || key,
          value,
        }))
    : []

  const years = Array.from({ length: 5 }, (_, i) => currentYear - i)

  return (
    <div className="p-6 space-y-6">
      {/* Header with year selector */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Dashboard</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 */}
      {loading ? (
        <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="Fälle gesamt"
            tooltip="Gesamtzahl aller erfassten Fälle im gewählten Jahr"
            value={data.kpis.total_cases}
            prevValue={data.prev_kpis?.total_cases}
            prevYear={jahr - 1}
            icon={<FileText className="size-5 text-muted-foreground" />}
            href="/cases"
          />
          <KpiCard
            title="Offene ICD"
            tooltip="Fälle, denen noch ein ICD-10-Diagnosecode zugewiesen werden muss"
            value={data.kpis.pending_icd}
            prevValue={data.prev_kpis?.pending_icd}
            prevYear={jahr - 1}
            icon={<Clock className="size-5 text-muted-foreground" />}
            href="/icd"
          />
          <KpiCard
            title="Offene Codierung"
            tooltip="Fälle, die noch nicht abschließend klassifiziert wurden"
            value={data.kpis.pending_coding}
            prevValue={data.prev_kpis?.pending_coding}
            prevYear={jahr - 1}
            icon={<Code className="size-5 text-muted-foreground" />}
            href={isAdmin ? '/coding' : undefined}
          />
          <KpiCard
            title="Gutachten gesamt"
            tooltip="Anzahl der Fälle mit erstelltem Gutachten"
            value={data.kpis.total_gutachten}
            prevValue={data.prev_kpis?.total_gutachten}
            prevYear={jahr - 1}
            icon={<Stethoscope className="size-5 text-muted-foreground" />}
            href="/gutachten-statistik"
          />
        </div>
      ) : (
        <p className="text-muted-foreground">Keine Daten verfügbar.</p>
      )}

      {/* Charts row */}
      {data && (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          {/* Weekly bar chart - takes 2 cols */}
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle>Wöchentliche Übersicht</CardTitle>
              <p className="text-xs text-muted-foreground">Ablehnungen, fehlende Rückmeldungen und Gutachten pro Kalenderwoche</p>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={350}>
                <BarChart data={data.weekly}>
                  <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                  <XAxis
                    dataKey="kw"
                    tickFormatter={(v) => `KW ${v}`}
                    className="text-xs"
                  />
                  <YAxis className="text-xs" />
                  <Tooltip
                    labelFormatter={(v) => `KW ${v}`}
                    contentStyle={{
                      backgroundColor: 'var(--popover)',
                      border: '1px solid var(--border)',
                      borderRadius: '8px',
                      color: 'var(--popover-foreground)',
                    }}
                  />
                  <Legend />
                  <Bar
                    dataKey="ablehnungen"
                    name="Ablehnungen"
                    stackId="a"
                    fill="var(--chart-1)"
                    radius={[0, 0, 0, 0]}
                  />
                  <Bar
                    dataKey="keine_rm"
                    name="Keine Rückmeldung"
                    stackId="a"
                    fill="var(--chart-2)"
                  />
                  <Bar
                    dataKey="gutachten"
                    name="Gutachten"
                    stackId="a"
                    fill="var(--chart-3)"
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>

          {/* Fallgruppen pie chart */}
          <Card>
            <CardHeader>
              <CardTitle>Fallgruppen</CardTitle>
              <p className="text-xs text-muted-foreground">Verteilung der Fälle nach medizinischer Fachgruppe</p>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={350}>
                <PieChart>
                  <Pie
                    data={fallgruppenData}
                    cx="50%"
                    cy="45%"
                    innerRadius={50}
                    outerRadius={85}
                    paddingAngle={3}
                    dataKey="value"
                    label={({ value }) => value}
                  >
                    {fallgruppenData.map((_, idx) => (
                      <Cell
                        key={idx}
                        fill={CHART_COLORS[idx % CHART_COLORS.length]}
                      />
                    ))}
                  </Pie>
                  <Tooltip
                    contentStyle={{
                      backgroundColor: 'var(--popover)',
                      border: '1px solid var(--border)',
                      borderRadius: '8px',
                      color: 'var(--popover-foreground)',
                    }}
                  />
                  <Legend
                    verticalAlign="bottom"
                    iconType="circle"
                    iconSize={10}
                    formatter={(value: string) => (
                      <span style={{ color: 'var(--foreground)', fontSize: '13px' }}>{value}</span>
                    )}
                  />
                </PieChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Row 2: Yearly KW comparison + Top 10 ICD */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Yearly KW comparison bar chart */}
        {filteredComparison.length > 0 && (
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle>Jahresvergleich nach Kalenderwoche</CardTitle>
              <p className="text-xs text-muted-foreground">Anzahl Fälle pro KW im Vergleich ab 2022</p>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={350}>
                <BarChart data={filteredComparison}>
                  <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={{
                      backgroundColor: 'var(--popover)',
                      border: '1px solid var(--border)',
                      borderRadius: '8px',
                      color: 'var(--popover-foreground)',
                    }}
                  />
                  <Legend />
                  {comparisonYears.map((yr) => (
                    <Bar
                      key={yr}
                      dataKey={yr}
                      name={yr}
                      fill={YEAR_COLORS[yr] || 'var(--chart-1)'}
                      radius={[2, 2, 0, 0]}
                    />
                  ))}
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        )}

        {/* Top 10 ICD codes */}
        {topIcdData && topIcdData.items.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Top 10 ICD-Codes</CardTitle>
              <p className="text-xs text-muted-foreground">Häufigste Diagnosecodes in {jahr}</p>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {topIcdData.items.map((item, idx) => (
                  <div key={item.icd} className="space-y-1">
                    <div className="flex items-center justify-between text-sm">
                      <span className="font-mono font-medium">{item.icd}</span>
                      <span className="text-muted-foreground tabular-nums">{item.count}</span>
                    </div>
                    <div className="h-2 w-full rounded-full bg-muted overflow-hidden">
                      <div
                        className="h-full rounded-full transition-all duration-300"
                        style={{
                          width: `${(item.count / topIcdMax) * 100}%`,
                          backgroundColor: CHART_COLORS[idx % CHART_COLORS.length],
                        }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* Row 3: Admin-only — Abrechnungsstatus + Gutachter-Verteilung */}
      {isAdmin && data && (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          {/* Abrechnungsstatus Donut */}
          <Card>
            <CardHeader>
              <CardTitle>Abrechnungsstatus</CardTitle>
              <p className="text-xs text-muted-foreground">Gutachten: abgerechnet vs. offen</p>
            </CardHeader>
            <CardContent>
              {abrechnungsData.length > 0 ? (
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={abrechnungsData}
                      cx="50%"
                      cy="45%"
                      innerRadius={50}
                      outerRadius={85}
                      paddingAngle={3}
                      dataKey="value"
                      label={({ value }) => value}
                    >
                      <Cell fill="var(--chart-3)" />
                      <Cell fill="var(--chart-1)" />
                    </Pie>
                    <Tooltip
                      contentStyle={{
                        backgroundColor: 'var(--popover)',
                        border: '1px solid var(--border)',
                        borderRadius: '8px',
                        color: 'var(--popover-foreground)',
                      }}
                    />
                    <Legend
                      verticalAlign="bottom"
                      iconType="circle"
                      iconSize={10}
                      formatter={(value: string) => (
                        <span style={{ color: 'var(--foreground)', fontSize: '13px' }}>{value}</span>
                      )}
                    />
                  </PieChart>
                </ResponsiveContainer>
              ) : (
                <p className="text-sm text-muted-foreground py-8 text-center">Keine Gutachten für {jahr} vorhanden.</p>
              )}
            </CardContent>
          </Card>

          {/* Gutachter-Verteilung */}
          {topGutachterData && (
            <Card className="lg:col-span-2">
              <CardHeader>
                <CardTitle>Top 10 Gutachter</CardTitle>
                <p className="text-xs text-muted-foreground">Gutachten pro Gutachter in {jahr}</p>
              </CardHeader>
              <CardContent>
                {topGutachterData.items.length > 0 ? (
                  <div className="space-y-3">
                    {topGutachterData.items.map((item, idx) => (
                      <div key={item.gutachter} className="space-y-1">
                        <div className="flex items-center justify-between text-sm">
                          <span className="font-medium truncate max-w-[200px]">{item.gutachter}</span>
                          <span className="text-muted-foreground tabular-nums">{item.count}</span>
                        </div>
                        <div className="h-2 w-full rounded-full bg-muted overflow-hidden">
                          <div
                            className="h-full rounded-full transition-all duration-300"
                            style={{
                              width: `${(item.count / topGutachterMax) * 100}%`,
                              backgroundColor: CHART_COLORS[idx % CHART_COLORS.length],
                            }}
                          />
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground py-8 text-center">Keine Gutachter-Zuordnungen für {jahr} vorhanden.</p>
                )}
              </CardContent>
            </Card>
          )}
        </div>
      )}
    </div>
  )
}

function KpiCard({ title, tooltip, value, prevValue, prevYear, icon, href }: {
  title: string
  tooltip?: string
  value: number
  prevValue?: number
  prevYear?: number
  icon: React.ReactNode
  href?: string
}) {
  // Calculate percentage change vs previous year
  const change = prevValue != null && prevValue > 0
    ? ((value - prevValue) / prevValue) * 100
    : null

  const card = (
    <Card className={href ? 'transition-colors hover:border-primary/50 hover:shadow-md' : undefined}>
      <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>
        {prevValue != null && prevYear != null && (
          <div className="mt-1 flex items-center gap-1 text-xs">
            {change !== null ? (
              change > 0 ? (
                <>
                  <TrendingUp className="size-3 text-green-600" />
                  <span className="text-green-600 font-medium">+{Math.round(change)}%</span>
                </>
              ) : change < 0 ? (
                <>
                  <TrendingDown className="size-3 text-red-500" />
                  <span className="text-red-500 font-medium">{Math.round(change)}%</span>
                </>
              ) : (
                <>
                  <Minus className="size-3 text-muted-foreground" />
                  <span className="text-muted-foreground">0%</span>
                </>
              )
            ) : prevValue === 0 && value > 0 ? (
              <span className="text-muted-foreground">Neu in {prevYear + 1}</span>
            ) : (
              <span className="text-muted-foreground">—</span>
            )}
            {change !== null && (
              <span className="text-muted-foreground">ggü. {prevYear}</span>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  )

  if (href) {
    return <Link to={href} className="block">{card}</Link>
  }
  return card
}
