'use client';

import { useEffect, useState, useCallback } from 'react';
import {
  Monitor,
  Server,
  Database,
  Globe,
  Lock,
  FileJson,
  Cloud,
  HardDrive,
  RefreshCw,
} from 'lucide-react';
import { healthService, type HealthCheckResult } from '@/services/health.service';

type StatusIndicator = 'green' | 'yellow' | 'red';

interface StatusItem {
  label: string;
  icon: typeof Monitor;
  status: StatusIndicator;
  latency?: number;
  message?: string;
}

function getIndicator(status: string, message?: string): StatusIndicator {
  if (status === 'ok') return 'green';
  if (status === 'not-implemented' || status === 'not-ready') return 'yellow';
  return 'red';
}

const statusDotColors: Record<StatusIndicator, string> = {
  green: 'bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.4)]',
  yellow: 'bg-amber-400 shadow-[0_0_8px_rgba(251,191,36,0.4)]',
  red: 'bg-red-400 shadow-[0_0_8px_rgba(248,113,113,0.4)]',
};

const statusBgColors: Record<StatusIndicator, string> = {
  green: 'bg-emerald-500/5 border-emerald-500/10',
  yellow: 'bg-amber-500/5 border-amber-500/10',
  red: 'bg-red-500/5 border-red-500/10',
};

const statusTextColors: Record<StatusIndicator, string> = {
  green: 'text-emerald-400',
  yellow: 'text-amber-400',
  red: 'text-red-400',
};

export function SystemStatus() {
  const [statuses, setStatuses] = useState<StatusItem[]>([
    { label: 'Frontend', icon: Monitor, status: 'green', message: 'Client running' },
    { label: 'Backend', icon: Server, status: 'yellow', message: 'Checking...' },
    { label: 'Database', icon: Database, status: 'yellow', message: 'Checking...' },
    { label: 'API', icon: Globe, status: 'yellow', message: 'Checking...' },
    { label: 'Authentication', icon: Lock, status: 'green', message: 'JWT ready' },
    { label: 'Prisma', icon: FileJson, status: 'yellow', message: 'Checking...' },
    { label: 'Environment', icon: Cloud, status: 'green', message: process.env.NODE_ENV ?? 'development' },
    { label: 'Build', icon: HardDrive, status: 'green', message: 'Next.js 14' },
  ]);
  const [lastChecked, setLastChecked] = useState<Date | null>(null);
  const [isPolling, setIsPolling] = useState(true);

  const checkHealth = useCallback(async () => {
    try {
      const health: HealthCheckResult = await healthService.runAllHealthChecks();
      setStatuses([
        { label: 'Frontend', icon: Monitor, status: getIndicator(health.frontend.status), latency: health.frontend.latency, message: health.frontend.message },
        { label: 'Backend', icon: Server, status: getIndicator(health.backend.status), latency: health.backend.latency, message: health.backend.message },
        { label: 'Database', icon: Database, status: getIndicator(health.database.status), latency: health.database.latency, message: health.database.message },
        { label: 'API', icon: Globe, status: getIndicator(health.api.status), latency: health.api.latency, message: health.api.message },
        { label: 'Authentication', icon: Lock, status: getIndicator(health.authentication.status), latency: health.authentication.latency, message: health.authentication.message },
        { label: 'Prisma', icon: FileJson, status: getIndicator(health.prisma.status), latency: health.prisma.latency, message: health.prisma.message },
        { label: 'Environment', icon: Cloud, status: getIndicator(health.environment.status), latency: health.environment.latency, message: health.environment.message },
        { label: 'Build', icon: HardDrive, status: getIndicator(health.build.status), latency: health.build.latency, message: health.build.message },
      ]);
      setLastChecked(new Date());
    } catch {
      // Keep existing statuses on error
    }
  }, []);

  useEffect(() => {
    checkHealth();
    const interval = setInterval(() => {
      if (isPolling) checkHealth();
    }, 10000); // Poll every 10 seconds
    return () => clearInterval(interval);
  }, [checkHealth, isPolling]);

  const overallStatus: StatusIndicator =
    statuses.some((s) => s.status === 'red') ? 'red' :
    statuses.some((s) => s.status === 'yellow') ? 'yellow' :
    'green';

  return (
    <div className="rounded-xl border border-white/5 bg-slate-900/50">
      <div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
        <div className="flex items-center gap-2">
          <div className={`h-2 w-2 rounded-full ${statusDotColors[overallStatus]} ${
            overallStatus === 'green' ? 'animate-pulse' : ''
          }`} />
          <h3 className="text-xs font-semibold text-white">System Status</h3>
          <span className={`text-[10px] font-mono font-medium ${statusTextColors[overallStatus]}`}>
            {overallStatus === 'green' ? 'All Systems Operational' :
             overallStatus === 'yellow' ? 'Degraded Performance' :
             'System Issues Detected'}
          </span>
        </div>
        <div className="flex items-center gap-2">
          {lastChecked && (
            <span className="text-[10px] text-slate-500 font-mono">
              Last: {lastChecked.toLocaleTimeString()}
            </span>
          )}
          <button
            onClick={() => { setIsPolling(true); checkHealth(); }}
            className="rounded-lg p-1.5 text-slate-400 hover:bg-white/5 hover:text-white transition-colors"
            title="Refresh"
          >
            <RefreshCw className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 p-4">
        {statuses.map((item) => (
          <div
            key={item.label}
            className={`flex items-center gap-2.5 rounded-lg border px-3 py-2 ${statusBgColors[item.status]} transition-all duration-500`}
          >
            <item.icon className={`h-4 w-4 ${statusTextColors[item.status]}`} />
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-1.5">
                <span className={`text-[11px] font-medium ${statusTextColors[item.status]}`}>
                  {item.label}
                </span>
                <span className={`h-1.5 w-1.5 rounded-full ${statusDotColors[item.status]}`} />
              </div>
              <div className="flex items-center gap-1.5">
                {item.message && (
                  <span className="truncate text-[9px] text-slate-500 font-mono">{item.message}</span>
                )}
                {item.latency !== undefined && (
                  <span className="text-[9px] text-slate-600 font-mono">{item.latency}ms</span>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

