import { useState } from 'react'
import { Check, X, ShieldOff, RotateCcw, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import {
  useDisclosures, useReviewDisclosure, useAdminRevokeDisclosure,
  useAdminDeleteDisclosure, useAdminReactivateDisclosure,
} from '@/hooks/useDisclosures'
import type { DisclosureRequest } from '@/types'

type StatusFilter = 'all' | 'pending' | 'approved' | 'rejected'

function statusBadge(dr: DisclosureRequest) {
  const now = new Date()
  if (dr.status === 'pending') {
    return <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-300">Ausstehend</Badge>
  }
  if (dr.status === 'rejected') {
    return <Badge variant="outline" className="bg-red-50 text-red-700 border-red-300">Abgelehnt</Badge>
  }
  if (dr.expires_at && new Date(dr.expires_at) <= now) {
    return <Badge variant="outline" className="bg-gray-50 text-gray-500 border-gray-300">Abgelaufen</Badge>
  }
  return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-300">Genehmigt</Badge>
}

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

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

export function DisclosuresPage() {
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')
  const queryStatus = statusFilter === 'all' ? undefined : statusFilter
  const { data: requests = [], isLoading } = useDisclosures(queryStatus)
  const reviewMutation = useReviewDisclosure()
  const revokeMutation = useAdminRevokeDisclosure()
  const deleteMutation = useAdminDeleteDisclosure()
  const reactivateMutation = useAdminReactivateDisclosure()

  const handleReview = (id: number, status: 'approved' | 'rejected') => {
    reviewMutation.mutate({ id, status })
  }

  return (
    <div className="p-6 space-y-4">
      <h1 className="text-2xl font-bold">Freigabe-Anfragen</h1>

      <Tabs value={statusFilter} onValueChange={(v) => setStatusFilter(v as StatusFilter)}>
        <TabsList>
          <TabsTrigger value="all">Alle</TabsTrigger>
          <TabsTrigger value="pending">Ausstehend</TabsTrigger>
          <TabsTrigger value="approved">Genehmigt</TabsTrigger>
          <TabsTrigger value="rejected">Abgelehnt</TabsTrigger>
        </TabsList>
      </Tabs>

      {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">Keine Anfragen gefunden.</p>
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Fall-ID</TableHead>
                <TableHead>Antragsteller</TableHead>
                <TableHead>Begründung</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Datum</TableHead>
                <TableHead>Gültig bis</TableHead>
                <TableHead className="text-right">Aktionen</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {requests.map((dr) => (
                <TableRow key={dr.id}>
                  <TableCell className="font-medium">{dr.fall_id || `#${dr.case_id}`}</TableCell>
                  <TableCell>{dr.requester_username || `User #${dr.requester_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">
                      {dr.status === 'pending' && (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            disabled={reviewMutation.isPending}
                            onClick={() => handleReview(dr.id, 'approved')}
                          >
                            <Check className="size-4 mr-1" />
                            Genehmigen
                          </Button>
                          <Button
                            size="sm"
                            variant="destructive"
                            disabled={reviewMutation.isPending}
                            onClick={() => handleReview(dr.id, 'rejected')}
                          >
                            <X className="size-4 mr-1" />
                            Ablehnen
                          </Button>
                        </>
                      )}
                      {isActiveApproved(dr) && (
                        <Button
                          size="sm"
                          variant="outline"
                          disabled={revokeMutation.isPending}
                          onClick={() => revokeMutation.mutate(dr.id)}
                        >
                          <ShieldOff className="size-4 mr-1" />
                          Entziehen
                        </Button>
                      )}
                      {isExpiredApproved(dr) && (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            disabled={reactivateMutation.isPending}
                            onClick={() => reactivateMutation.mutate(dr.id)}
                          >
                            <RotateCcw className="size-4 mr-1" />
                            Wieder aufleben
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            disabled={deleteMutation.isPending}
                            onClick={() => deleteMutation.mutate(dr.id)}
                          >
                            <Trash2 className="size-4 mr-1" />
                            Verwerfen
                          </Button>
                        </>
                      )}
                      {dr.status === 'rejected' && (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            disabled={reactivateMutation.isPending}
                            onClick={() => reactivateMutation.mutate(dr.id)}
                          >
                            <RotateCcw className="size-4 mr-1" />
                            Wieder aufleben
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            disabled={deleteMutation.isPending}
                            onClick={() => deleteMutation.mutate(dr.id)}
                          >
                            <Trash2 className="size-4 mr-1" />
                            Verwerfen
                          </Button>
                        </>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}
    </div>
  )
}
