import React, { useEffect, useMemo, useState } from 'react';
import {
  Database, Cloud, RefreshCw, ShieldAlert, CheckCircle2, AlertTriangle,
  Building2, Server, Hash, Key, GitMerge, Layers,
  ArrowDownToLine, HardDrive
} from 'lucide-react';

interface SupabaseCloudLinkProps {
  api: any;
  tenants: any[];
}

function fmtDate(d: any): string {
  if (!d) return 'G��';
  const dt = new Date(d);
  return isNaN(dt.getTime()) ? 'G��' : dt.toLocaleString();
}

function maskSupabaseUrl(raw: string | null): string {
  if (!raw) return '(not configured)';
  try {
    const u = new URL(raw);
    return `${u.protocol}//${u.host}`;
  } catch {
    return '(malformed)';
  }
}

function ErrorBanner({ message }: { message: string }) {
  return (
    <div className="rounded-xl bg-rose-500/10 border border-rose-500/20 p-4 text-rose-500 font-mono text-xs">
      <AlertTriangle size={13} className="inline-block mr-1 -mt-0.5" />
      {message}
    </div>
  );
}

function EmptyState({ label }: { label: string }) {
  return (
    <div className="py-6 text-center text-muted-foreground font-mono text-xs">
      <Cloud size={18} className="inline-block mr-2 text-muted-foreground/60" />
      {label}
    </div>
  );
}

