'use client';

import { useEffect, useState } from 'react';
import { Activity, CheckCircle, RefreshCw, ShieldAlert } from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

interface ServiceCheck {
  id: string;
  name: string;
  status: 'healthy' | 'degraded' | 'down' | 'maintenance';
  latency: number;
  version?: string;
  message?: string;
  lastChecked: string;
}

interface OpsStatus {
  overall: 'healthy' | 'degraded' | 'critical';
  timestamp: string;
  services: ServiceCheck[];
}

export default function OpsPage() {
  const [data, setData] = useState<OpsStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [_error, setError] = useState<string | null>(null);
  const [countdown, setCountdown] = useState(10);

  const fetchStatus = async () => {
    try {
      setLoading(true);
      const res = await fetch('/api/ops/status');
      if (!res.ok) throw new Error('Failed to fetch status');
      const json = await res.json();
      setData(json);
      setLastUpdated(new Date());
      setError(null);
    } catch (err) {
      setError(String(err));
    } finally {
      setLoading(false);
      setCountdown(10);
    }
  };

  useEffect(() => {
    fetchStatus();
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          fetchStatus(); // trigger refresh
          return 10;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'healthy':
        return 'bg-green-500/10 text-green-500 hover:bg-green-500/20';
      case 'degraded':
        return 'bg-yellow-500/10 text-yellow-500 hover:bg-yellow-500/20';
      case 'down':
        return 'bg-red-500/10 text-red-500 hover:bg-red-500/20';
      default:
        return 'bg-gray-500/10 text-gray-500';
    }
  };

  const getLatencyColor = (ms: number) => {
    if (ms < 100) return 'text-green-500';
    if (ms < 500) return 'text-yellow-500';
    return 'text-red-500';
  };

  return (
    <div className="flex-1 space-y-4 p-8 pt-6">
      <div className="flex items-center justify-between space-y-2">
        <h2 className="text-3xl font-bold tracking-tight">Mission Control</h2>
        <div className="flex items-center space-x-2">
          <Button variant="outline" size="sm" onClick={() => fetchStatus()}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh ({countdown}s)
          </Button>
        </div>
      </div>

      {/* Global Status Banner */}
      {data && (
        <Card
          className={`border-l-4 ${data.overall === 'healthy' ? 'border-l-green-500' : data.overall === 'degraded' ? 'border-l-yellow-500' : 'border-l-red-500'}`}
        >
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Global System Status</CardTitle>
            {data.overall === 'healthy' ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <ShieldAlert className="h-4 w-4 text-red-500" />
            )}
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold capitalize">{data.overall}</div>
            <p className="text-xs text-muted-foreground">
              Last updated: {lastUpdated?.toLocaleTimeString()}
            </p>
          </CardContent>
        </Card>
      )}

      {/* Service Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {data?.services.map(svc => (
          <Card key={svc.id}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{svc.name}</CardTitle>
              <Activity
                className={`h-4 w-4 ${svc.status === 'healthy' ? 'text-muted-foreground' : 'text-red-500 animate-pulse'}`}
              />
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between mb-2">
                <Badge variant="outline" className={getStatusColor(svc.status)}>
                  {svc.status}
                </Badge>
                <div className={`text-sm font-mono font-bold ${getLatencyColor(svc.latency)}`}>
                  {svc.latency}ms
                </div>
              </div>

              <div className="space-y-1 mt-3">
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">Uptime (30d)</span>
                  <span className="font-medium">99.9%</span>
                </div>
                <Progress value={svc.status === 'down' ? 0 : 99} className="h-1" />
              </div>

              {svc.message && (
                <div className="mt-3 rounded bg-muted p-2 text-xs font-mono text-destructive">
                  {svc.message}
                </div>
              )}

              <div className="mt-3 text-xs text-muted-foreground flex justify-between">
                <span>v{svc.version || '?'}</span>
                <span>{new Date(svc.lastChecked).toLocaleTimeString()}</span>
              </div>
            </CardContent>
          </Card>
        ))}

        {!data &&
          loading &&
          Array.from({ length: 5 }).map((_, i) => (
            <Card key={i}>
              <CardHeader>
                <Skeleton className="h-4 w-[150px]" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-[100px] w-full" />
              </CardContent>
            </Card>
          ))}
      </div>

      {/* Dependency Matrix (Static for now) */}
      <Card>
        <CardHeader>
          <CardTitle>Infrastructure Dependencies</CardTitle>
          <CardDescription>Status of external cloud providers and databases.</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Dependency</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Region</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow>
                <TableCell className="font-medium">Azure Cosmos DB</TableCell>
                <TableCell>Database</TableCell>
                <TableCell>West US 2</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="font-medium">Azure OpenAI</TableCell>
                <TableCell>AI Model</TableCell>
                <TableCell>Sweden Central</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="font-medium">Stripe API</TableCell>
                <TableCell>Payments</TableCell>
                <TableCell>Global</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
