'use client';

import { useState, useEffect, useCallback } from 'react';

interface EndpointResult {
  loading: boolean;
  status: number | null;
  json: unknown;
  error: string | null;
  fetchedAt: string | null;
}

const defaultResult = (): EndpointResult => ({
  loading: false,
  status: null,
  json: null,
  error: null,
  fetchedAt: null,
});

export default function AIHealthPage() {
  const [ollamaHealth, setOllamaHealth] = useState<EndpointResult>(defaultResult());
  const [nodeHealth, setNodeHealth] = useState<EndpointResult>(defaultResult());

  const fetchEndpoint = useCallback(
    async (
      url: string,
      setter: React.Dispatch<React.SetStateAction<EndpointResult>>
    ) => {
      setter((prev) => ({ ...prev, loading: true, error: null }));
      try {
        const res = await fetch(url);
        const json = await res.json().catch(() => null);
        setter({
          loading: false,
          status: res.status,
          json,
          error: null,
          fetchedAt: new Date().toISOString(),
        });
      } catch (err) {
        setter({
          loading: false,
          status: null,
          json: null,
          error: err instanceof Error ? err.message : 'Fetch failed',
          fetchedAt: new Date().toISOString(),
        });
      }
    },
    []
  );

  const fetchAll = useCallback(() => {
    fetchEndpoint('/api/ai/ollama-health', setOllamaHealth);
    fetchEndpoint('/api/ai/node-health', setNodeHealth);
  }, [fetchEndpoint]);

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

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100 p-6">
      <div className="max-w-5xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-2xl font-bold text-white">AI Node Health</h1>
            <p className="text-gray-400 text-sm mt-1">
              Live responses from AI_001 health endpoints
            </p>
          </div>
          <button
            onClick={fetchAll}
            className="flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white text-sm font-medium rounded-lg transition-colors"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Refresh
          </button>
        </div>

        {/* Endpoint Cards */}
        <div className="grid grid-cols-1 gap-6">
          <EndpointCard
            title="GET /api/ai/ollama-health"
            description="Pings AI_001 at /ping — no auth required"
            result={ollamaHealth}
            onRefresh={() => fetchEndpoint('/api/ai/ollama-health', setOllamaHealth)}
          />
          <EndpointCard
            title="GET /api/ai/node-health"
            description="Calls AI_001 at /health — uses AI_NODE_API_KEY bearer token"
            result={nodeHealth}
            onRefresh={() => fetchEndpoint('/api/ai/node-health', setNodeHealth)}
          />
        </div>
      </div>
    </div>
  );
}

interface EndpointCardProps {
  title: string;
  description: string;
  result: EndpointResult;
  onRefresh: () => void;
}

function EndpointCard({ title, description, result, onRefresh }: EndpointCardProps) {
  const isOk =
    result.status !== null && result.status >= 200 && result.status < 300;
  const hasData = result.json !== null || result.error !== null;

  return (
    <div className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden">
      {/* Card Header */}
      <div className="flex items-start justify-between px-5 py-4 border-b border-gray-800">
        <div>
          <div className="flex items-center gap-3">
            <code className="text-indigo-400 font-mono text-sm font-semibold">{title}</code>
            {result.status !== null && (
              <span
                className={`px-2 py-0.5 rounded text-xs font-bold ${
                  isOk
                    ? 'bg-emerald-900/60 text-emerald-400 border border-emerald-700' :'bg-red-900/60 text-red-400 border border-red-700'
                }`}
              >
                HTTP {result.status}
              </span>
            )}
            {result.loading && (
              <span className="px-2 py-0.5 rounded text-xs font-bold bg-yellow-900/60 text-yellow-400 border border-yellow-700 animate-pulse">
                Loading…
              </span>
            )}
          </div>
          <p className="text-gray-500 text-xs mt-1">{description}</p>
        </div>
        <button
          onClick={onRefresh}
          disabled={result.loading}
          className="text-gray-500 hover:text-gray-300 transition-colors disabled:opacity-40 ml-4 mt-0.5"
          title="Refresh this endpoint"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
        </button>
      </div>

      {/* Raw JSON Output */}
      <div className="px-5 py-4">
        {result.loading && !hasData && (
          <div className="flex items-center gap-2 text-gray-500 text-sm py-4">
            <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
            </svg>
            Fetching…
          </div>
        )}

        {!result.loading && !hasData && (
          <p className="text-gray-600 text-sm py-4">No data yet.</p>
        )}

        {result.error && result.json === null && (
          <div className="bg-red-950/40 border border-red-800 rounded-lg p-4">
            <p className="text-red-400 text-sm font-mono">{result.error}</p>
          </div>
        )}

        {result.json !== null && (
          <pre className="bg-gray-950 border border-gray-800 rounded-lg p-4 text-sm font-mono text-green-300 overflow-x-auto whitespace-pre-wrap break-words leading-relaxed">
            {JSON.stringify(result.json, null, 2)}
          </pre>
        )}

        {result.fetchedAt && (
          <p className="text-gray-600 text-xs mt-2">
            Last fetched: {new Date(result.fetchedAt).toLocaleTimeString()}
          </p>
        )}
      </div>
    </div>
  );
}
