import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { SkeletonRow } from '@/components/ui/Skeleton';
import { adminAPI } from '@/api/client';
import { formatRelativeTime } from '@/lib/constants';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function AuditLog() {
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminAPI.getAuditLog().then(({ data }) => {
      setLogs(data.logs || data.entries || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, []);

  const actionColors: Record<string, string> = {
    ban_user: 'danger',
    change_role: 'info',
    edit_elo_config: 'warning',
    unlink_steam: 'warning',
    cancel_match: 'danger',
  };

  return (
    <div className="p-6">
      <h1 className="text-xl font-bold text-text-primary mb-6">Audit Log</h1>

      {loading ? (
        <div className="space-y-3">{[...Array(8)].map((_, i) => <SkeletonRow key={i} />)}</div>
      ) : (
        <Card padding={false}>
          <motion.div variants={staggerContainer} initial="initial" animate="animate">
            {logs.map((log, i) => (
              <motion.div
                key={log.id || i}
                variants={staggerItem}
                className="flex items-start gap-4 px-5 py-3 border-b border-white/[0.03] last:border-0"
              >
                <Badge variant={(actionColors[log.action] as any) || 'default'}>
                  {(log.action || '').replace(/_/g, ' ')}
                </Badge>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-text-primary">
                    <span className="font-medium">{log.actor_name || 'System'}</span>
                    {log.target_name && (
                      <> on <span className="font-medium">{log.target_name}</span></>
                    )}
                  </p>
                  {log.details && (
                    <p className="text-xs text-text-muted mt-0.5 truncate">{JSON.stringify(log.details)}</p>
                  )}
                </div>
                <span className="text-xs text-text-muted flex-shrink-0">
                  {log.created_at ? formatRelativeTime(log.created_at) : ''}
                </span>
              </motion.div>
            ))}
            {logs.length === 0 && (
              <p className="px-5 py-8 text-center text-sm text-text-muted">No audit log entries</p>
            )}
          </motion.div>
        </Card>
      )}
    </div>
  );
}
