import { AlertTriangle, Globe, Info, Key, Lock, LogIn, Shield, UserX } from 'lucide-react';

import { useSecurityLogs } from '@/hooks/user/useSecurityLogs';

import { SectionHeading } from './primitives';

const EVENT_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
  login: LogIn,
  login_failed: UserX,
  password_changed: Lock,
  password_reset: Key,
  two_factor_disabled: Shield,
  two_factor_enabled: Shield,
  account_deleted: UserX,
  session_revoked: AlertTriangle,
};

function eventIcon(eventType: string) {
  const Icon = EVENT_ICONS[eventType] ?? Info;
  const isCritical =
    eventType.includes('failed') || eventType.includes('deleted') || eventType.includes('disabled');
  return (
    <Icon
      className={`size-4 shrink-0 ${isCritical ? 'text-destructive' : 'text-muted-foreground'}`}
    />
  );
}

function eventLabel(eventType: string) {
  return eventType.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

export function SecurityLogsTab() {
  const { data: logs, isLoading, error } = useSecurityLogs();

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load security logs.
        </div>
      </div>
    );
  }

  return (
    <div className="px-8 pt-10 pb-8 max-w-[680px]">
      <SectionHeading
        title="Security Log"
        description="A record of security-related events on your account. Review regularly for suspicious activity."
      />

      {(logs ?? []).length === 0 ? (
        <div className="rounded-lg border border-dashed border-border px-4 py-10 text-center">
          <Shield className="mx-auto size-8 text-border" />
          <p className="mt-2 text-[14px] text-muted-foreground">No security events recorded.</p>
        </div>
      ) : (
        <div className="space-y-1">
          {(logs ?? []).map((log) => (
            <div
              key={log.id}
              className="flex items-start gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-muted"
            >
              <div className="mt-0.5">{eventIcon(log.event_type)}</div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <p className="text-[14px] font-medium text-foreground">
                    {eventLabel(log.event_type)}
                  </p>
                  {log.event_type.includes('failed') && (
                    <span className="shrink-0 rounded-full bg-destructive/10 px-2 py-0.5 text-[11px] font-medium text-destructive">
                      Failed
                    </span>
                  )}
                </div>
                {log.description && (
                  <p className="mt-0.5 text-[13px] text-muted-foreground">{log.description}</p>
                )}
                <p className="mt-0.5 flex items-center gap-2 text-[12px] text-muted-foreground/60">
                  <span>{new Date(log.created_at).toLocaleString()}</span>
                  {log.ip_address && (
                    <>
                      <span className="text-border">·</span>
                      <Globe className="size-3" />
                      <span>{log.ip_address}</span>
                    </>
                  )}
                  {log.user_agent && (
                    <>
                      <span className="text-border">·</span>
                      <span className="truncate max-w-[200px]">{log.user_agent}</span>
                    </>
                  )}
                </p>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
