import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabaseClient';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Loader2 } from 'lucide-react';
import { format } from 'date-fns';
import { handleError } from '@/lib/errorHandler';
import { AuditLogEntry } from '@/types/database';

interface ProfileChangeField {
  field_name: string;
  old_value: string | null;
  new_value: string | null;
}

interface ProfileAuditLogWithChanges extends Omit<AuditLogEntry, 'changes'> {
  profile_change_fields?: ProfileChangeField[];
}

export function ProfileAuditLog(): React.JSX.Element {
  const [logs, setLogs] = useState<ProfileAuditLogWithChanges[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    void fetchAuditLogs();
  }, []);

  const fetchAuditLogs = async (): Promise<void> => {
    try {
      const { data, error } = await supabase
        .from('profile_audit_log')
        .select(`
          *,
          profiles!user_id(username, display_name),
          profile_change_fields(
            field_name,
            old_value,
            new_value
          )
        `)
        .order('created_at', { ascending: false })
        .limit(50);

      if (error) throw error;
      setLogs((data || []) as ProfileAuditLogWithChanges[]);
    } catch (error: unknown) {
      handleError(error, { action: 'Load audit logs' });
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center py-8">
          <Loader2 className="w-6 h-6 animate-spin" />
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Profile Audit Log</CardTitle>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>User</TableHead>
              <TableHead>Action</TableHead>
              <TableHead>Changes</TableHead>
              <TableHead>Date</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {logs.map((log) => (
              <TableRow key={log.id}>
                <TableCell>
                  {(log as { profiles?: { display_name?: string; username?: string } }).profiles?.display_name || (log as { profiles?: { username?: string } }).profiles?.username || 'Unknown'}
                </TableCell>
                <TableCell>
                  <Badge variant="secondary">{log.action}</Badge>
                </TableCell>
                <TableCell>
                  {log.profile_change_fields && log.profile_change_fields.length > 0 ? (
                    <div className="space-y-1">
                      {log.profile_change_fields.map((change, idx) => (
                        <div key={idx} className="text-xs">
                          <span className="font-medium">{change.field_name}:</span>{' '}
                          <span className="text-muted-foreground">{change.old_value || 'null'}</span>
                          {' → '}
                          <span className="text-foreground">{change.new_value || 'null'}</span>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <span className="text-xs text-muted-foreground">No changes</span>
                  )}
                </TableCell>
                <TableCell className="text-sm text-muted-foreground">
                  {format(new Date(log.created_at), 'PPpp')}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}
