'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  ShieldCheck,
  Users,
  Activity,
  AlertTriangle,
  Loader2,
  AlertCircle,
  RefreshCw,
  Eye,
  Lock,
  Unlock,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

interface SecurityOverview {
  totalUsers: number;
  mfaAdoptionPercent: number;
  providerDistribution: Record<string, number>;
  activeSessions: number;
  suspiciousEvents24h: number;
}

interface LoginEvent {
  id: string;
  eventType: string;
  method: string;
  ip: string;
  userAgent: string;
  riskScore: number;
  riskFactors: string[];
  createdAt: string;
  userId?: string;
  email?: string;
}

function getToken(): string | null {
  return typeof window !== 'undefined' ? localStorage.getItem('admin_access_token') : null;
}

function authHeaders(): Record<string, string> {
  const t = getToken();
  return t ? { Authorization: `Bearer ${t}` } : {};
}

function riskColor(score: number): string {
  if (score >= 80) return 'text-red-600 bg-red-50';
  if (score >= 50) return 'text-orange-600 bg-orange-50';
  if (score >= 25) return 'text-yellow-600 bg-yellow-50';
  return 'text-green-600 bg-green-50';
}

export default function SecurityDashboardPage() {
  const [overview, setOverview] = useState<SecurityOverview | null>(null);
  const [events, setEvents] = useState<LoginEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showSuspiciousOnly, setShowSuspiciousOnly] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const [overviewRes, eventsRes] = await Promise.all([
        fetch('/api/auth/security/overview', { headers: authHeaders() }),
        fetch(`/api/auth/login-events?limit=50${showSuspiciousOnly ? '&suspicious=true' : ''}`, {
          headers: authHeaders(),
        }),
      ]);

      if (overviewRes.ok) setOverview(await overviewRes.json());
      if (eventsRes.ok) setEvents(await eventsRes.json());
    } catch {
      setError('Failed to load security data');
    } finally {
      setLoading(false);
    }
  }, [showSuspiciousOnly]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleUnlock = async (userId: string) => {
    try {
      await fetch(`/api/auth/security/unlock`, {
        method: 'POST',
        headers: { ...authHeaders(), 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId }),
      });
      await fetchData();
    } catch {
      setError('Failed to unlock user');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Security Dashboard</h1>
          <p className="text-muted-foreground">
            Authentication overview and login event monitoring
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchData}>
          <RefreshCw className="mr-2 h-4 w-4" />
          Refresh
        </Button>
      </div>

      {error && (
        <div className="flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive">
          <AlertCircle className="h-4 w-4 shrink-0" />
          {error}
        </div>
      )}

      {/* Stats Cards */}
      {overview && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Total Users</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{overview.totalUsers}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">MFA Adoption</CardTitle>
              <ShieldCheck className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{overview.mfaAdoptionPercent}%</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Active Sessions</CardTitle>
              <Activity className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{overview.activeSessions}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium">Suspicious (24h)</CardTitle>
              <AlertTriangle className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div
                className={`text-2xl font-bold ${overview.suspiciousEvents24h > 0 ? 'text-red-600' : ''}`}
              >
                {overview.suspiciousEvents24h}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Provider Distribution */}
      {overview && Object.keys(overview.providerDistribution).length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-sm">Auth Provider Distribution</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-4">
              {Object.entries(overview.providerDistribution).map(([provider, count]) => (
                <div
                  key={provider}
                  className="flex items-center gap-2 rounded-full bg-muted px-3 py-1 text-sm"
                >
                  <Lock className="h-3 w-3" />
                  <span className="font-medium capitalize">{provider}</span>
                  <span className="text-muted-foreground">{count}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Login Events */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Recent Login Events</CardTitle>
            <Button
              variant={showSuspiciousOnly ? 'default' : 'outline'}
              size="sm"
              onClick={() => setShowSuspiciousOnly(!showSuspiciousOnly)}
            >
              <Eye className="mr-2 h-4 w-4" />
              {showSuspiciousOnly ? 'Showing suspicious' : 'Show suspicious only'}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {events.length === 0 ? (
            <p className="text-sm text-muted-foreground py-4 text-center">No login events found</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left text-muted-foreground">
                    <th className="pb-2 pr-4">Time</th>
                    <th className="pb-2 pr-4">Type</th>
                    <th className="pb-2 pr-4">Method</th>
                    <th className="pb-2 pr-4">IP</th>
                    <th className="pb-2 pr-4">Risk</th>
                    <th className="pb-2">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {events.map(evt => (
                    <tr key={evt.id} className="border-b last:border-0">
                      <td className="py-2 pr-4 text-xs text-muted-foreground">
                        {new Date(evt.createdAt).toLocaleString()}
                      </td>
                      <td className="py-2 pr-4">{evt.eventType}</td>
                      <td className="py-2 pr-4 capitalize">{evt.method}</td>
                      <td className="py-2 pr-4 font-mono text-xs">{evt.ip}</td>
                      <td className="py-2 pr-4">
                        <span
                          className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${riskColor(evt.riskScore)}`}
                        >
                          {evt.riskScore}
                        </span>
                        {evt.riskFactors.length > 0 && (
                          <span className="ml-1 text-xs text-muted-foreground">
                            {evt.riskFactors.join(', ')}
                          </span>
                        )}
                      </td>
                      <td className="py-2">
                        {evt.userId && evt.eventType === 'lockout' && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleUnlock(evt.userId!)}
                          >
                            <Unlock className="mr-1 h-3 w-3" />
                            Unlock
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
