'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Smartphone,
  Monitor,
  Tablet,
  Loader2,
  AlertCircle,
  Trash2,
  ShieldCheck,
  ShieldOff,
  Globe,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

interface Device {
  id: string;
  name: string;
  platform: string;
  trustLevel: 'trusted' | 'remembered' | 'unknown';
  trustExpiresAt: string | null;
  lastIp: string;
  lastLoginAt: string;
  createdAt: 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 platformIcon(platform: string) {
  const p = platform.toLowerCase();
  if (p.includes('mobile') || p.includes('ios') || p.includes('android')) return Smartphone;
  if (p.includes('tablet') || p.includes('ipad')) return Tablet;
  if (p.includes('web') || p.includes('browser')) return Globe;
  return Monitor;
}

function trustBadge(level: Device['trustLevel']) {
  switch (level) {
    case 'trusted':
      return (
        <span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-2 py-0.5 text-xs font-medium text-green-700">
          <ShieldCheck className="h-3 w-3" />
          Trusted
        </span>
      );
    case 'remembered':
      return (
        <span className="inline-flex items-center gap-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">
          <ShieldCheck className="h-3 w-3" />
          Remembered
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600">
          <ShieldOff className="h-3 w-3" />
          Unknown
        </span>
      );
  }
}

export default function DeviceManagementPage() {
  const [devices, setDevices] = useState<Device[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchDevices = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/auth/devices', { headers: authHeaders() });
      if (res.ok) {
        setDevices(await res.json());
      } else {
        setError('Failed to load devices');
      }
    } catch {
      setError('Service unavailable');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleRevoke = async (deviceId: string) => {
    if (!confirm('Revoke this device? It will need to re-authenticate.')) return;
    try {
      const res = await fetch(`/api/auth/devices/${deviceId}`, {
        method: 'DELETE',
        headers: authHeaders(),
      });
      if (res.ok) {
        setDevices(prev => prev.filter(d => d.id !== deviceId));
      } else {
        setError('Failed to revoke device');
      }
    } catch {
      setError('Service unavailable');
    }
  };

  const handleRevokeAll = async () => {
    if (!confirm('Revoke ALL devices? Every session will be logged out.')) return;
    try {
      const res = await fetch('/api/auth/devices', {
        method: 'DELETE',
        headers: authHeaders(),
      });
      if (res.ok) {
        setDevices([]);
      } else {
        setError('Failed to revoke devices');
      }
    } catch {
      setError('Service unavailable');
    }
  };

  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">Device Management</h1>
          <p className="text-muted-foreground">View and manage trusted devices for your account</p>
        </div>
        {devices.length > 1 && (
          <Button variant="destructive" size="sm" onClick={handleRevokeAll}>
            <Trash2 className="mr-2 h-4 w-4" />
            Revoke all
          </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>
      )}

      {devices.length === 0 ? (
        <Card>
          <CardContent className="py-8 text-center text-muted-foreground">
            No devices found
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {devices.map(device => {
            const Icon = platformIcon(device.platform);
            return (
              <Card key={device.id}>
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
                        <Icon className="h-5 w-5 text-muted-foreground" />
                      </div>
                      <div>
                        <CardTitle className="text-base">
                          {device.name || 'Unknown Device'}
                        </CardTitle>
                        <CardDescription>
                          {device.platform} · {device.lastIp}
                        </CardDescription>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {trustBadge(device.trustLevel)}
                      <Button variant="ghost" size="sm" onClick={() => handleRevoke(device.id)}>
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="flex gap-6 text-xs text-muted-foreground">
                    <div>Last login: {new Date(device.lastLoginAt).toLocaleString()}</div>
                    <div>First seen: {new Date(device.createdAt).toLocaleString()}</div>
                    {device.trustExpiresAt && (
                      <div>Trust expires: {new Date(device.trustExpiresAt).toLocaleString()}</div>
                    )}
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
