import React, { useEffect, useMemo, useState } from 'react';
import {
  Building2, Users, DollarSign, Key, RefreshCw, ShieldAlert,
  Server, CheckCircle2, AlertTriangle, ArrowUpRight, Clock, Activity,
  Cloud, CloudOff, AlertCircle, CheckCircle, Loader2
} from 'lucide-react';
import { DashboardMetrics } from '../hooks/useDashboardData';

interface DashboardProps {
  metrics: DashboardMetrics | null;
  tenants: any[];
  instances: any[];
  loading: boolean;
  onRefresh: () => void;
  onNavigateToInstances?: () => void;
  api?: any;
}

export function Dashboard({
  metrics,
  tenants,
  instances,
  loading,
  onRefresh,
  onNavigateToInstances,
  api,
}: DashboardProps) {
  const licenseHealth = useMemo(() => {
    let active = 0, expired = 0, overridden = 0;
    for (const t of tenants) {
      const isOverridden = t.license?.status === 'overridden';
      const isExpired = !!t.is_expired;
      if (isOverridden) overridden += 1;
      else if (isExpired) expired += 1;
      else active += 1;
    }
    const total = Math.max(tenants.length, 1);
    return { active, expired, overridden, activePct: Math.round((active / total) * 100), expiredPct: Math.round((expired / total) * 100), overriddenPct: Math.round((overridden / total) * 100) };
  }, [tenants]);

  // Cloud distribution: fetch each tenant's cloud sync state and
  // surface aggregate counts. Cheap because we only need a single
  // GET per tenant; the SuperAdmin server already aggregates.
  const [cloudRollup, setCloudRollup] = useState<{
    in_sync: number;
    drift: number;
    not_pushed: number;
    cloud_only: number;
    unknown: number;
    total: number;
    error?: string;
  }>({ in_sync: 0, drift: 0, not_pushed: 0, cloud_only: 0, unknown: 0, total: 0 });

  useEffect(() => {
    let cancelled = false;
    if (tenants.length === 0) return;
    (async () => {
      let in_sync = 0, drift = 0, not_pushed = 0, cloud_only = 0, unknown = 0;
      for (const t of tenants) {
        if (cancelled) return;
        try {
          if (!api) continue;
          const res = await api.get(`/tenants/${t.id}/licenses/cloud`);
          const state = res?.data?.sync_state;
          if (state === 'in_sync') in_sync += 1;
          else if (state === 'drift') drift += 1;
          else if (state === 'not_pushed') not_pushed += 1;
          else if (state === 'cloud_only') cloud_only += 1;
          else unknown += 1;
        } catch (_) {
          unknown += 1;
        }
      }
      if (!cancelled) {
        setCloudRollup({ in_sync, drift, not_pushed, cloud_only, unknown, total: tenants.length });
      }
    })();
    return () => { cancelled = true; };
  }, [tenants.map((t) => t.id).join(','), api]);

  const recentTenants = useMemo(() => {
    const getCreated = (t: any) => (t.created_at ? new Date(t.created_at).getTime() : 0);
    return [...tenants].sort((a, b) => getCreated(b) - getCreated(a)).slice(0, 5);
  }, [tenants]);

  const runningInstances = useMemo(() => instances.filter(i => i.status === 'RUNNING'), [instances]);
  const topRunning = runningInstances.slice(0, 3);
  const syncInfo = metrics?.supabase_sync;
  const cloudTotal = cloudRollup.in_sync + cloudRollup.drift + cloudRollup.not_pushed + cloudRollup.cloud_only;
  const cloudInSyncPct = cloudTotal > 0 ? Math.round((cloudRollup.in_sync / cloudTotal) * 100) : 0;

  return (
    <div className="space-y-8">
      <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">
              Tenant Management & <span className="text-primary">Licensing</span>
            </h1>
            <span className="px-2.5 py-0.5 rounded-full bg-amber-500/10 border border-amber-500/20 text-amber-500 text-xs font-mono font-bold">
              PLATFORM OWNER PORTAL
            </span>
          </div>
          <p className="text-xs text-muted-foreground mt-1 font-medium">
            Multi-Tenant Licensing & Tenant Management Console
          </p>
        </div>
        <button
          onClick={onRefresh}
          disabled={loading}
          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 disabled:opacity-50 shadow-sm"
        >
          <RefreshCw size={14} className={loading ? 'animate-spin text-primary' : ''} />
          <span>Refresh Telemetry</span>
        </button>
      </header>

      {/* Five Operational Pillars */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
        <div className="bg-card border border-border rounded-2xl p-5 relative overflow-hidden shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-[0.65rem] font-bold uppercase tracking-widest text-muted-foreground">Subscribing Schools</span>
            <div className="stat-icon blue"><Building2 size={18} /></div>
          </div>
          <h3 className="text-2xl font-black text-foreground">{metrics?.total_schools ?? 0}</h3>
          <p className="text-[0.7rem] text-emerald-500 font-mono mt-2 flex items-center gap-1 font-bold">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block animate-pulse" />
            {metrics?.active_schools ?? 0} Active License Tenants
          </p>
        </div>

        <div className="bg-card border border-border rounded-2xl p-5 relative overflow-hidden shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-[0.65rem] font-bold uppercase tracking-widest text-muted-foreground">Active Learners</span>
            <div className="stat-icon cyan"><Users size={18} /></div>
          </div>
          <h3 className="text-2xl font-black text-foreground">{(metrics?.total_learners ?? 0).toLocaleString()}</h3>
          <p className="text-[0.7rem] text-muted-foreground font-mono mt-2">Across all institutions</p>
        </div>

        <div className="bg-card border border-border rounded-2xl p-5 relative overflow-hidden shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-[0.65rem] font-bold uppercase tracking-widest text-muted-foreground">Term Revenue</span>
            <div className="stat-icon green"><DollarSign size={18} /></div>
          </div>
          <h3 className="text-2xl font-black text-emerald-500">${(metrics?.termly_revenue_usd ?? 0).toLocaleString()}</h3>
          <p className="text-[0.7rem] text-muted-foreground font-mono mt-2">Termly platform volume</p>
        </div>

        <div className="bg-card border border-border rounded-2xl p-5 relative overflow-hidden shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-[0.65rem] font-bold uppercase tracking-widest text-muted-foreground">Term Licenses</span>
            <div className="stat-icon orange"><Key size={18} /></div>
          </div>
          <h3 className="text-2xl font-black text-foreground">{metrics?.active_licenses ?? 0}</h3>
          <p className="text-[0.7rem] text-rose-500 font-mono mt-2 font-bold">
            {metrics?.expired_licenses ?? 0} Expired / Grace
          </p>
        </div>

        <div className="bg-card border border-border rounded-2xl p-5 relative overflow-hidden shadow-sm hover:shadow-md transition-all">
          <div className="flex items-center justify-between mb-3">
            <span className="text-[0.65rem] font-bold uppercase tracking-widest text-muted-foreground">Supabase Cloud Sync</span>
            <div className={`stat-icon ${syncInfo?.configured ? 'green' : 'orange'}`}>
              <Cloud size={18} />
            </div>
          </div>
          <h3 className="text-2xl font-black text-foreground">
            {syncInfo?.configured ? `${syncInfo.synced_count ?? 0}/${metrics?.total_schools ?? 0}` : 'Off-Cloud'}
          </h3>
          <p className={`text-[0.7rem] font-mono mt-2 font-bold flex items-center gap-1 ${
            syncInfo?.configured ? 'text-emerald-500' : 'text-amber-500'
          }`}>
            <span className={`w-1.5 h-1.5 rounded-full inline-block ${syncInfo?.configured ? 'bg-emerald-500 animate-pulse' : 'bg-amber-500'}`} />
            {syncInfo?.status_label || (syncInfo?.configured ? 'Cloud Synced' : 'Not Configured')}
          </p>
        </div>
      </div>

      {/* License Health + Cloud Distribution */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <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">
              License Health Distribution
            </h2>
            <ShieldAlert size={18} className="text-amber-500" />
          </div>
          <div className="h-3 w-full rounded-full overflow-hidden bg-muted flex">
            <div className="bg-emerald-500 transition-all" style={{ width: `${licenseHealth.activePct}%` }} />
            <div className="bg-rose-500 transition-all" style={{ width: `${licenseHealth.expiredPct}%` }} />
            <div className="bg-amber-500 transition-all" style={{ width: `${licenseHealth.overriddenPct}%` }} />
          </div>
          <div className="grid grid-cols-3 gap-2 mt-4">
            {[
              { dot: 'bg-emerald-500', label: 'Active', count: licenseHealth.active, tone: 'text-emerald-500' },
              { dot: 'bg-rose-500', label: 'Expired', count: licenseHealth.expired, tone: 'text-rose-500' },
              { dot: 'bg-amber-500', label: 'Override', count: licenseHealth.overridden, tone: 'text-amber-500' },
            ].map(c => (
              <div key={c.label} className="rounded-xl bg-muted/40 border border-border p-3 text-center">
                <span className={`inline-block w-2 h-2 rounded-full ${c.dot} mb-1`} />
                <p className={`text-lg font-black ${c.tone}`}>{c.count}</p>
                <p className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">{c.label}</p>
              </div>
            ))}
          </div>
        </div>

        {/* Cloud Sync Distribution — per-tenant Supabase publish state */}
        <div className="bg-card border border-border rounded-2xl p-6 shadow-sm lg:col-span-2">
          <div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider flex items-center gap-2">
              <Cloud size={14} className="text-sky-500" /> Supabase Cloud Distribution
            </h2>
            {cloudTotal > 0 && (
              <span className="text-[0.65rem] font-mono font-bold px-2.5 py-1 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-500 flex items-center gap-1">
                <CheckCircle2 size={11} /> {cloudInSyncPct}% IN SYNC
              </span>
            )}
          </div>
          <p className="text-[0.7rem] text-muted-foreground font-mono mb-4">
            {cloudTotal > 0
              ? `Live state from Supabase Cloud. ${cloudRollup.drift} drift, ${cloudRollup.not_pushed} not yet pushed.`
              : 'Loading per-tenant cloud sync state…'}
          </p>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {[
              { dot: 'bg-emerald-500', label: 'In Sync', count: cloudRollup.in_sync, tone: 'text-emerald-500', Icon: CheckCircle },
              { dot: 'bg-rose-500', label: 'Drift', count: cloudRollup.drift, tone: 'text-rose-500', Icon: AlertCircle },
              { dot: 'bg-amber-500', label: 'Not Pushed', count: cloudRollup.not_pushed, tone: 'text-amber-500', Icon: Cloud },
              { dot: 'bg-sky-500', label: 'Cloud Only', count: cloudRollup.cloud_only, tone: 'text-sky-500', Icon: Cloud },
            ].map(c => (
              <div key={c.label} className="rounded-xl bg-muted/40 border border-border p-3">
                <div className="flex items-center gap-2">
                  <span className={`inline-block w-2 h-2 rounded-full ${c.dot}`} />
                  <c.Icon size={12} className={c.tone} />
                </div>
                <p className={`text-2xl font-black mt-2 ${c.tone}`}>{c.count}</p>
                <p className="text-[0.65rem] uppercase tracking-wider text-muted-foreground font-bold">{c.label}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

        <div className="bg-card border border-border rounded-2xl p-6 shadow-sm lg:col-span-2">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">
              Recent Tenant Onboarding & Cloud Sync
            </h2>
            <Activity size={18} className="text-primary" />
          </div>
          <div className="divide-y divide-border/60">
            {recentTenants.length === 0 ? (
              <div className="py-6 text-center text-muted-foreground font-mono text-xs">
                No tenant onboarding activity yet.
              </div>
            ) : (
              recentTenants.map(t => {
                const isOverridden = t.license?.status === 'overridden';
                const isExpired = !!t.is_expired;
                const subStatus = t.supabase_status || 'unconfigured';
                const onboardedAt = t.created_at ? new Date(t.created_at).toLocaleDateString() : '—';
                const badgeClass = isOverridden
                  ? 'bg-primary/10 border-primary/20 text-primary'
                  : !isExpired
                  ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500'
                  : 'bg-rose-500/10 border-rose-500/20 text-rose-500';
                const badgeText = isOverridden ? 'OVERRIDDEN' : !isExpired ? 'ACTIVE' : 'EXPIRED';
                const BadgeIcon = isOverridden ? ShieldAlert : !isExpired ? CheckCircle2 : AlertTriangle;
                return (
                  <div key={t.id} className="flex items-center justify-between py-3">
                    <div className="min-w-0">
                      <p className="font-bold text-foreground text-sm truncate">{t.name}</p>
                      <p className="text-[0.7rem] text-muted-foreground font-mono">{t.code} · onboarded {onboardedAt}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      {subStatus === 'synced' ? (
                        <span className="px-2 py-0.5 rounded-full text-[0.6rem] font-mono font-bold bg-emerald-500/10 border border-emerald-500/20 text-emerald-500 flex items-center gap-1">
                          <Cloud size={10} /> CLOUD SYNCED
                        </span>
                      ) : subStatus === 'local_only' ? (
                        <span className="px-2 py-0.5 rounded-full text-[0.6rem] font-mono font-bold bg-amber-500/10 border border-amber-500/20 text-amber-500 flex items-center gap-1">
                          <CloudOff size={10} /> LOCAL ONLY
                        </span>
                      ) : subStatus === 'mismatched' ? (
                        <span className="px-2 py-0.5 rounded-full text-[0.6rem] font-mono font-bold bg-purple-500/10 border border-purple-500/20 text-purple-500 flex items-center gap-1">
                          <RefreshCw size={10} /> MISMATCHED
                        </span>
                      ) : null}
                      <span className={`px-2.5 py-1 rounded-full text-[0.65rem] font-mono font-bold border flex items-center gap-1 ${badgeClass}`}>
                        <BadgeIcon size={12} /> {badgeText}
                      </span>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>

      {/* Live Tenant Instances */}
      <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-sm font-black text-foreground font-heading uppercase tracking-wider">Live Tenant Instances</h2>
            <p className="text-xs text-muted-foreground mt-0.5">
              {runningInstances.length} of {instances.length} spawned instances are running
            </p>
          </div>
          <button
            onClick={onNavigateToInstances}
            className="flex items-center gap-1 text-xs font-bold text-primary hover:underline"
          >
            Manage Instances <ArrowUpRight size={13} />
          </button>
        </div>
        {topRunning.length === 0 ? (
          <div className="py-6 text-center text-muted-foreground font-mono text-xs">No instances are currently running.</div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {topRunning.map(inst => (
              <button
                key={inst.id}
                onClick={onNavigateToInstances}
                className="text-left p-4 rounded-xl bg-muted/40 border border-border hover:bg-muted transition-colors"
              >
                <div className="flex items-center justify-between mb-2">
                  <Server size={16} className="text-amber-500" />
                  <span className="text-[0.6rem] font-mono px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">RUNNING</span>
                </div>
                <p className="font-bold text-foreground text-sm truncate">{inst.name}</p>
                <p className="text-[0.7rem] text-muted-foreground font-mono truncate">{inst.code} · port {inst.server_port}</p>
                <p className="text-[0.65rem] text-muted-foreground font-mono mt-2 flex items-center gap-1">
                  <Clock size={10} /> PID {inst.pid || 'N/A'}
                </p>
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default Dashboard;
