'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { CheckCircle2, XCircle, AlertCircle } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { StatCardSkeleton } from '@/components/Skeletons';

type Detail = { label?: string; identity?: string; ok: boolean; error?: string; note?: string };
type Integration = { key: string; label: string; configured: boolean; detail: Detail[]; settingsPath: string | null };

export default function IntegrationsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const [integrations, setIntegrations] = useState<Integration[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/integrations/status', accessToken, appSecretProof);
      setIntegrations(d.integrations || []);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">Integrations &middot; System Health &bull; admin.lussavara.co.tz</h1>
      <p className="text-xs text-gray-500">One screen for what used to mean visiting Email, WhatsApp Manager, and Settings separately to piece together.</p>

      {loading ? <StatCardSkeleton count={4} /> : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {integrations.map((i) => (
            <div key={i.key} className="bg-white border border-brand-border rounded-xl p-4">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  {i.configured ? <CheckCircle2 size={16} className="text-emerald-500" /> : <XCircle size={16} className="text-gray-300" />}
                  <p className="text-sm font-semibold">{i.label}</p>
                </div>
                {i.settingsPath && <Link href={i.settingsPath} className="text-[10px] text-brand-red hover:underline">Manage &rarr;</Link>}
              </div>
              <div className="space-y-1 text-xs">
                {i.detail.map((d, idx) => (
                  <div key={idx} className="flex items-center gap-1.5">
                    {d.ok ? <CheckCircle2 size={12} className="text-emerald-500 shrink-0" /> : <AlertCircle size={12} className="text-amber-500 shrink-0" />}
                    <span>{d.identity || d.label}</span>
                    {d.error && <span className="text-red-500">— {d.error}</span>}
                    {d.note && <span className="text-gray-400">— {d.note}</span>}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
