'use client';

import { useState, useEffect } from 'react';
import { Shield, User, Settings2, Key, CreditCard, Search, AlertTriangle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { mockAuditLog, type AuditEntry } from '@/lib/mock-data';
import { apiGetAudit } from '@/lib/api';

const categoryConfig: Record<
  AuditEntry['category'],
  { label: string; icon: typeof Shield; color: string }
> = {
  auth: { label: 'Auth', icon: Shield, color: 'bg-blue-50 text-blue-700' },
  user: { label: 'User', icon: User, color: 'bg-purple-50 text-purple-700' },
  config: { label: 'Config', icon: Settings2, color: 'bg-amber-50 text-amber-700' },
  token: { label: 'Token', icon: Key, color: 'bg-emerald-50 text-emerald-700' },
  billing: { label: 'Billing', icon: CreditCard, color: 'bg-pink-50 text-pink-700' },
};

function formatTimestamp(ts: string): string {
  const d = new Date(ts);
  return d.toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

export default function AuditLogPage() {
  const [entries, setEntries] = useState<AuditEntry[]>(mockAuditLog);
  const [search, setSearch] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('all');

  useEffect(() => {
    apiGetAudit().then(({ data }) => {
      if (data?.entries?.length) {
        setEntries(
          data.entries.map(e => ({
            id: e.id,
            category: e.category as AuditEntry['category'],
            action: e.action,
            actor: e.actor,
            target: e.target,
            ip: e.ip,
            timestamp: e.timestamp,
          }))
        );
      }
    });
  }, []);

  const filtered = entries.filter(entry => {
    const matchSearch =
      !search ||
      entry.actor.toLowerCase().includes(search.toLowerCase()) ||
      entry.action.toLowerCase().includes(search.toLowerCase()) ||
      (entry.target?.toLowerCase().includes(search.toLowerCase()) ?? false) ||
      (entry.details?.toLowerCase().includes(search.toLowerCase()) ?? false);
    const matchCategory = categoryFilter === 'all' || entry.category === categoryFilter;
    return matchSearch && matchCategory;
  });

  const failedLogins = entries.filter(e => e.action === 'Failed Login').length;
  const configChanges = entries.filter(e => e.category === 'config').length;
  const userActions = entries.filter(e => e.category === 'user').length;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Audit Log</h1>
        <p className="text-muted-foreground">
          Track all administrative actions and security events
        </p>
      </div>

      {/* Summary cards */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Total Events</CardTitle>
            <Shield className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{entries.length}</div>
            <p className="text-xs text-muted-foreground">Last 3 days</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Failed Logins</CardTitle>
            <AlertTriangle className="h-4 w-4 text-destructive" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-destructive">{failedLogins}</div>
            <p className="text-xs text-muted-foreground">Potential threats</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Config Changes</CardTitle>
            <Settings2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{configChanges}</div>
            <p className="text-xs text-muted-foreground">+ {userActions} user actions</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-3 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by actor, action, target…"
            className="pl-9"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
        <Select value={categoryFilter} onValueChange={setCategoryFilter}>
          <SelectTrigger className="w-[160px]">
            <SelectValue placeholder="Category" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Categories</SelectItem>
            <SelectItem value="auth">Auth</SelectItem>
            <SelectItem value="user">User</SelectItem>
            <SelectItem value="config">Config</SelectItem>
            <SelectItem value="token">Token</SelectItem>
            <SelectItem value="billing">Billing</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Table */}
      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[140px]">Time</TableHead>
                <TableHead>Actor</TableHead>
                <TableHead>Action</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Target</TableHead>
                <TableHead className="hidden lg:table-cell">Details</TableHead>
                <TableHead className="hidden md:table-cell">IP</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map(entry => {
                const cat = categoryConfig[entry.category];
                const isFailed = entry.action === 'Failed Login';
                return (
                  <TableRow key={entry.id} className={isFailed ? 'bg-destructive/5' : undefined}>
                    <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                      {formatTimestamp(entry.timestamp)}
                    </TableCell>
                    <TableCell className="text-sm font-medium">{entry.actor}</TableCell>
                    <TableCell className="text-sm">
                      {isFailed && (
                        <AlertTriangle className="mr-1 inline h-3.5 w-3.5 text-destructive" />
                      )}
                      {entry.action}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary" className={cat.color}>
                        <cat.icon className="mr-1 h-3 w-3" />
                        {cat.label}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {entry.target ?? '—'}
                    </TableCell>
                    <TableCell className="hidden lg:table-cell text-xs text-muted-foreground max-w-[200px] truncate">
                      {entry.details ?? '—'}
                    </TableCell>
                    <TableCell className="hidden md:table-cell font-mono text-xs text-muted-foreground">
                      {entry.ip}
                    </TableCell>
                  </TableRow>
                );
              })}
              {filtered.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="h-24 text-center text-muted-foreground">
                    No audit entries found.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
