import { useState, useEffect } from 'react';
import { ChevronDown, ChevronRight, History, Eye, Lock, Unlock, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Skeleton } from '@/components/ui/skeleton';
import { format } from 'date-fns';
import { supabase } from '@/lib/supabaseClient';
import { handleError } from '@/lib/errorHandler';

interface AuditLogEntry {
  id: string;
  action: string;
  moderator_id: string;
  submission_id: string | null;
  previous_status: string | null;
  new_status: string | null;
  notes: string | null;
  created_at: string;
  is_test_data: boolean | null;
}

interface AuditTrailViewerProps {
  submissionId: string;
}

export function AuditTrailViewer({ submissionId }: AuditTrailViewerProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isOpen && auditLogs.length === 0) {
      fetchAuditLogs();
    }
  }, [isOpen, submissionId]);

  const fetchAuditLogs = async () => {
    try {
      setLoading(true);
      
      const { data, error } = await supabase
        .from('moderation_audit_log')
        .select('*')
        .eq('submission_id', submissionId)
        .order('created_at', { ascending: false });

      if (error) throw error;
      setAuditLogs(data || []);
    } catch (error) {
      handleError(error, {
        action: 'Fetch Audit Trail',
        metadata: { submissionId }
      });
    } finally {
      setLoading(false);
    }
  };

  const getActionIcon = (action: string) => {
    switch (action) {
      case 'viewed':
        return <Eye className="h-4 w-4" />;
      case 'claimed':
      case 'locked':
        return <Lock className="h-4 w-4" />;
      case 'released':
      case 'unlocked':
        return <Unlock className="h-4 w-4" />;
      case 'approved':
        return <CheckCircle className="h-4 w-4" />;
      case 'rejected':
        return <XCircle className="h-4 w-4" />;
      case 'escalated':
        return <AlertCircle className="h-4 w-4" />;
      default:
        return <History className="h-4 w-4" />;
    }
  };

  const getActionColor = (action: string) => {
    switch (action) {
      case 'approved':
        return 'text-green-600 dark:text-green-400';
      case 'rejected':
        return 'text-red-600 dark:text-red-400';
      case 'escalated':
        return 'text-orange-600 dark:text-orange-400';
      case 'claimed':
      case 'locked':
        return 'text-blue-600 dark:text-blue-400';
      default:
        return 'text-muted-foreground';
    }
  };

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <CollapsibleTrigger className="flex items-center gap-2 text-sm font-medium hover:text-primary transition-colors w-full">
        {isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        <History className="h-4 w-4" />
        <span>Audit Trail</span>
        {auditLogs.length > 0 && (
          <Badge variant="outline" className="ml-auto">
            {auditLogs.length} action{auditLogs.length !== 1 ? 's' : ''}
          </Badge>
        )}
      </CollapsibleTrigger>
      
      <CollapsibleContent className="mt-3">
        <div className="bg-card rounded-lg border">
          {loading ? (
            <div className="p-4 space-y-3">
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
            </div>
          ) : auditLogs.length === 0 ? (
            <div className="p-4 text-sm text-muted-foreground text-center">
              No audit trail entries found
            </div>
          ) : (
            <div className="divide-y">
              {auditLogs.map((entry) => (
                <div key={entry.id} className="p-3 hover:bg-muted/50 transition-colors">
                  <div className="flex items-start gap-3">
                    <div className={`mt-0.5 ${getActionColor(entry.action)}`}>
                      {getActionIcon(entry.action)}
                    </div>
                    
                    <div className="flex-1 space-y-1">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-sm font-medium capitalize">
                          {entry.action.replace('_', ' ')}
                        </span>
                        <span className="text-xs text-muted-foreground font-mono">
                          {format(new Date(entry.created_at), 'MMM d, HH:mm:ss')}
                        </span>
                      </div>
                      
                      {(entry.previous_status || entry.new_status) && (
                        <div className="flex items-center gap-2 text-xs">
                          {entry.previous_status && (
                            <Badge variant="outline" className="capitalize">
                              {entry.previous_status}
                            </Badge>
                          )}
                          {entry.previous_status && entry.new_status && (
                            <span className="text-muted-foreground">→</span>
                          )}
                          {entry.new_status && (
                            <Badge variant="default" className="capitalize">
                              {entry.new_status}
                            </Badge>
                          )}
                        </div>
                      )}
                      
                      {entry.notes && (
                        <p className="text-xs text-muted-foreground bg-muted/50 p-2 rounded mt-2">
                          {entry.notes}
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}
