import { useState } from 'react'
import { ShieldOff, RefreshCw, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import {
  Dialog, DialogContent, DialogDescription, DialogFooter,
  DialogHeader, DialogTitle,
} from '@/components/ui/dialog'
import {
  useMyDisclosures, useRevokeDisclosure,
  useDeleteDisclosure, useRequestDisclosure,
} from '@/hooks/useDisclosures'
import {
  Tooltip, TooltipContent, TooltipTrigger,
} from '@/components/ui/tooltip'
import type { DisclosureRequest } from '@/types'

function statusBadge(dr: DisclosureRequest) {
  const now = new Date()
  if (dr.status === 'pending') {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-300 cursor-help">Ausstehend</Badge>
        </TooltipTrigger>
        <TooltipContent>Ihre Anfrage wird vom Administrator geprüft</TooltipContent>
      </Tooltip>
    )
  }
  if (dr.status === 'rejected') {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Badge variant="outline" className="bg-red-50 text-red-700 border-red-300 cursor-help">Abgelehnt</Badge>
        </TooltipTrigger>
        <TooltipContent>Der Administrator hat Ihre Anfrage abgelehnt</TooltipContent>
      </Tooltip>
    )
  }
  // approved
  if (dr.expires_at && new Date(dr.expires_at) <= now) {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Badge variant="outline" className="bg-gray-50 text-gray-500 border-gray-300 cursor-help">Abgelaufen</Badge>
        </TooltipTrigger>
        <TooltipContent>Die Freigabe ist nicht mehr gültig</TooltipContent>
      </Tooltip>
    )
  }
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Badge variant="outline" className="bg-green-50 text-green-700 border-green-300 cursor-help">Genehmigt</Badge>
      </TooltipTrigger>
      <TooltipContent>Personendaten sind bis zum Ablaufdatum sichtbar</TooltipContent>
    </Tooltip>
  )
}

function isActive(dr: DisclosureRequest): boolean {
  if (dr.status !== 'approved') return false
  if (!dr.expires_at) return false
  return new Date(dr.expires_at) > new Date()
}

function isInactive(dr: DisclosureRequest): boolean {
  if (dr.status === 'rejected') return true
  if (dr.status === 'approved' && dr.expires_at && new Date(dr.expires_at) <= new Date()) return true
  return false
}

export function MyDisclosuresPage() {
  const { data: requests = [], isLoading } = useMyDisclosures()
  const revokeMutation = useRevokeDisclosure()
  const deleteMutation = useDeleteDisclosure()
  const requestMutation = useRequestDisclosure()

  const [reRequestTarget, setReRequestTarget] = useState<DisclosureRequest | null>(null)
  const [reason, setReason] = useState('')

  const openReRequestDialog = (dr: DisclosureRequest) => {
    setReason(dr.reason)
    setReRequestTarget(dr)
  }

  const submitReRequest = () => {
    if (!reRequestTarget || !reason.trim()) return
    requestMutation.mutate(
      { caseId: reRequestTarget.case_id, reason: reason.trim() },
      { onSuccess: () => setReRequestTarget(null) },
    )
  }

  return (
    <div className="p-6 space-y-4">
      <div>
        <h1 className="text-2xl font-bold">Meine Freigaben</h1>
        <p className="text-sm text-muted-foreground mt-1">
          Übersicht Ihrer Freigabe-Anfragen für Personendaten. Genehmigte Freigaben sind 24 Stunden gültig.
        </p>
      </div>

      {isLoading ? (
        <div className="space-y-2">
          {[1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-12 w-full" />
          ))}
        </div>
      ) : requests.length === 0 ? (
        <p className="text-muted-foreground">Sie haben noch keine Freigaben angefragt.</p>
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Fall-ID</TableHead>
                <TableHead>Begründung</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Angefragt am</TableHead>
                <TableHead>Gültig bis</TableHead>
                <TableHead className="text-right">Aktion</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {requests.map((dr) => (
                <TableRow key={dr.id}>
                  <TableCell className="font-medium">{dr.fall_id || `#${dr.case_id}`}</TableCell>
                  <TableCell className="max-w-xs truncate">{dr.reason}</TableCell>
                  <TableCell>{statusBadge(dr)}</TableCell>
                  <TableCell>{new Date(dr.created_at).toLocaleDateString('de-DE')}</TableCell>
                  <TableCell>
                    {dr.expires_at
                      ? new Date(dr.expires_at).toLocaleString('de-DE')
                      : '—'}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      {isActive(dr) && (
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              size="sm"
                              variant="outline"
                              disabled={revokeMutation.isPending}
                              onClick={() => revokeMutation.mutate(dr.id)}
                            >
                              <ShieldOff className="size-4 mr-1" />
                              Als erledigt markieren
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>Freigabe vorzeitig beenden — Personendaten werden wieder ausgeblendet</TooltipContent>
                        </Tooltip>
                      )}
                      {isInactive(dr) && (
                        <>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                size="sm"
                                variant="outline"
                                disabled={requestMutation.isPending}
                                onClick={() => openReRequestDialog(dr)}
                              >
                                <RefreshCw className="size-4 mr-1" />
                                Erneute Anfrage
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>Neue Freigabe mit gleicher oder geänderter Begründung beantragen</TooltipContent>
                          </Tooltip>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button
                                size="sm"
                                variant="ghost"
                                disabled={deleteMutation.isPending}
                                onClick={() => deleteMutation.mutate(dr.id)}
                              >
                                <Trash2 className="size-4 mr-1" />
                                Verwerfen
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>Diese Freigabe-Anfrage aus Ihrer Liste entfernen</TooltipContent>
                          </Tooltip>
                        </>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={!!reRequestTarget} onOpenChange={(open) => { if (!open) setReRequestTarget(null) }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Erneute Freigabe-Anfrage</DialogTitle>
            <DialogDescription>
              Fall: {reRequestTarget?.fall_id || `#${reRequestTarget?.case_id}`}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-2">
            <label htmlFor="reason" className="text-sm font-medium">Begründung</label>
            <textarea
              id="reason"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              rows={3}
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              placeholder="Begründung für die erneute Anfrage..."
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setReRequestTarget(null)}>
              Abbrechen
            </Button>
            <Button
              disabled={!reason.trim() || requestMutation.isPending}
              onClick={submitReRequest}
            >
              Anfrage senden
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
