import { useState } from 'react'
import { ChevronDown, ChevronRight, Filter } from 'lucide-react'
import { useAuditLog } from '@/hooks/useAuditLog'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'

export function AdminAuditPage() {
  const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set())

  // Filters
  const [filterUserId, setFilterUserId] = useState('')
  const [filterAction, setFilterAction] = useState('')
  const [filterDateFrom, setFilterDateFrom] = useState('')
  const [filterDateTo, setFilterDateTo] = useState('')

  // Pagination
  const [skip, setSkip] = useState(0)
  const limit = 50

  const { data: entries = [], isLoading: loading } = useAuditLog({
    skip,
    limit,
    user_id: filterUserId,
    action: filterAction,
    date_from: filterDateFrom,
    date_to: filterDateTo,
  })

  const handleFilter = () => {
    setSkip(0)
  }

  const toggleExpanded = (id: number) => {
    setExpandedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }

  const resetFilters = () => {
    setFilterUserId('')
    setFilterAction('')
    setFilterDateFrom('')
    setFilterDateTo('')
    setSkip(0)
  }

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

      {/* Filters */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Filter className="h-4 w-4" />
            Filter
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap items-end gap-4">
            <div className="space-y-1">
              <Label htmlFor="filter-user">Benutzer-ID</Label>
              <Input
                id="filter-user"
                value={filterUserId}
                onChange={(e) => setFilterUserId(e.target.value)}
                placeholder="z.B. 1"
                className="w-28"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="filter-action">Aktion</Label>
              <Input
                id="filter-action"
                value={filterAction}
                onChange={(e) => setFilterAction(e.target.value)}
                placeholder="z.B. login"
                className="w-40"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="filter-from">Datum von</Label>
              <Input
                id="filter-from"
                type="date"
                value={filterDateFrom}
                onChange={(e) => setFilterDateFrom(e.target.value)}
                className="w-40"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="filter-to">Datum bis</Label>
              <Input
                id="filter-to"
                type="date"
                value={filterDateTo}
                onChange={(e) => setFilterDateTo(e.target.value)}
                className="w-40"
              />
            </div>
            <Button onClick={handleFilter}>Filtern</Button>
            <Button variant="outline" onClick={resetFilters}>Zurücksetzen</Button>
          </div>
        </CardContent>
      </Card>

      {/* Audit table */}
      {loading ? (
        <div className="space-y-2">
          {Array.from({ length: 8 }).map((_, i) => (
            <Skeleton key={i} className="h-10 w-full" />
          ))}
        </div>
      ) : entries.length > 0 ? (
        <>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-8" />
                <TableHead>Zeitpunkt</TableHead>
                <TableHead>Benutzer-ID</TableHead>
                <TableHead>Aktion</TableHead>
                <TableHead>Entität</TableHead>
                <TableHead>Details</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {entries.map((entry) => {
                const isExpanded = expandedIds.has(entry.id)
                const hasValues = entry.old_values || entry.new_values
                return (
                  <>
                    <TableRow
                      key={entry.id}
                      className={hasValues ? 'cursor-pointer' : ''}
                      onClick={() => hasValues && toggleExpanded(entry.id)}
                    >
                      <TableCell>
                        {hasValues && (
                          isExpanded
                            ? <ChevronDown className="h-4 w-4" />
                            : <ChevronRight className="h-4 w-4" />
                        )}
                      </TableCell>
                      <TableCell className="whitespace-nowrap">
                        {formatDateTime(entry.created_at)}
                      </TableCell>
                      <TableCell>
                        {entry.user_id !== null ? entry.user_id : '-'}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{entry.action}</Badge>
                      </TableCell>
                      <TableCell>
                        {entry.entity_type ? (
                          <span className="text-sm">
                            {entry.entity_type}
                            {entry.entity_id ? ` #${entry.entity_id}` : ''}
                          </span>
                        ) : (
                          '-'
                        )}
                      </TableCell>
                      <TableCell>
                        {entry.ip_address && (
                          <span className="text-xs text-muted-foreground font-mono">
                            {entry.ip_address}
                          </span>
                        )}
                      </TableCell>
                    </TableRow>
                    {isExpanded && hasValues && (
                      <TableRow key={`${entry.id}-details`}>
                        <TableCell colSpan={6} className="bg-muted/30 p-4">
                          <div className="grid gap-4 md:grid-cols-2">
                            {entry.old_values && (
                              <div>
                                <p className="text-sm font-medium mb-1">Alte Werte</p>
                                <pre className="text-xs bg-background rounded p-2 overflow-auto max-h-48 border">
                                  {JSON.stringify(entry.old_values, null, 2)}
                                </pre>
                              </div>
                            )}
                            {entry.new_values && (
                              <div>
                                <p className="text-sm font-medium mb-1">Neue Werte</p>
                                <pre className="text-xs bg-background rounded p-2 overflow-auto max-h-48 border">
                                  {JSON.stringify(entry.new_values, null, 2)}
                                </pre>
                              </div>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    )}
                  </>
                )
              })}
            </TableBody>
          </Table>

          {/* Pagination */}
          <div className="flex items-center justify-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={skip === 0}
              onClick={() => setSkip((s) => Math.max(0, s - limit))}
            >
              Zurück
            </Button>
            <span className="text-sm text-muted-foreground">
              Einträge {skip + 1} - {skip + entries.length}
            </span>
            <Button
              variant="outline"
              size="sm"
              disabled={entries.length < limit}
              onClick={() => setSkip((s) => s + limit)}
            >
              Weiter
            </Button>
          </div>
        </>
      ) : (
        <p className="py-8 text-center text-muted-foreground">
          Keine Audit-Einträge gefunden.
        </p>
      )}
    </div>
  )
}

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', second: '2-digit',
    })
  } catch {
    return dateStr
  }
}
