import { useState, ReactNode } from 'react';
import { Head } from '@inertiajs/react';
import { useQuery } from '@tanstack/react-query';
import AdminLayout from '@/layouts/AdminLayout';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { ScrollText, Search, Download } from 'lucide-react';
import { format } from 'date-fns';
import { exportToCSV } from '@/lib/csv-export';

const entityColors: Record<string, string> = {
  order: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  company: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
  course: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  delegate: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  certificate: 'bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-400',
  user: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
};

const AuditLogPage = () => {
  const [search, setSearch] = useState('');
  const [entityFilter, setEntityFilter] = useState('all');

  const { data: logs, isLoading } = useQuery({
    queryKey: ['audit-log', entityFilter],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (entityFilter !== 'all') params.set('entity_type', entityFilter);
      const res = await fetch(`/api/admin/activity-log?${params.toString()}`);
      if (!res.ok) return [];
      return res.json();
    },
  });

  const filtered = (logs as any[] | undefined)?.filter((l) => {
    if (!search) return true;
    const s = search.toLowerCase();
    return (
      l.action?.toLowerCase().includes(s) ||
      l.user_email?.toLowerCase().includes(s) ||
      l.entity_id?.toLowerCase().includes(s) ||
      JSON.stringify(l.details || {}).toLowerCase().includes(s)
    );
  }) || [];

  const handleExport = () => {
    exportToCSV(
      filtered.map((l) => ({
        timestamp: format(new Date(l.created_at), 'yyyy-MM-dd HH:mm:ss'),
        user_email: l.user_email || '',
        action: l.action,
        entity_type: l.entity_type,
        entity_id: l.entity_id || '',
        details: JSON.stringify(l.details || {}),
      })),
      `audit-log-${format(new Date(), 'yyyy-MM-dd')}`,
    );
  };

  return (
    <>
      <Head title="Audit Log" />
      <div>
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
              <ScrollText className="h-6 w-6" /> Audit Log
            </h1>
            <p className="text-sm text-muted-foreground">Track all system activity and changes</p>
          </div>
          <Button variant="outline" size="sm" onClick={handleExport} disabled={!filtered.length}>
            <Download className="h-4 w-4 mr-1.5" /> Export CSV
          </Button>
        </div>

        <div className="flex flex-col sm:flex-row gap-3 mb-6">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input placeholder="Search actions, users, entities..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
          </div>
          <Select value={entityFilter} onValueChange={setEntityFilter}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Entity Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Entities</SelectItem>
              <SelectItem value="order">Orders</SelectItem>
              <SelectItem value="company">Companies</SelectItem>
              <SelectItem value="course">Courses</SelectItem>
              <SelectItem value="delegate">Delegates</SelectItem>
              <SelectItem value="certificate">Certificates</SelectItem>
              <SelectItem value="user">Users</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[160px]">Timestamp</TableHead>
                <TableHead>User</TableHead>
                <TableHead>Action</TableHead>
                <TableHead>Entity</TableHead>
                <TableHead>Entity ID</TableHead>
                <TableHead>Details</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow><TableCell colSpan={6} className="text-center text-muted-foreground py-12">Loading...</TableCell></TableRow>
              ) : !filtered.length ? (
                <TableRow><TableCell colSpan={6} className="text-center text-muted-foreground py-12">No activity recorded yet.</TableCell></TableRow>
              ) : (
                filtered.map((log: any) => (
                  <TableRow key={log.id}>
                    <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                      {format(new Date(log.created_at), 'dd MMM yy HH:mm')}
                    </TableCell>
                    <TableCell className="text-sm">{log.user_email || 'System'}</TableCell>
                    <TableCell className="text-sm font-medium">{log.action}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className={`text-[10px] ${entityColors[log.entity_type] || ''}`}>
                        {log.entity_type}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-xs font-mono text-muted-foreground">
                      {log.entity_id ? `${log.entity_id.slice(0, 8)}…` : '—'}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground max-w-[200px] truncate">
                      {log.details && Object.keys(log.details).length > 0 ? JSON.stringify(log.details) : '—'}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>
    </>
  );
};

AuditLogPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default AuditLogPage;
