'use client';

import { useState, useEffect, useCallback } from 'react';
import { CheckCircle2, XCircle, AlertTriangle, RefreshCw } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';

interface ServiceStatus {
  name: string;
  status: string;
  latency?: number;
  lastChecked: string;
  url?: string;
}

const statusConfig: Record<string, { color: string; icon: typeof CheckCircle2 }> = {
  healthy: { color: 'bg-emerald-50 text-emerald-700', icon: CheckCircle2 },
  degraded: { color: 'bg-amber-50 text-amber-700', icon: AlertTriangle },
  down: { color: 'bg-red-50 text-red-700', icon: XCircle },
  unknown: { color: 'bg-gray-50 text-gray-600', icon: AlertTriangle },
};

export default function StatusPage() {
  const [services, setServices] = useState<ServiceStatus[]>([]);
  const [loading, setLoading] = useState(true);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const checks = [
        {
          name: 'Platform Service',
          url: process.env.NEXT_PUBLIC_PLATFORM_URL || '/api/settings/kill-switch',
        },
        { name: 'Admin Dashboard', url: '/api/health' },
      ];

      const results: ServiceStatus[] = [];
      for (const svc of checks) {
        const start = Date.now();
        try {
          const res = await fetch(svc.url, { signal: AbortSignal.timeout(5000) });
          results.push({
            name: svc.name,
            status: res.ok ? 'healthy' : 'degraded',
            latency: Date.now() - start,
            lastChecked: new Date().toISOString(),
            url: svc.url,
          });
        } catch {
          results.push({
            name: svc.name,
            status: 'down',
            latency: Date.now() - start,
            lastChecked: new Date().toISOString(),
            url: svc.url,
          });
        }
      }
      setServices(results);
    } catch {
      // ignore
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  const healthyCount = services.filter(s => s.status === 'healthy').length;
  const overallStatus =
    services.length === 0
      ? 'unknown'
      : healthyCount === services.length
        ? 'healthy'
        : healthyCount > 0
          ? 'degraded'
          : 'down';
  const overallCfg = statusConfig[overallStatus];
  const OverallIcon = overallCfg.icon;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Platform Status</h1>
          <p className="text-sm text-muted-foreground">
            Real-time health check of all platform services
          </p>
        </div>
        <Button variant="outline" onClick={loadData} disabled={loading}>
          <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} /> Refresh
        </Button>
      </div>

      <Card>
        <CardContent className="py-8">
          <div className="flex flex-col items-center gap-3">
            <OverallIcon
              className={`h-12 w-12 ${overallStatus === 'healthy' ? 'text-emerald-500' : overallStatus === 'degraded' ? 'text-amber-500' : 'text-red-500'}`}
            />
            <h2 className="text-xl font-bold">
              {overallStatus === 'healthy'
                ? 'All Systems Operational'
                : overallStatus === 'degraded'
                  ? 'Partial Degradation'
                  : 'Service Disruption'}
            </h2>
            <Badge className={`${overallCfg.color} border-0 text-sm`}>
              {overallStatus.toUpperCase()}
            </Badge>
          </div>
        </CardContent>
      </Card>

      <div className="space-y-3">
        {services.map(svc => {
          const cfg = statusConfig[svc.status] || statusConfig.unknown;
          const StatusIcon = cfg.icon;
          return (
            <Card key={svc.name}>
              <CardContent className="p-4 flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <StatusIcon
                    className={`h-5 w-5 ${svc.status === 'healthy' ? 'text-emerald-500' : svc.status === 'degraded' ? 'text-amber-500' : 'text-red-500'}`}
                  />
                  <div>
                    <p className="font-medium text-sm">{svc.name}</p>
                    {svc.url && (
                      <p className="text-xs text-muted-foreground font-mono">{svc.url}</p>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  {svc.latency != null && (
                    <span className="text-xs text-muted-foreground">{svc.latency}ms</span>
                  )}
                  <Badge className={`${cfg.color} border-0`}>{svc.status}</Badge>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
