import { useState, useEffect } from 'react'
import { Save, CheckCircle, Loader2 } from 'lucide-react'
import api from '@/services/api'
import type { Case, CaseListResponse, CodingUpdatePayload } from '@/types'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription } from '@/components/ui/alert'

const FALLGRUPPEN_LABELS: Record<string, string> = {
  onko: 'Onkologie',
  kardio: 'Kardiologie',
  intensiv: 'Intensivmedizin',
  galle: 'Gallenblase',
  sd: 'Schilddrüse',
}

const FALLGRUPPEN_OPTIONS = [
  { value: '__all__', label: 'Alle Fallgruppen' },
  { value: 'onko', label: 'Onkologie' },
  { value: 'kardio', label: 'Kardiologie' },
  { value: 'intensiv', label: 'Intensivmedizin' },
  { value: 'galle', label: 'Gallenblase' },
  { value: 'sd', label: 'Schilddrüse' },
]

interface CodingFormState {
  gutachten_typ: string | null
  therapieaenderung: string | null
  ta_diagnosekorrektur: boolean
  ta_unterversorgung: boolean
  ta_uebertherapie: boolean
}

function getInitialFormState(c: Case): CodingFormState {
  return {
    gutachten_typ: c.gutachten_typ || null,
    therapieaenderung: c.therapieaenderung || null,
    ta_diagnosekorrektur: false,
    ta_unterversorgung: false,
    ta_uebertherapie: false,
  }
}

