import { Fragment, useCallback, useState } from 'react'
import { ChevronDown, ChevronRight, Download, FileSpreadsheet, Info, Loader2, Plus, Upload } from 'lucide-react'
import api from '@/services/api'
import { useAuth } from '@/context/AuthContext'
import {
  useReports,
  useReportData,
  useGenerateWochenuebersicht,
  useDeleteReports,
  useUploadWochenuebersichtIcd,
} from '@/hooks/useReports'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
  Tooltip, TooltipContent, TooltipTrigger,
} from '@/components/ui/tooltip'

const EXPORT_TYPES = [
  { value: 'c2s', label: 'Onko-Intensiv (c2s)' },
  { value: 'c2s_g_s', label: 'Galle-Schild (c2s_g_s)' },
] as const

const REPORT_TYPE_LABELS: Record<string, string> = {
  wochenuebersicht_c2s: 'Onko-Intensiv',
  'wochenuebersicht_c2s_g_s': 'Galle-Schild',
}

function getISOWeek(d: Date): number {
  const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()))
  const dayNum = date.getUTCDay() || 7
  date.setUTCDate(date.getUTCDate() + 4 - dayNum)
  const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1))
  return Math.ceil(((date.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7)
}

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
  }
}

export function WochenuebersichtPage() {
  const { isAdmin } = useAuth()
  const currentYear = new Date().getFullYear()
  const currentKw = getISOWeek(new Date())

  // Report list (only Wochenübersicht reports)
  const { data, isLoading: listLoading } = useReports('wochenuebersicht')
  const reports = data?.items ?? []

  // Generation form state (admin only)
  const [jahr, setJahr] = useState(currentYear)
  const [kwVon, setKwVon] = useState(1)
  const [kwBis, setKwBis] = useState(currentKw)
  const [exportType, setExportType] = useState('c2s')
  const [genError, setGenError] = useState('')
  const [genSuccess, setGenSuccess] = useState('')

  const generateMutation = useGenerateWochenuebersicht()
  const deleteMutation = useDeleteReports()

  // ICD Upload state
  const [uploadFile, setUploadFile] = useState<File | null>(null)
  const [uploadError, setUploadError] = useState('')
  const [uploadSuccess, setUploadSuccess] = useState('')
  const uploadMutation = useUploadWochenuebersichtIcd()

  // Inline expansion state
  const [expandedId, setExpandedId] = useState<number | null>(null)
  const { data: reportData, isLoading: reportDataLoading } = useReportData(expandedId)

  // Drag state
  const [isDragOver, setIsDragOver] = useState(false)

  const handleGenerate = async () => {
    setGenError('')
    setGenSuccess('')
    if (kwVon > kwBis) {
      setGenError('KW von darf nicht größer als KW bis sein.')
      return
    }
    try {
      const result = await generateMutation.mutateAsync({
        export_type: exportType, jahr, kw_von: kwVon, kw_bis: kwBis,
      })
      const typeLabel = REPORT_TYPE_LABELS[result.report_type] ?? result.report_type
      setGenSuccess(`Wochenübersicht "${typeLabel}" KW ${kwVon}–${kwBis}/${jahr} wurde generiert.`)
    } catch {
      setGenError('Fehler beim Generieren der Wochenübersicht.')
    }
  }

  const downloadReport = (reportId: number) => {
    api.get(`/reports/download/${reportId}`, { responseType: 'blob' })
      .then((res) => {
        const blob = new Blob([res.data as BlobPart], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        })
        const blobUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = blobUrl
        const contentDisposition = res.headers['content-disposition']
        let filename = `wochenuebersicht_${reportId}.xlsx`
        if (contentDisposition) {
          const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
          if (match) filename = match[1].replace(/['"]/g, '')
        }
        link.download = filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(blobUrl)
      })
      .catch(() => {
        const token = localStorage.getItem('access_token')
        if (token) {
          window.open(`/api/reports/download/${reportId}?token=${encodeURIComponent(token)}`, '_blank')
        }
      })
  }

  const handleUpload = async () => {
    if (!uploadFile) return
    setUploadError('')
    setUploadSuccess('')
    try {
      const result = await uploadMutation.mutateAsync(uploadFile)
      const errorCount = result.errors?.length ?? 0
      setUploadSuccess(
        `${result.updated} ICD-Codes aktualisiert.` +
        (errorCount > 0 ? ` ${errorCount} Fehler.` : ''),
      )
      setUploadFile(null)
    } catch {
      setUploadError('Fehler beim Hochladen der ICD-Datei.')
    }
  }

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragOver(false)
    const file = e.dataTransfer.files[0]
    if (file && (file.name.endsWith('.xlsx') || file.name.endsWith('.xls'))) {
      setUploadFile(file)
    }
  }, [])

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragOver(true)
  }, [])

  const handleDragLeave = useCallback(() => {
    setIsDragOver(false)
  }, [])

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-2xl font-bold">Wochenübersicht</h1>

      {/* Generation form (admin only) */}
      {isAdmin && (
        <Card>
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <FileSpreadsheet className="h-5 w-5" />
              Wochenübersicht generieren
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Erstellt eine Excel-Datei mit den Falldaten pro Kalenderwoche,
              die an die DAK zur ICD-Code-Eingabe gesendet wird.
            </p>

            <div className="flex flex-wrap items-end gap-4">
              <div className="space-y-1">
                <Label htmlFor="wu-jahr">Jahr</Label>
                <Input
                  id="wu-jahr"
                  type="number"
                  value={jahr}
                  onChange={(e) => setJahr(Number(e.target.value))}
                  className="w-28"
                  min={2020}
                  max={2030}
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="wu-kw-von">KW von</Label>
                <Input
                  id="wu-kw-von"
                  type="number"
                  value={kwVon}
                  onChange={(e) => setKwVon(Number(e.target.value))}
                  className="w-24"
                  min={1}
                  max={53}
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="wu-kw-bis">KW bis</Label>
                <Input
                  id="wu-kw-bis"
                  type="number"
                  value={kwBis}
                  onChange={(e) => setKwBis(Number(e.target.value))}
                  className="w-24"
                  min={1}
                  max={53}
                />
              </div>
              <div className="space-y-1">
                <Label>Exporttyp</Label>
                <Select value={exportType} onValueChange={setExportType}>
                  <SelectTrigger className="w-52">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {EXPORT_TYPES.map((t) => (
                      <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button onClick={handleGenerate} disabled={generateMutation.isPending}>
                {generateMutation.isPending ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Wird generiert...
                  </>
                ) : (
                  <>
                    <Plus className="mr-2 h-4 w-4" />
                    Generieren
                  </>
                )}
              </Button>
            </div>

            {genError && (
              <Alert variant="destructive">
                <AlertDescription>{genError}</AlertDescription>
              </Alert>
            )}
            {genSuccess && (
              <Alert>
                <AlertDescription>{genSuccess}</AlertDescription>
              </Alert>
            )}
          </CardContent>
        </Card>
      )}

      {/* Reports table (all roles) */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">
            Bisherige Wochenübersichten ({reports.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {listLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 3 }).map((_, i) => (
                <Skeleton key={i} className="h-10 w-full" />
              ))}
            </div>
          ) : reports.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Berichtsdatum</TableHead>
                  <TableHead>Jahr</TableHead>
                  <TableHead>KW</TableHead>
                  <TableHead>Typ</TableHead>
                  <TableHead>Erstellt am</TableHead>
                  <TableHead className="text-right">Aktion</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {reports.map((r) => {
                  const isExpanded = expandedId === r.id
                  return (
                    <Fragment key={r.id}>
                      <TableRow
                        className="cursor-pointer hover:bg-muted/50"
                        onClick={() => setExpandedId(isExpanded ? null : r.id)}
                      >
                        <TableCell>
                          <span className="inline-flex items-center gap-1.5">
                            {isExpanded
                              ? <ChevronDown className="size-4 text-muted-foreground" />
                              : <ChevronRight className="size-4 text-muted-foreground" />}
                            {formatDate(r.report_date)}
                          </span>
                        </TableCell>
                        <TableCell>{r.jahr}</TableCell>
                        <TableCell>KW {r.kw}</TableCell>
                        <TableCell>{REPORT_TYPE_LABELS[r.report_type] ?? r.report_type}</TableCell>
                        <TableCell>{formatDateTime(r.generated_at)}</TableCell>
                        <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => downloadReport(r.id)}
                          >
                            <Download className="mr-1.5 h-4 w-4" />
                            Download
                          </Button>
                          {isAdmin && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="ml-2 text-destructive"
                              onClick={async () => {
                                await deleteMutation.mutateAsync([r.id])
                              }}
                              disabled={deleteMutation.isPending}
                            >
                              Löschen
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                      {isExpanded && (
                        <TableRow>
                          <TableCell colSpan={6} className="p-0">
                            {reportDataLoading ? (
                              <div className="p-6">
                                <Skeleton className="h-48 w-full" />
                              </div>
                            ) : reportData ? (
                              <div className="p-4 border-t bg-muted/20">
                                <WochenuebersichtViewer data={reportData} />
                              </div>
                            ) : (
                              <div className="p-6 text-center text-muted-foreground">
                                Keine Vorschaudaten verfügbar.
                              </div>
                            )}
                          </TableCell>
                        </TableRow>
                      )}
                    </Fragment>
                  )
                })}
              </TableBody>
            </Table>
          ) : (
            <p className="py-8 text-center text-muted-foreground">
              Keine Wochenübersichten vorhanden.
            </p>
          )}
        </CardContent>
      </Card>

      {/* ICD Upload (all roles) */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Upload className="h-5 w-5" />
            ICD-Codes hochladen
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Laden Sie die ausgefüllte Wochenübersicht mit den ergänzten ICD-Codes hoch.
            Die ICD-Codes werden automatisch den Fällen anhand der KVNR zugeordnet.
          </p>
          <p className="text-xs text-muted-foreground">
            Unterstützte Formate: .xlsx, .xls — Die KVNR wird zum Abgleich der Fälle verwendet.
          </p>

          <div
            className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
              isDragOver
                ? 'border-primary bg-primary/5'
                : 'border-muted-foreground/25 hover:border-muted-foreground/50'
            }`}
            onDrop={handleDrop}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
          >
            {uploadFile ? (
              <div className="space-y-2">
                <p className="text-sm font-medium">{uploadFile.name}</p>
                <p className="text-xs text-muted-foreground">
                  {(uploadFile.size / 1024).toFixed(1)} KB
                </p>
                <div className="flex justify-center gap-2">
                  <Button size="sm" onClick={handleUpload} disabled={uploadMutation.isPending}>
                    {uploadMutation.isPending ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Wird importiert...
                      </>
                    ) : (
                      <>
                        <Upload className="mr-2 h-4 w-4" />
                        Hochladen
                      </>
                    )}
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => setUploadFile(null)}
                  >
                    Abbrechen
                  </Button>
                </div>
              </div>
            ) : (
              <div className="space-y-2">
                <p className="text-sm text-muted-foreground">
                  Excel-Datei hierher ziehen oder
                </p>
                <label>
                  <input
                    type="file"
                    accept=".xlsx,.xls"
                    className="hidden"
                    onChange={(e) => {
                      const file = e.target.files?.[0]
                      if (file) setUploadFile(file)
                    }}
                  />
                  <Button variant="outline" size="sm" asChild>
                    <span>Datei auswählen</span>
                  </Button>
                </label>
              </div>
            )}
          </div>

          {uploadError && (
            <Alert variant="destructive">
              <AlertDescription>{uploadError}</AlertDescription>
            </Alert>
          )}
          {uploadSuccess && (
            <Alert>
              <AlertDescription>{uploadSuccess}</AlertDescription>
            </Alert>
          )}
          {uploadMutation.data && (uploadMutation.data.errors?.length ?? 0) > 0 && (
            <Alert variant="destructive">
              <AlertDescription>
                <details>
                  <summary className="cursor-pointer">
                    {uploadMutation.data.errors.length} Fehler beim Import
                  </summary>
                  <ul className="mt-2 text-xs space-y-1">
                    {uploadMutation.data.errors.map((err, i) => (
                      <li key={i}>{err}</li>
                    ))}
                  </ul>
                </details>
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>
    </div>
  )
}


// ---------------------------------------------------------------------------
// Wochenübersicht Viewer (inline preview — individual cases per KW)
// ---------------------------------------------------------------------------

interface CaseRow {
  kvnr: string
  datum: string
  erstgespraech: boolean
  abbruch: boolean
  unterlagen: boolean
  gutachten: boolean
  fg1: boolean
  fg2: boolean
  icd: string
}

interface WeekBlock {
  kw: number
  cases: CaseRow[]
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function WochenuebersichtViewer({ data }: { data: Record<string, any> }) {
  const weeks: WeekBlock[] = data?.weeks ?? []
  const fg1Label: string = data?.fg1_label ?? 'FG1'
  const fg2Label: string = data?.fg2_label ?? 'FG2'

  if (!weeks.length || weeks.every((w) => w.cases.length === 0)) {
    return (
      <p className="py-4 text-center text-muted-foreground">
        Keine Vorschaudaten verfügbar.
      </p>
    )
  }

  const totalCases = weeks.reduce((sum, w) => sum + w.cases.length, 0)
  const totalIcd = weeks.reduce(
    (sum, w) => sum + w.cases.filter((c) => c.icd).length, 0,
  )

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-4 text-sm text-muted-foreground">
        <span>{totalCases} Fälle gesamt</span>
        <span>{totalIcd} mit ICD</span>
      </div>
      {weeks.map((week) => (
        <div key={week.kw}>
          <h4 className="text-sm font-semibold mb-1">
            KW {week.kw} — {week.cases.length} Fälle
          </h4>
          {week.cases.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="inline-flex items-center gap-1 cursor-help border-b border-dashed border-muted-foreground/40">
                          KVNR
                          <Info className="size-3 text-muted-foreground" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>Krankenversichertennummer</TooltipContent>
                    </Tooltip>
                  </TableHead>
                  <TableHead>Datum</TableHead>
                  <TableHead className="text-center">
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="inline-flex items-center gap-1 cursor-help border-b border-dashed border-muted-foreground/40">
                          Erstgespräch
                          <Info className="size-3 text-muted-foreground" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>Initialkontakt mit dem Versicherten erfolgt</TooltipContent>
                    </Tooltip>
                  </TableHead>
                  <TableHead className="text-center">
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="inline-flex items-center gap-1 cursor-help border-b border-dashed border-muted-foreground/40">
                          Abbruch
                          <Info className="size-3 text-muted-foreground" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>Zweitmeinung/Vorbereitung bei Ablehnung oder Abbruch</TooltipContent>
                    </Tooltip>
                  </TableHead>
                  <TableHead className="text-center">
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="inline-flex items-center gap-1 cursor-help border-b border-dashed border-muted-foreground/40">
                          Unterlagen
                          <Info className="size-3 text-muted-foreground" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>Zweitmeinung/Vorbereitung mit Erteilung</TooltipContent>
                    </Tooltip>
                  </TableHead>
                  <TableHead className="text-center">
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="inline-flex items-center gap-1 cursor-help border-b border-dashed border-muted-foreground/40">
                          Gutachten
                          <Info className="size-3 text-muted-foreground" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>Schriftliche Dokumentation (Gutachten) erstellt</TooltipContent>
                    </Tooltip>
                  </TableHead>
                  <TableHead className="text-center">{fg1Label}</TableHead>
                  <TableHead className="text-center">{fg2Label}</TableHead>
                  <TableHead>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="inline-flex items-center gap-1 cursor-help border-b border-dashed border-muted-foreground/40">
                          ICD-10
                          <Info className="size-3 text-muted-foreground" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>Internationale Klassifikation der Krankheiten</TooltipContent>
                    </Tooltip>
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {week.cases.map((c, i) => (
                  <TableRow key={i}>
                    <TableCell className="font-mono text-xs">{c.kvnr || '—'}</TableCell>
                    <TableCell className="text-xs">{c.datum}</TableCell>
                    <TableCell className="text-center">{c.erstgespraech ? 'x' : ''}</TableCell>
                    <TableCell className="text-center">{c.abbruch ? 'x' : ''}</TableCell>
                    <TableCell className="text-center">{c.unterlagen ? 'x' : ''}</TableCell>
                    <TableCell className="text-center">{c.gutachten ? 'x' : ''}</TableCell>
                    <TableCell className="text-center">{c.fg1 ? 'x' : ''}</TableCell>
                    <TableCell className="text-center">{c.fg2 ? 'x' : ''}</TableCell>
                    <TableCell className="font-mono text-xs">{c.icd || ''}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <p className="text-xs text-muted-foreground">Keine Fälle in dieser KW.</p>
          )}
        </div>
      ))}
    </div>
  )
}