export function SupabaseCloudLink({ api, tenants }: SupabaseCloudLinkProps) {
  const [health, setHealth] = useState<any>(null);
  const [healthLoading, setHealthLoading] = useState(true);
  const [healthError, setHealthError] = useState<string | null>(null);

  const [cloudTenants, setCloudTenants] = useState<any[]>([]);
  const [cloudTenantsLoading, setCloudTenantsLoading] = useState(false);
  const [cloudTenantsError, setCloudTenantsError] = useState<string | null>(null);

  const [cloudLicenses, setCloudLicenses] = useState<any[]>([]);
  const [cloudLicensesLoading, setCloudLicensesLoading] = useState(false);
  const [cloudLicensesError, setCloudLicensesError] = useState<string | null>(null);

  const [reconcile, setReconcile] = useState<any>(null);
  const [reconcileLoading, setReconcileLoading] = useState(false);
  const [reconcileError, setReconcileError] = useState<string | null>(null);

  // Read-only status from the SuperAdmin server. The server reads
  // Supabase credentials from `superadmin/server/.env` at startup;
  // the UI has no input field to mutate them.
  const [config, setConfig] = useState<any>(null);
  const [configLoading, setConfigLoading] = useState(true);
  const [configError, setConfigError] = useState<string | null>(null);

  const supabaseUrl = useMemo(() => {
    if (typeof window !== 'undefined') {
      const envUrl = (window as any).__SUPABASE_URL__;
      if (envUrl) return envUrl as string;
    }
    return null;
  }, []);

  useEffect(() => {
    let cancelled = false;
    const fetchHealth = async () => {
      setHealthLoading(true);
      setHealthError(null);
      try {
        const res = await api.get('/health');
        if (!cancelled) setHealth(res?.data ?? null);
      } catch (err: any) {
        if (!cancelled) {
          setHealth(null);
          setHealthError(err?.message || 'request failed');
        }
      } finally {
        if (!cancelled) setHealthLoading(false);
      }
    };
    fetchHealth();
    return () => { cancelled = true; };
  }, [api]);

  let loadConfigCancelled = false;
  const loadConfig = async () => {
    setConfigLoading(true);
    try {
      const res = await api.get('/supabase/config');
      if (!loadConfigCancelled && res?.data?.ok) {
        setConfig(res.data);
      } else if (!loadConfigCancelled) {
        setConfig(null);
      }
    } catch (err) {
      if (!loadConfigCancelled) setConfig(null);
    } finally {
      if (!loadConfigCancelled) setConfigLoading(false);
    }
  };

  useEffect(() => {
    loadConfig();
    return () => { loadConfigCancelled = true; };
  }, [api]);

  const loadCloudTenants = async () => {
    setCloudTenantsLoading(true);
    setCloudTenantsError(null);
    try {
      let res = await api.get('/supabase/tenants');
      if (res?.status === 401) {
        await new Promise((r) => setTimeout(r, 200));
        res = await api.get('/supabase/tenants');
      }
      if (!res?.data?.ok) throw new Error(res?.data?.error || 'Pull failed');
      setCloudTenants(Array.isArray(res.data.data) ? res.data.data : []);
    } catch (err: any) {
      setCloudTenants([]);
      setCloudTenantsError(err?.response?.data?.error || err?.message || 'Failed to fetch cloud tenants');
    } finally {
      setCloudTenantsLoading(false);
    }
  };

  const loadCloudLicenses = async () => {
    setCloudLicensesLoading(true);
    setCloudLicensesError(null);
    try {
      let res = await api.get('/supabase/licenses');
      if (res?.status === 401) {
        await new Promise((r) => setTimeout(r, 200));
        res = await api.get('/supabase/licenses');
      }
      if (!res?.data?.ok) throw new Error(res?.data?.error || 'Pull failed');
      setCloudLicenses(Array.isArray(res.data.data) ? res.data.data : []);
    } catch (err: any) {
      setCloudLicenses([]);
      setCloudLicensesError(err?.response?.data?.error || err?.message || 'Failed to fetch cloud licenses');
    } finally {
      setCloudLicensesLoading(false);
    }
  };

  const runReconcile = async () => {
    setReconcileLoading(true);
    setReconcileError(null);
    try {
      let res = await api.post('/supabase/sync/pull', {});
      if (res?.status === 401) {
        await new Promise((r) => setTimeout(r, 200));
        res = await api.post('/supabase/sync/pull', {});
      }
      if (!res?.data?.ok) throw new Error(res?.data?.error || 'Reconcile failed');
      setReconcile(res.data);
    } catch (err: any) {
      setReconcile(null);
      setReconcileError(err?.response?.data?.error || err?.message || 'Reconciliation failed');
    } finally {
      setReconcileLoading(false);
    }
  };

  const onlineFlag = !!health && !healthError;
  const reconcileCounts = reconcile?.counts;
  const keySource = (config?.keySource || 'none') as 'env' | 'configured' | 'none';
  const hasUrl = !!config?.hasUrl;
  const hasKey = !!config?.hasKey;
  const configured = !!config?.configured;
  const canConnect = !!config?.canConnect;

  const statusColor = !hasUrl
    ? 'amber'
    : canConnect
      ? 'emerald'
      : 'rose';
  const statusLabel = !hasUrl
    ? 'URL missing'
    : canConnect
      ? 'Connected'
      : hasKey
        ? 'Key present but unverified'
        : 'No key configured';

  return (
    <div className="space-y-8">
      {/* Header */}
      <header className="flex flex-wrap items-center justify-between gap-4 pb-6 border-b border-border">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="text-2xl font-black tracking-tight text-foreground font-heading">
              Supabase <span className="text-primary">Cloud Link</span>
            </h1>
            <span className={`px-2.5 py-0.5 rounded-full text-xs font-mono font-bold border flex items-center gap-1 ${
              onlineFlag
                ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500'
                : 'bg-rose-500/10 border-rose-500/20 text-rose-500'
            }`}>
              <span className={`w-1.5 h-1.5 rounded-full inline-block ${onlineFlag ? 'bg-emerald-500 animate-pulse' : 'bg-rose-500'}`} />
              {onlineFlag ? 'CLOUD ONLINE' : 'CLOUD OFFLINE'}
            </span>
          </div>
          <p className="text-xs text-muted-foreground mt-1 font-medium">
            Direct multi-tenant upsert + storage bucket provisioning via @supabase/supabase-js
          </p>
        </div>
        <button
          onClick={() => {
            setHealth(null);
            setHealthLoading(true);
            setHealthError(null);
            api.get('/health')
              .then(res => setHealth(res?.data ?? null))
              .catch(err => { setHealth(null); setHealthError(err?.message || 'request failed'); })
              .finally(() => setHealthLoading(false));
          }}
          className="flex items-center gap-2 px-4 py-2.5 bg-card hover:bg-muted text-foreground rounded-xl text-xs font-bold transition-all border border-border shadow-sm"
        >
          <RefreshCw size={14} className={`text-primary ${healthLoading ? 'animate-spin' : ''}`} />
          <span>Re-ping Cloud</span>
        </button>
      </header>

      {/* Cloud Configuration (env-only) */}
      <section className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
          <div>
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Cloud Configuration (env-only)</h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              The SuperAdmin UI does not accept API keys. Set them in{' '}
              <code className="font-mono">superadmin/server/.env</code> and restart the process.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={loadConfig}
              disabled={configLoading}
              className="flex items-center gap-2 px-3 py-2 bg-card hover:bg-muted text-foreground rounded-xl text-xs font-bold transition-all border border-border shadow-sm disabled:opacity-50"
            >
              <RefreshCw size={13} className={`text-primary ${configLoading ? 'animate-spin' : ''}`} />
              <span>Refresh status</span>
            </button>
          </div>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className={`rounded-xl border p-3 ${
            statusColor === 'emerald' ? 'bg-emerald-500/10 border-emerald-500/20'
              : statusColor === 'amber' ? 'bg-amber-500/10 border-amber-500/20'
                : 'bg-rose-500/10 border-rose-500/20'
          }`}>
            <dt className={`text-[0.65rem] uppercase tracking-wider font-bold ${
              statusColor === 'emerald' ? 'text-emerald-500'
                : statusColor === 'amber' ? 'text-amber-500' : 'text-rose-500'
            }`}>Status</dt>
            <dd className={`text-sm font-black mt-1 font-mono flex items-center gap-1 ${
              statusColor === 'emerald' ? 'text-emerald-500'
                : statusColor === 'amber' ? 'text-amber-500' : 'text-rose-500'
            }`}>
              {statusColor === 'emerald' ? <CheckCircle2 size={13} /> : <AlertTriangle size={13} />}
              {statusLabel}
            </dd>
          </div>
          <div className="rounded-xl bg-muted/40 border border-border p-3">
            <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">URL</dt>
            <dd className="text-sm font-mono text-foreground mt-1 flex items-center gap-1">
              {hasUrl ? <CheckCircle2 size={13} className="text-emerald-500" /> : <AlertTriangle size={13} className="text-rose-500" />}
              <span>{hasUrl ? 'set' : 'missing'}</span>
            </dd>
          </div>
          <div className="rounded-xl bg-muted/40 border border-border p-3">
            <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Key</dt>
            <dd className="text-sm font-mono text-foreground mt-1 flex items-center gap-1">
              {hasKey ? <CheckCircle2 size={13} className="text-emerald-500" /> : <AlertTriangle size={13} className="text-rose-500" />}
              <span>{hasKey ? 'configured' : 'missing'}</span>
            </dd>
          </div>
          <div className="rounded-xl bg-muted/40 border border-border p-3">
            <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Source</dt>
            <dd className="text-sm font-mono text-foreground mt-1">
              <span className={`px-2 py-0.5 rounded-md border text-[0.7rem] font-bold ${
                keySource === 'env'
                  ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-500'
                  : 'bg-rose-500/10 border-rose-500/20 text-rose-500'
              }`}>{keySource === 'env' ? '.env' : 'none'}</span>
            </dd>
          </div>
        </div>

        {!hasKey && (
          <div className="mt-4 rounded-xl bg-amber-500/10 border border-amber-500/30 p-4 text-amber-500 font-mono text-xs flex items-start gap-2">
            <AlertTriangle size={14} className="mt-0.5 shrink-0" />
            <div>
              <strong>Supabase credentials missing.</strong> Set{' '}
              <code>SUPABASE_URL</code> and <code>SUPABASE_KEY</code> (or{' '}
              <code>VITE_SUPABASE_ANON_KEY</code>) in{' '}
              <code>superadmin/server/.env</code>, then restart the SuperAdmin server.
            </div>
          </div>
        )}

        {configError && (
          <div className="mt-4 rounded-xl bg-rose-500/10 border border-rose-500/20 p-4 text-rose-500 font-mono text-xs flex items-center gap-2">
            <AlertTriangle size={14} /> {configError}
          </div>
        )}
      </section>

      {/* Cloud Health + Configuration row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        {/* Health */}
        <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Cloud Health</h2>
            <Cloud size={18} className={onlineFlag ? 'text-emerald-500' : 'text-rose-500'} />
          </div>
          {healthLoading ? (
            <div className="py-6 text-center text-muted-foreground font-mono text-xs flex items-center justify-center gap-2">
              <RefreshCw size={14} className="animate-spin" /> Probing /api/health GǪ
            </div>
          ) : healthError || !health ? (
            <div className="rounded-xl bg-rose-500/10 border border-rose-500/20 p-4 text-rose-500 font-mono text-xs">
              Cloud link status: unreachable
              {healthError && <span className="block mt-1 text-rose-400/80">G�� {healthError}</span>}
            </div>
          ) : (
            <dl className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="rounded-xl bg-muted/40 border border-border p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Service</dt>
                <dd className="text-sm font-black text-foreground mt-1 font-mono">{health.service || health.name || 'superadmin'}</dd>
              </div>
              <div className="rounded-xl bg-muted/40 border border-border p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Status</dt>
                <dd className="text-sm font-black text-emerald-500 mt-1 font-mono flex items-center gap-1">
                  <CheckCircle2 size={13} /> {health.status || 'OK'}
                </dd>
              </div>
              <div className="rounded-xl bg-muted/40 border border-border p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Uptime</dt>
                <dd className="text-sm font-black text-foreground mt-1 font-mono">
                  {typeof health.uptime === 'number' ? `${health.uptime.toFixed(1)}s` : 'G��'}
                </dd>
              </div>
              <div className="rounded-xl bg-muted/40 border border-border p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Now (server)</dt>
                <dd className="text-sm font-black text-foreground mt-1 font-mono">
                  {health.now ? fmtDate(health.now) : fmtDate(new Date().toISOString())}
                </dd>
              </div>
              <div className="rounded-xl bg-muted/40 border border-border p-3 sm:col-span-2">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Raw Response</dt>
                <dd className="text-[0.7rem] text-foreground mt-1 font-mono break-all">
                  <pre className="whitespace-pre-wrap break-all">{JSON.stringify(health, null, 2)}</pre>
                </dd>
              </div>
            </dl>
          )}
        </div>

        {/* Configuration */}
        <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Cloud Configuration</h2>
            <Database size={18} className="text-primary" />
          </div>
          <div className="space-y-3">
            <div className="rounded-xl bg-muted/40 border border-border p-3">
              <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">SUPABASE_URL</dt>
              <dd className="text-sm font-mono text-foreground mt-1 break-all">{maskSupabaseUrl(supabaseUrl)}</dd>
              <p className="text-[0.65rem] text-muted-foreground mt-1 font-mono">
                Loaded from <code className="font-mono">SUPABASE_URL</code> in <code className="font-mono">superadmin/server/.env</code>.
              </p>
            </div>
            <div className="rounded-xl bg-muted/40 border border-border p-3">
              <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">SUPABASE_KEY (anon)</dt>
              <dd className="text-sm font-mono text-foreground mt-1 flex items-center gap-2">
                {hasKey ? (
                  <span className="text-emerald-500 font-bold uppercase tracking-wider text-xs flex items-center gap-1">
                    <CheckCircle2 size={13} /> CONFIGURED
                  </span>
                ) : (
                  <span className="text-rose-500 font-bold uppercase tracking-wider text-xs flex items-center gap-1">
                    <AlertTriangle size={13} /> MISSING
                  </span>
                )}
              </dd>
              <p className="text-[0.65rem] text-muted-foreground mt-1 font-mono">
                Value is never echoed. Set in <code className="font-mono">SUPABASE_KEY</code> (or{' '}
                <code className="font-mono">VITE_SUPABASE_ANON_KEY</code>) in{' '}
                <code className="font-mono">superadmin/server/.env</code> and restart the process. Writes go through SECURITY DEFINER RPC functions; the service-role key is never used.
              </p>
            </div>
            <div className="rounded-xl bg-muted/40 border border-border p-3">
              <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Tables Synced</dt>
              <dd className="text-sm font-mono text-foreground mt-1 flex items-center gap-2">
                <Hash size={12} className="text-muted-foreground" />
                <span>tenants</span>
                <span className="text-muted-foreground">-+</span>
                <span>tenant_licenses</span>
              </dd>
            </div>
            <div className="rounded-xl bg-muted/40 border border-border p-3">
              <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">Storage Buckets Created</dt>
              <dd className="text-sm font-mono text-foreground mt-1">
                <code>tenant-&lt;id&gt;</code> per tenant ({tenants.length} total bucket{tenants.length === 1 ? '' : 's'})
              </dd>
            </div>
          </div>
        </div>
      </div>

      <section className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
          <div>
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Cloud Tenants</h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              Fetched directly from Supabase <code className="font-mono">tenants</code> table.
            </p>
          </div>
          <button
            onClick={loadCloudTenants}
            disabled={cloudTenantsLoading || !canConnect}
            title={!canConnect ? 'Set SUPABASE_KEY (or VITE_SUPABASE_ANON_KEY) in superadmin/server/.env and restart the process.' : undefined}
            className="flex items-center gap-2 px-4 py-2 bg-card hover:bg-muted text-foreground rounded-xl text-xs font-bold transition-all border border-border shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <RefreshCw size={14} className={`text-primary ${cloudTenantsLoading ? 'animate-spin' : ''}`} />
            <span>Refresh</span>
          </button>
        </div>
        {cloudTenantsLoading ? (
          <div className="py-6 text-center text-muted-foreground font-mono text-xs flex items-center justify-center gap-2">
            <RefreshCw size={14} className="animate-spin" /> Pulling cloud tenants GǪ
          </div>
        ) : cloudTenantsError ? (
          <ErrorBanner message={cloudTenantsError} />
        ) : cloudTenants.length === 0 ? (
          <EmptyState label="Cloud is empty G�� no tenants in Supabase yet." />
        ) : (
          <div className="ng-table-container overflow-x-auto">
            <table className="ng-table min-w-[640px]">
              <thead className="ng-table-header">
                <tr>
                  <th>Name</th>
                  <th>Code</th>
                  <th>Status</th>
                  <th>Contact Email</th>
                  <th>Cloud ID</th>
                  <th>Created</th>
                </tr>
              </thead>
              <tbody>
                {cloudTenants.map(t => (
                  <tr key={t.id} className="ng-table-row">
                    <td className="ng-table-cell">
                      <div className="flex items-center gap-2">
                        <Building2 size={14} className="text-muted-foreground" />
                        <span className="font-bold text-foreground text-sm">{t.name || 'G��'}</span>
                      </div>
                    </td>
                    <td className="ng-table-cell font-mono text-xs">{t.code || 'G��'}</td>
                    <td className="ng-table-cell">
                      <span className={`ng-table-badge ${
                        t.status === 'active'
                          ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500'
                          : 'bg-amber-500/10 border-amber-500/20 text-amber-500'
                      }`}>
                        {t.status || 'G��'}
                      </span>
                    </td>
                    <td className="ng-table-cell font-mono text-xs">{t.contact_email || 'G��'}</td>
                    <td className="ng-table-cell font-mono text-xs break-all">{t.id}</td>
                    <td className="ng-table-cell font-mono text-xs">{fmtDate(t.created_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <section className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
          <div>
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Cloud Licenses</h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              Fetched directly from Supabase <code className="font-mono">tenant_licenses</code> table.
            </p>
          </div>
          <button
            onClick={loadCloudLicenses}
            disabled={cloudLicensesLoading || !canConnect}
            title={!canConnect ? 'Set SUPABASE_KEY (or VITE_SUPABASE_ANON_KEY) in superadmin/server/.env and restart the process.' : undefined}
            className="flex items-center gap-2 px-4 py-2 bg-card hover:bg-muted text-foreground rounded-xl text-xs font-bold transition-all border border-border shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <RefreshCw size={14} className={`text-primary ${cloudLicensesLoading ? 'animate-spin' : ''}`} />
            <span>Refresh</span>
          </button>
        </div>
        {cloudLicensesLoading ? (
          <div className="py-6 text-center text-muted-foreground font-mono text-xs flex items-center justify-center gap-2">
            <RefreshCw size={14} className="animate-spin" /> Pulling cloud licenses GǪ
          </div>
        ) : cloudLicensesError ? (
          <ErrorBanner message={cloudLicensesError} />
        ) : cloudLicenses.length === 0 ? (
          <EmptyState label="Cloud is empty G�� no licenses in Supabase yet." />
        ) : (
          <div className="ng-table-container overflow-x-auto">
            <table className="ng-table min-w-[820px]">
              <thead className="ng-table-header">
                <tr>
                  <th>License ID</th>
                  <th>Tenant</th>
                  <th>Algorithm</th>
                  <th>Status</th>
                  <th>Start</th>
                  <th>End</th>
                </tr>
              </thead>
              <tbody>
                {cloudLicenses.map(l => (
                  <tr key={l.id} className="ng-table-row">
                    <td className="ng-table-cell font-mono text-xs break-all">{l.id}</td>
                    <td className="ng-table-cell font-mono text-xs break-all">{l.tenant_id}</td>
                    <td className="ng-table-cell">
                      <span className="ng-table-badge bg-primary/10 border-primary/20 text-primary font-mono">
                        <Key size={11} /> {l.algorithm || 'EdDSA'}
                      </span>
                    </td>
                    <td className="ng-table-cell">
                      <span className={`ng-table-badge ${
                        l.status === 'active'
                          ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500'
                          : 'bg-amber-500/10 border-amber-500/20 text-amber-500'
                      }`}>
                        {l.status || 'G��'}
                      </span>
                    </td>
                    <td className="ng-table-cell font-mono text-xs">{fmtDate(l.start_date)}</td>
                    <td className="ng-table-cell font-mono text-xs">{fmtDate(l.end_date)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {/* Tenant License Distribution G�� new flow */}
      <section className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
          <div>
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider flex items-center gap-2">
              <ArrowDownToLine size={14} className="text-primary" />
              Tenant License Distribution Flow
            </h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              Each tenant server now fetches its signed license directly from Supabase Cloud.
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
          <div className="rounded-xl bg-primary/5 border border-primary/20 p-3">
            <dt className="text-[0.65rem] uppercase tracking-wider text-primary font-bold flex items-center gap-1">
              <Cloud size={10} /> 1. SuperAdmin issues
            </dt>
            <dd className="text-xs text-foreground mt-1 leading-snug">
              You generate a signed license here. The token is pushed to{' '}
              <code className="font-mono text-primary">public.tenant_licenses</code>{' '}
              via the anon key + the <code className="font-mono">upsert_license_cloud</code> SECURITY DEFINER RPC.
            </dd>
          </div>
          <div className="rounded-xl bg-sky-500/5 border border-sky-500/20 p-3">
            <dt className="text-[0.65rem] uppercase tracking-wider text-sky-500 font-bold flex items-center gap-1">
              <ArrowDownToLine size={10} /> 2. Tenant fetches with anon key
            </dt>
            <dd className="text-xs text-foreground mt-1 leading-snug">
              On every request, the tenant server hits Supabase with its anon key, filtered by
              its own <code className="font-mono">tenant_id</code>. The signed EdDSA token is
              verified locally against your public key.
            </dd>
          </div>
          <div className="rounded-xl bg-emerald-500/5 border border-emerald-500/20 p-3">
            <dt className="text-[0.65rem] uppercase tracking-wider text-emerald-500 font-bold flex items-center gap-1">
              <HardDrive size={10} /> 3. Offline write-back
            </dt>
            <dd className="text-xs text-foreground mt-1 leading-snug">
              The fetched row is upserted into the tenant's local SQLite{' '}
              <code className="font-mono">tenant_licenses</code>. If Supabase goes down, the
              middleware keeps verifying from the local cache.
            </dd>
          </div>
        </div>

        <div className="rounded-xl bg-muted/40 border border-border p-3 flex items-start gap-3">
          <ShieldAlert size={14} className="text-amber-500 mt-0.5 shrink-0" />
          <div className="text-xs text-muted-foreground leading-snug">
            <strong className="text-foreground">RLS policy</strong> G�� the migration
            <code className="font-mono mx-1">2026072900000000_tenant_licenses_rls_read_policy</code>
            enables a permissive read policy for the <code className="font-mono">anon</code> role in
            the Supabase project. The application layer scopes every fetch by{' '}
            <code className="font-mono">tenant_id</code> so a tenant only ever sees its own row.
            Apply the migration with{' '}
            <code className="font-mono">knex migrate:latest</code> on the Supabase project, or
            paste <code className="font-mono">sql/20260729_tenant_licenses_rls_read_policy.sql</code>
            into the Supabase SQL editor.
          </div>
        </div>
      </section>

      <section className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
          <div>
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Reconciliation Report</h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              Diff cloud state against the local SQLite used by the SuperAdmin controller.
            </p>
          </div>
          <button
            onClick={runReconcile}
            disabled={reconcileLoading || !canConnect}
            title={!canConnect ? 'Set SUPABASE_KEY (or VITE_SUPABASE_ANON_KEY) in superadmin/server/.env and restart the process.' : undefined}
            className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary/90 text-primary-foreground rounded-xl text-xs font-bold transition-all border border-primary shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <GitMerge size={14} className={reconcileLoading ? 'animate-spin' : ''} />
            <span>Pull & Reconcile</span>
          </button>
        </div>

        {reconcileLoading ? (
          <div className="py-6 text-center text-muted-foreground font-mono text-xs flex items-center justify-center gap-2">
            <RefreshCw size={14} className="animate-spin" /> Reconciling cloud vs. local GǪ
          </div>
        ) : reconcileError ? (
          <ErrorBanner message={reconcileError} />
        ) : !reconcile ? (
          <EmptyState label="No report yet G�� click Pull & Reconcile to diff cloud against local." />
        ) : (
          <div className="space-y-5">
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
              <div className="rounded-xl bg-muted/40 border border-border p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold flex items-center gap-1">
                  <Cloud size={10} /> Cloud Tenants
                </dt>
                <dd className="text-2xl font-black text-foreground mt-1 font-mono">
                  {reconcileCounts?.cloud_tenants ?? 0}
                </dd>
              </div>
              <div className="rounded-xl bg-muted/40 border border-border p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold flex items-center gap-1">
                  <Server size={10} /> Local Tenants
                </dt>
                <dd className="text-2xl font-black text-foreground mt-1 font-mono">
                  {reconcileCounts?.local_tenants ?? 0}
                </dd>
              </div>
              <div className="rounded-xl bg-rose-500/10 border border-rose-500/20 p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-rose-500 font-bold flex items-center gap-1">
                  <ShieldAlert size={10} /> Missing Locally
                </dt>
                <dd className="text-2xl font-black text-rose-500 mt-1 font-mono">
                  {reconcileCounts?.missing_locally ?? 0}
                </dd>
              </div>
              <div className="rounded-xl bg-amber-500/10 border border-amber-500/20 p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-amber-500 font-bold flex items-center gap-1">
                  <AlertTriangle size={10} /> Missing In Cloud
                </dt>
                <dd className="text-2xl font-black text-amber-500 mt-1 font-mono">
                  {reconcileCounts?.missing_in_cloud ?? 0}
                </dd>
              </div>
              <div className="rounded-xl bg-purple-500/10 border border-purple-500/20 p-3">
                <dt className="text-[0.65rem] uppercase tracking-wider text-purple-500 font-bold flex items-center gap-1">
                  <Layers size={10} /> Mismatched
                </dt>
                <dd className="text-2xl font-black text-purple-500 mt-1 font-mono">
                  {((reconcileCounts?.mismatched_tenants ?? 0) + (reconcileCounts?.mismatched_licenses ?? 0))}
                </dd>
              </div>
            </div>

            {reconcile.db_error && (
              <ErrorBanner message={`Local SQLite unavailable: ${reconcile.db_error}`} />
            )}

            {reconcile.missingLocally?.length > 0 && (
              <div>
                <h3 className="text-xs font-black text-foreground font-heading uppercase tracking-wider mb-2 flex items-center gap-1">
                  <ShieldAlert size={12} className="text-rose-500" /> Tenants in Cloud but Missing Locally ({reconcile.missingLocally.length})
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {reconcile.missingLocally.map((t: any) => (
                    <div key={t.id} className="rounded-xl bg-rose-500/5 border border-rose-500/20 p-3">
                      <div className="flex items-center justify-between">
                        <span className="font-bold text-foreground text-sm">{t.name || 'G��'}</span>
                        <span className="font-mono text-[0.65rem] text-muted-foreground">{t.code || 'G��'}</span>
                      </div>
                      <div className="font-mono text-[0.65rem] text-muted-foreground mt-1 break-all">{t.id}</div>
                      <div className="text-[0.7rem] text-muted-foreground mt-1">
                        {t.contact_email || 'G��'} -+ status: <span className="font-mono">{t.status || 'G��'}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {reconcile.mismatchedTenants?.length > 0 && (
              <div>
                <h3 className="text-xs font-black text-foreground font-heading uppercase tracking-wider mb-2 flex items-center gap-1">
                  <Layers size={12} className="text-purple-500" /> Tenant Field Mismatches ({reconcile.mismatchedTenants.length})
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {reconcile.mismatchedTenants.map((t: any) => (
                    <div key={t.id} className="rounded-xl bg-purple-500/5 border border-purple-500/20 p-3">
                      <div className="flex items-center justify-between">
                        <span className="font-bold text-foreground text-sm">{t.name}</span>
                        <span className="font-mono text-[0.65rem] text-muted-foreground">{t.code}</span>
                      </div>
                      <ul className="mt-2 space-y-1">
                        {Object.entries(t.diffs).map(([field, diff]: any) => (
                          <li key={field} className="text-[0.7rem] font-mono">
                            <span className="text-purple-500 font-bold">{field}</span>
                            <span className="text-muted-foreground"> G�� local: </span>
                            <span className="text-foreground">{String(diff.local ?? 'G��')}</span>
                            <span className="text-muted-foreground"> -+ cloud: </span>
                            <span className="text-foreground">{String(diff.cloud ?? 'G��')}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {reconcile.mismatchedLicenses?.length > 0 && (
              <div>
                <h3 className="text-xs font-black text-foreground font-heading uppercase tracking-wider mb-2 flex items-center gap-1">
                  <Key size={12} className="text-purple-500" /> License Field Mismatches ({reconcile.mismatchedLicenses.length})
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {reconcile.mismatchedLicenses.map((l: any) => (
                    <div key={`${l.id}-${l.start_date}`} className="rounded-xl bg-purple-500/5 border border-purple-500/20 p-3">
                      <div className="flex items-center justify-between">
                        <span className="font-bold text-foreground text-sm font-mono">{l.id}</span>
                        <span className="font-mono text-[0.65rem] text-muted-foreground">{l.term_name}</span>
                      </div>
                      <div className="font-mono text-[0.65rem] text-muted-foreground mt-1 break-all">{l.tenant_id}</div>
                      <div className="text-[0.7rem] text-muted-foreground mt-1">
                        start: <span className="font-mono">{l.start_date}</span> -+ end: <span className="font-mono">{l.end_date}</span>
                      </div>
                      <ul className="mt-2 space-y-1">
                        {Object.entries(l.diffs).map(([field, diff]: any) => (
                          <li key={field} className="text-[0.7rem] font-mono">
                            <span className="text-purple-500 font-bold">{field}</span>
                            <span className="text-muted-foreground"> G�� local: </span>
                            <span className="text-foreground">{String(diff.local ?? 'G��')}</span>
                            <span className="text-muted-foreground"> -+ cloud: </span>
                            <span className="text-foreground">{String(diff.cloud ?? 'G��')}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {(reconcile.missingLocally?.length || 0) === 0 &&
              (reconcile.mismatchedTenants?.length || 0) === 0 &&
              (reconcile.mismatchedLicenses?.length || 0) === 0 && (
              <div className="rounded-xl bg-emerald-500/10 border border-emerald-500/20 p-4 text-emerald-500 font-mono text-xs flex items-center gap-2">
                <CheckCircle2 size={14} />
                Cloud and local are in sync G�� no missing or mismatched records.
              </div>
            )}

            <div className="text-[0.65rem] text-muted-foreground font-mono">
              Generated {fmtDate(reconcile.generated_at)} -+ DB: {reconcile.db_path}
            </div>
          </div>
        )}
      </section>
    </div>
  );
}

export default SupabaseCloudLink;