export function CodingPage() {
  const currentYear = new Date().getFullYear()
  const years = Array.from({ length: 5 }, (_, i) => currentYear - i)
  const [jahr, setJahr] = useState<string>('__all__')
  const [fallgruppe, setFallgruppe] = useState<string>('__all__')
  const [page, setPage] = useState(1)
  const [data, setData] = useState<CaseListResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [formStates, setFormStates] = useState<Record<number, CodingFormState>>({})
  const [savingIds, setSavingIds] = useState<Set<number>>(new Set())
  const [savedIds, setSavedIds] = useState<Set<number>>(new Set())
  const [errors, setErrors] = useState<Record<number, string>>({})

  // Fetch coding queue
  useEffect(() => {
    const controller = new AbortController()
    setLoading(true)
    const params: Record<string, string | number> = { page, per_page: 50 }
    if (fallgruppe !== '__all__') params.fallgruppe = fallgruppe
    if (jahr !== '__all__') params.jahr = Number(jahr)

    api.get<CaseListResponse>('/coding/queue', { params, signal: controller.signal })
      .then((res) => {
        setData(res.data)
        // Initialize form states for each case
        const states: Record<number, CodingFormState> = {}
        for (const c of res.data.items) {
          states[c.id] = getInitialFormState(c)
        }
        setFormStates(states)
        setSavedIds(new Set())
        setErrors({})
      })
      .catch(() => {
        if (!controller.signal.aborted) setData(null)
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false)
      })

    return () => controller.abort()
  }, [page, fallgruppe, jahr])

  const updateFormField = (caseId: number, field: keyof CodingFormState, value: unknown) => {
    setFormStates((prev) => ({
      ...prev,
      [caseId]: { ...prev[caseId], [field]: value },
    }))
    // Clear saved state when editing
    setSavedIds((prev) => {
      const next = new Set(prev)
      next.delete(caseId)
      return next
    })
  }

  const saveCase = async (caseId: number) => {
    const form = formStates[caseId]
    if (!form) return

    setSavingIds((prev) => new Set(prev).add(caseId))
    setErrors((prev) => {
      const next = { ...prev }
      delete next[caseId]
      return next
    })

    try {
      const payload: CodingUpdatePayload = {
        gutachten_typ: form.gutachten_typ,
        therapieaenderung: form.therapieaenderung,
        ta_diagnosekorrektur: form.ta_diagnosekorrektur,
        ta_unterversorgung: form.ta_unterversorgung,
        ta_uebertherapie: form.ta_uebertherapie,
      }
      await api.put(`/coding/${caseId}`, payload)
      setSavedIds((prev) => new Set(prev).add(caseId))
    } catch {
      setErrors((prev) => ({ ...prev, [caseId]: 'Fehler beim Speichern.' }))
    } finally {
      setSavingIds((prev) => {
        const next = new Set(prev)
        next.delete(caseId)
        return next
      })
    }
  }

  // Count coded cases on current page
  const codedCount = data
    ? data.items.filter((c) => savedIds.has(c.id) || c.gutachten_typ !== null).length
    : 0
  const grandTotal = data?.total ?? 0
  const activeFilters: string[] = []
  if (fallgruppe !== '__all__') activeFilters.push(FALLGRUPPEN_LABELS[fallgruppe] || fallgruppe)
  if (jahr !== '__all__') activeFilters.push(jahr)

  return (
    <div className="p-6 space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Coding-Warteschlange</h1>
          {!loading && data && (
            <p className="text-sm text-muted-foreground mt-0.5">
              {grandTotal} {grandTotal === 1 ? 'Fall' : 'Fälle'} offen
              {activeFilters.length > 0 && (
                <> — gefiltert nach <span className="font-medium text-foreground">{activeFilters.join(', ')}</span></>
              )}
            </p>
          )}
        </div>
        <div className="flex items-center gap-3">
          <Badge variant="outline" className="text-sm py-1 px-3">
            {codedCount} / {data?.items.length ?? 0} auf dieser Seite codiert
          </Badge>
          <Select value={jahr} onValueChange={(v) => { setJahr(v); setPage(1) }}>
            <SelectTrigger className="w-[130px]">
              <SelectValue placeholder="Jahr" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="__all__">Alle Jahre</SelectItem>
              {years.map((y) => (
                <SelectItem key={y} value={String(y)}>{y}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={fallgruppe} onValueChange={(v) => { setFallgruppe(v); setPage(1) }}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Fallgruppe" />
            </SelectTrigger>
            <SelectContent>
              {FALLGRUPPEN_OPTIONS.map((o) => (
                <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Progress bar */}
      {data && grandTotal > 0 && (
        <div className="h-2 w-full rounded-full bg-muted overflow-hidden">
          <div
            className="h-full rounded-full bg-primary transition-all duration-300"
            style={{ width: `${(codedCount / (data.items.length || 1)) * 100}%` }}
          />
        </div>
      )}

      {/* Cards */}
      {loading ? (
        <div className="grid gap-4 md:grid-cols-2">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-64 w-full rounded-lg" />
          ))}
        </div>
      ) : data && data.items.length > 0 ? (
        <div className="grid gap-4 md:grid-cols-2">
          {data.items.map((c) => {
            const form = formStates[c.id]
            if (!form) return null
            const isSaving = savingIds.has(c.id)
            const isSaved = savedIds.has(c.id)
            const error = errors[c.id]

            return (
              <Card key={c.id} className={isSaved ? 'border-green-300' : ''}>
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <CardTitle className="text-base">
                      {c.fall_id || `#${c.id}`} &mdash; {c.nachname}
                      {c.vorname ? `, ${c.vorname}` : ''}
                    </CardTitle>
                    {isSaved && (
                      <CheckCircle className="h-5 w-5 text-green-600 shrink-0" />
                    )}
                  </div>
                  <div className="flex flex-wrap gap-2 text-sm">
                    <Badge variant="outline">
                      {FALLGRUPPEN_LABELS[c.fallgruppe] || c.fallgruppe}
                    </Badge>
                    {c.icd && (
                      <Badge variant="secondary" className="font-mono">
                        {c.icd}
                      </Badge>
                    )}
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Gutachten-Typ */}
                  <div className="space-y-1">
                    <label className="text-sm font-medium">Gutachten-Typ</label>
                    <Select
                      value={form.gutachten_typ ?? '__none__'}
                      onValueChange={(v) =>
                        updateFormField(c.id, 'gutachten_typ', v === '__none__' ? null : v)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Auswählen..." />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="__none__">-- Auswählen --</SelectItem>
                        <SelectItem value="Bestätigung">Bestätigung</SelectItem>
                        <SelectItem value="Alternative">Alternative</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Therapieänderung */}
                  <div className="space-y-1">
                    <label className="text-sm font-medium">Therapieänderung</label>
                    <Select
                      value={form.therapieaenderung ?? '__none__'}
                      onValueChange={(v) =>
                        updateFormField(c.id, 'therapieaenderung', v === '__none__' ? null : v)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Auswählen..." />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="__none__">-- Auswählen --</SelectItem>
                        <SelectItem value="Ja">Ja</SelectItem>
                        <SelectItem value="Nein">Nein</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Checkboxes */}
                  <div className="space-y-2">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id={`diag-${c.id}`}
                        checked={form.ta_diagnosekorrektur}
                        onCheckedChange={(checked) =>
                          updateFormField(c.id, 'ta_diagnosekorrektur', !!checked)
                        }
                      />
                      <label htmlFor={`diag-${c.id}`} className="text-sm">
                        Diagnosekorrektur
                      </label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id={`unter-${c.id}`}
                        checked={form.ta_unterversorgung}
                        onCheckedChange={(checked) =>
                          updateFormField(c.id, 'ta_unterversorgung', !!checked)
                        }
                      />
                      <label htmlFor={`unter-${c.id}`} className="text-sm">
                        Unterversorgung
                      </label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id={`ueber-${c.id}`}
                        checked={form.ta_uebertherapie}
                        onCheckedChange={(checked) =>
                          updateFormField(c.id, 'ta_uebertherapie', !!checked)
                        }
                      />
                      <label htmlFor={`ueber-${c.id}`} className="text-sm">
                        Übertherapie
                      </label>
                    </div>
                  </div>

                  {error && (
                    <Alert variant="destructive">
                      <AlertDescription>{error}</AlertDescription>
                    </Alert>
                  )}

                  <Button
                    className="w-full"
                    onClick={() => saveCase(c.id)}
                    disabled={isSaving}
                  >
                    {isSaving ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Speichern...
                      </>
                    ) : isSaved ? (
                      <>
                        <CheckCircle className="mr-2 h-4 w-4" />
                        Gespeichert
                      </>
                    ) : (
                      <>
                        <Save className="mr-2 h-4 w-4" />
                        Speichern
                      </>
                    )}
                  </Button>
                </CardContent>
              </Card>
            )
          })}
        </div>
      ) : (
        <p className="text-muted-foreground py-8 text-center">
          Keine Fälle in der Warteschlange.
        </p>
      )}

      {/* Pagination */}
      {data && data.total > 50 && (
        <div className="flex items-center justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={page <= 1}
            onClick={() => setPage((p) => p - 1)}
          >
            Zurück
          </Button>
          <span className="text-sm text-muted-foreground">
            Seite {page} von {Math.ceil(data.total / 50)}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={page >= Math.ceil(data.total / 50)}
            onClick={() => setPage((p) => p + 1)}
          >
            Weiter
          </Button>
        </div>
      )}
    </div>
  )
}
