import { useState, useEffect, useCallback, useRef } from 'react'
import {
  Search, ChevronLeft, ChevronRight, Save, CheckCircle, XCircle,
} from 'lucide-react'
import api from '@/services/api'
import type { Case, CaseListResponse } from '@/types'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import {
  Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription,
} from '@/components/ui/sheet'
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' },
]

const ICD_OPTIONS = [
  { value: '__all__', label: 'Alle' },
  { value: 'true', label: 'Mit ICD' },
  { value: 'false', label: 'Ohne ICD' },
]

interface CasesPageProps {
  /** When true, fetches from pending-icd endpoint instead */
  pendingIcdOnly?: boolean
}

export function CasesPage({ pendingIcdOnly = false }: CasesPageProps) {
  const currentYear = new Date().getFullYear()
  const [search, setSearch] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')
  const [jahr, setJahr] = useState<string>('__all__')
  const [fallgruppe, setFallgruppe] = useState<string>('__all__')
  const [hasIcd, setHasIcd] = useState<string>('__all__')
  const [page, setPage] = useState(1)
  const [perPage] = useState(50)
  const [data, setData] = useState<CaseListResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [selectedCase, setSelectedCase] = useState<Case | null>(null)
  const [sheetOpen, setSheetOpen] = useState(false)

  // Debounce search
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const handleSearchChange = useCallback((val: string) => {
    setSearch(val)
    if (debounceRef.current) clearTimeout(debounceRef.current)
    debounceRef.current = setTimeout(() => {
      setDebouncedSearch(val)
      setPage(1)
    }, 300)
  }, [])

  useEffect(() => {
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current)
    }
  }, [])

  // Fetch cases
  useEffect(() => {
    setLoading(true)

    if (pendingIcdOnly) {
      api.get<CaseListResponse>('/cases/pending-icd', {
        params: { page, per_page: perPage },
      })
        .then((res) => setData(res.data))
        .catch(() => setData(null))
        .finally(() => setLoading(false))
    } else {
      const params: Record<string, string | number> = { page, per_page: perPage }
      if (debouncedSearch) params.search = debouncedSearch
      if (jahr !== '__all__') params.jahr = Number(jahr)
      if (fallgruppe !== '__all__') params.fallgruppe = fallgruppe
      if (hasIcd !== '__all__') params.has_icd = hasIcd

      api.get<CaseListResponse>('/cases/', { params })
        .then((res) => setData(res.data))
        .catch(() => setData(null))
        .finally(() => setLoading(false))
    }
  }, [page, perPage, debouncedSearch, jahr, fallgruppe, hasIcd, pendingIcdOnly])

  const totalPages = data ? Math.ceil(data.total / perPage) : 0
  const years = Array.from({ length: 5 }, (_, i) => currentYear - i)

  const openDetail = (c: Case) => {
    setSelectedCase(c)
    setSheetOpen(true)
  }

  const handleIcdSaved = (updated: Case) => {
    setSelectedCase(updated)
    // Refresh list
    setData((prev) =>
      prev
        ? {
            ...prev,
            items: prev.items.map((c) => (c.id === updated.id ? updated : c)),
          }
        : prev,
    )
  }

  return (
    <div className="p-6 space-y-4">
      <h1 className="text-2xl font-bold">
        {pendingIcdOnly ? 'ICD-Eingabe' : 'Fälle'}
      </h1>

      {/* Filter bar */}
      {!pendingIcdOnly && (
        <div className="flex flex-wrap items-center gap-3">
          <div className="relative flex-1 min-w-[200px] max-w-sm">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              placeholder="Suche nach Name, Fall-ID..."
              value={search}
              onChange={(e) => handleSearchChange(e.target.value)}
              className="pl-9"
            />
          </div>
          <Select value={jahr} onValueChange={(v) => { setJahr(v); setPage(1) }}>
            <SelectTrigger className="w-[120px]">
              <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-[170px]">
              <SelectValue placeholder="Fallgruppe" />
            </SelectTrigger>
            <SelectContent>
              {FALLGRUPPEN_OPTIONS.map((o) => (
                <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={hasIcd} onValueChange={(v) => { setHasIcd(v); setPage(1) }}>
            <SelectTrigger className="w-[130px]">
              <SelectValue placeholder="ICD" />
            </SelectTrigger>
            <SelectContent>
              {ICD_OPTIONS.map((o) => (
                <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Table */}
      {loading ? (
        <div className="space-y-2">
          {Array.from({ length: 8 }).map((_, i) => (
            <Skeleton key={i} className="h-10 w-full" />
          ))}
        </div>
      ) : data && data.items.length > 0 ? (
        <>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Fall-ID</TableHead>
                <TableHead>Datum</TableHead>
                <TableHead>Nachname</TableHead>
                <TableHead>Vorname</TableHead>
                <TableHead>KVNR</TableHead>
                <TableHead>Fallgruppe</TableHead>
                <TableHead>ICD</TableHead>
                <TableHead>Gutachten</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.items.map((c) => (
                <TableRow
                  key={c.id}
                  className="cursor-pointer"
                  onClick={() => openDetail(c)}
                >
                  <TableCell className="font-mono text-sm">
                    {c.fall_id || '-'}
                  </TableCell>
                  <TableCell>{formatDate(c.datum)}</TableCell>
                  <TableCell className="font-medium">{c.nachname}</TableCell>
                  <TableCell>{c.vorname || '-'}</TableCell>
                  <TableCell className="font-mono text-sm">
                    {c.kvnr || '-'}
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {FALLGRUPPEN_LABELS[c.fallgruppe] || c.fallgruppe}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {c.icd ? (
                      <span className="font-mono text-sm">{c.icd}</span>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell>
                    {c.gutachten ? (
                      <CheckCircle className="size-4 text-green-600" />
                    ) : (
                      <XCircle className="size-4 text-muted-foreground" />
                    )}
                  </TableCell>
                  <TableCell>
                    <StatusBadges c={c} />
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          {/* Pagination */}
          <div className="flex items-center justify-between">
            <p className="text-sm text-muted-foreground">
              {data.total} Fälle insgesamt
            </p>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                disabled={page <= 1}
                onClick={() => setPage((p) => p - 1)}
              >
                <ChevronLeft className="size-4" />
              </Button>
              <span className="text-sm">
                Seite {page} von {totalPages || 1}
              </span>
              <Button
                variant="outline"
                size="sm"
                disabled={page >= totalPages}
                onClick={() => setPage((p) => p + 1)}
              >
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        </>
      ) : (
        <p className="text-muted-foreground py-8 text-center">
          Keine Fälle gefunden.
        </p>
      )}

      {/* Detail Sheet */}
      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent className="w-full sm:max-w-lg overflow-y-auto">
          {selectedCase && (
            <CaseDetail
              caseData={selectedCase}
              onIcdSaved={handleIcdSaved}
            />
          )}
        </SheetContent>
      </Sheet>
    </div>
  )
}

function StatusBadges({ c }: { c: Case }) {
  return (
    <div className="flex gap-1">
      {c.unterlagen && <Badge variant="secondary" className="text-xs">Unterlagen</Badge>}
      {c.gutachten && <Badge variant="secondary" className="text-xs">Gutachten</Badge>}
      {c.abgerechnet && <Badge className="text-xs">Abgerechnet</Badge>}
      {c.ablehnung && <Badge variant="destructive" className="text-xs">Abgelehnt</Badge>}
      {c.abbruch && <Badge variant="destructive" className="text-xs">Abbruch</Badge>}
    </div>
  )
}

function CaseDetail({
  caseData,
  onIcdSaved,
}: {
  caseData: Case
  onIcdSaved: (updated: Case) => void
}) {
  const [icdValue, setIcdValue] = useState(caseData.icd || '')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  // Reset on case change
  useEffect(() => {
    setIcdValue(caseData.icd || '')
    setError('')
    setSuccess(false)
  }, [caseData.id, caseData.icd])

  const saveIcd = async () => {
    if (!icdValue.trim()) return
    setSaving(true)
    setError('')
    setSuccess(false)
    try {
      const res = await api.put<Case>(`/cases/${caseData.id}/icd`, { icd: icdValue.trim() })
      onIcdSaved(res.data)
      setSuccess(true)
    } catch {
      setError('Fehler beim Speichern des ICD-Codes.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <>
      <SheetHeader>
        <SheetTitle>
          Fall {caseData.fall_id || `#${caseData.id}`}
        </SheetTitle>
        <SheetDescription>
          {FALLGRUPPEN_LABELS[caseData.fallgruppe] || caseData.fallgruppe} &mdash; KW {caseData.kw}/{caseData.jahr}
        </SheetDescription>
      </SheetHeader>

      <div className="px-4 space-y-4">
        {/* Status badges */}
        <div className="flex flex-wrap gap-2">
          <StatusBadges c={caseData} />
        </div>

        {/* Patient info */}
        <div className="grid grid-cols-2 gap-3 text-sm">
          <DetailField label="Anrede" value={caseData.anrede} />
          <DetailField label="Vorname" value={caseData.vorname} />
          <DetailField label="Nachname" value={caseData.nachname} />
          <DetailField label="Geburtsdatum" value={caseData.geburtsdatum ? formatDate(caseData.geburtsdatum) : null} />
          <DetailField label="KVNR" value={caseData.kvnr} />
          <DetailField label="Versicherung" value={caseData.versicherung} />
        </div>

        {/* Case details */}
        <div className="border-t pt-3 grid grid-cols-2 gap-3 text-sm">
          <DetailField label="Datum" value={formatDate(caseData.datum)} />
          <DetailField label="KW / Jahr" value={`${caseData.kw} / ${caseData.jahr}`} />
          <DetailField label="CRM-Ticket" value={caseData.crm_ticket_id} />
          <DetailField label="Gutachter" value={caseData.gutachter} />
          <DetailField label="Gutachten-Typ" value={caseData.gutachten_typ} />
          <DetailField label="Therapieänderung" value={caseData.therapieaenderung} />
        </div>

        {/* ICD edit */}
        <div className="border-t pt-3 space-y-2">
          <label className="text-sm font-medium">ICD-Code</label>
          <div className="flex gap-2">
            <Input
              value={icdValue}
              onChange={(e) => { setIcdValue(e.target.value); setSuccess(false) }}
              placeholder="z.B. C50.9"
              className="flex-1"
            />
            <Button
              size="sm"
              onClick={saveIcd}
              disabled={saving || !icdValue.trim()}
            >
              <Save className="size-4 mr-1" />
              {saving ? 'Speichern...' : 'Speichern'}
            </Button>
          </div>
          {error && (
            <Alert variant="destructive">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
          {success && (
            <p className="text-sm text-green-600">ICD-Code gespeichert.</p>
          )}
        </div>

        {/* Description fields */}
        {caseData.kurzbeschreibung && (
          <div className="border-t pt-3 space-y-1">
            <label className="text-sm font-medium">Kurzbeschreibung</label>
            <p className="text-sm text-muted-foreground whitespace-pre-wrap">{caseData.kurzbeschreibung}</p>
          </div>
        )}
        {caseData.fragestellung && (
          <div className="space-y-1">
            <label className="text-sm font-medium">Fragestellung</label>
            <p className="text-sm text-muted-foreground whitespace-pre-wrap">{caseData.fragestellung}</p>
          </div>
        )}
        {caseData.kommentar && (
          <div className="space-y-1">
            <label className="text-sm font-medium">Kommentar</label>
            <p className="text-sm text-muted-foreground whitespace-pre-wrap">{caseData.kommentar}</p>
          </div>
        )}

        <div className="border-t pt-3 text-xs text-muted-foreground space-y-1">
          <p>Importiert: {formatDateTime(caseData.imported_at)}</p>
          <p>Aktualisiert: {formatDateTime(caseData.updated_at)}</p>
          {caseData.import_source && <p>Quelle: {caseData.import_source}</p>}
        </div>
      </div>
    </>
  )
}

function DetailField({ label, value }: { label: string; value: string | null | undefined }) {
  return (
    <div>
      <span className="text-muted-foreground">{label}</span>
      <p className="font-medium">{value || '-'}</p>
    </div>
  )
}

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleDateString('de-DE', {
      day: '2-digit', month: '2-digit', year: 'numeric',
    })
  } catch {
    return dateStr
  }
}

function formatDateTime(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleString('de-DE', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    })
  } catch {
    return dateStr
  }
}
