import React, { useEffect, useState } from 'react';
import {
  Search, Download, Eye, AlertTriangle, CheckCircle2, ShieldAlert,
  Building2, Key, PlusCircle, Cloud, CloudOff, RefreshCw, Loader2, AlertCircle, UploadCloud, Copy, Check
} from 'lucide-react';
import { Modal } from '../components/ui/Modal';
import { TenantProfileModal } from '../components/TenantProfileModal';
import { OnboardSchoolForm } from '../components/forms/OnboardSchoolForm';
import { IssueLicenseForm } from '../components/forms/IssueLicenseForm';
import { OverrideForm } from '../components/forms/OverrideForm';
import { ToastType } from '../hooks/useToasts';

interface TenantManagementProps {
  api: any;
  tenants: any[];
  onRefresh: () => void;
  addToast: (type: ToastType, title: string, message?: string) => void;
  onSpawnInstanceFromProfile?: () => void;
}

type StatusFilter = 'ALL' | 'ACTIVE' | 'EXPIRED' | 'OVERRIDDEN' | 'CLOUD_SYNCED' | 'LOCAL_ONLY' | 'CLOUD_MISMATCH';

function cloudStateLabelFor(state: string | undefined): { text: string; cls: string; Icon?: any } {
  switch (state) {
    case 'in_sync':
      return { text: 'CLOUD IN-SYNC', cls: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20', Icon: CheckCircle2 };
    case 'drift':
      return { text: 'CLOUD DRIFT', cls: 'bg-rose-500/10 text-rose-500 border-rose-500/20', Icon: AlertCircle };
    case 'not_pushed':
      return { text: 'NOT PUSHED', cls: 'bg-amber-500/10 text-amber-500 border-amber-500/20', Icon: Cloud };
    case 'cloud_only':
      return { text: 'CLOUD ONLY', cls: 'bg-sky-500/10 text-sky-500 border-sky-500/20', Icon: Cloud };
    default:
      return { text: 'CHECKINGΓÇª', cls: 'bg-muted/40 text-muted-foreground border-border', Icon: Loader2 };
  }
}

export function TenantManagement({
  api,
  tenants,
  onRefresh,
  addToast,
  onSpawnInstanceFromProfile,
}: TenantManagementProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('ALL');
  const [selectedTenant, setSelectedTenant] = useState<any>(null);
  const [showOnboardModal, setShowOnboardModal] = useState(false);
  const [showLicenseModal, setShowLicenseModal] = useState(false);
  const [showOverrideModal, setShowOverrideModal] = useState(false);
  const [showProfileModal, setShowProfileModal] = useState(false);
  const [repushingId, setRepushingId] = useState<string | null>(null);
  const [copiedIdMap, setCopiedIdMap] = useState<Record<string, boolean>>({});

  const handleCopyTenantId = (id: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    navigator.clipboard.writeText(id);
    setCopiedIdMap((prev) => ({ ...prev, [id]: true }));
    setTimeout(() => {
      setCopiedIdMap((prev) => ({ ...prev, [id]: false }));
    }, 2000);
  };

  // Per-tenant cloud sync state. Keyed by tenant id.
  //   { state: 'in_sync' | 'drift' | 'not_pushed' | 'cloud_only' | 'unknown',
  //     cloudEnd?: string, localEnd?: string, error?: string }
  const [cloudState, setCloudState] = useState<Record<string, { state: string; error?: string; cloudEnd?: string; localEnd?: string }>>({});
  const [refreshingCloudFor, setRefreshingCloudFor] = useState<string | null>(null);
  const [repushingFor, setRepushingFor] = useState<string | null>(null);

  const refreshCloudFor = async (tenantId: string) => {
    setRefreshingCloudFor(tenantId);
    try {
      const res = await api.get(`/tenants/${tenantId}/licenses/cloud`);
      if (res?.data) {
        setCloudState((prev) => ({
          ...prev,
          [tenantId]: {
            state: res.data.sync_state || 'unknown',
            cloudEnd: res.data.cloud?.end_date,
            localEnd: res.data.local?.end_date,
            error: res.data.cloud_error
          }
        }));
      }
    } catch (err: any) {
      setCloudState((prev) => ({
        ...prev,
        [tenantId]: { state: 'unknown', error: err?.response?.data?.error || err?.message || 'fetch failed' }
      }));
    } finally {
      setRefreshingCloudFor(null);
    }
  };

  const refreshAllCloud = async () => {
    await Promise.all(tenants.map((t) => refreshCloudFor(t.id)));
  };

  const repushToCloud = async (tenantId: string, tenantName: string) => {
    setRepushingFor(tenantId);
    try {
      const res = await api.post(`/tenants/${tenantId}/licenses/repush`, {});
      if (res?.data?.ok) {
        addToast('success', 'Re-pushed to Supabase', `${tenantName} license synced to cloud.`);
        await refreshCloudFor(tenantId);
        onRefresh();
      } else {
        addToast('error', 'Re-push Failed', res?.data?.error || 'Unknown error');
      }
    } catch (err: any) {
      addToast('error', 'Re-push Failed', err?.response?.data?.error || err?.message || 'Network error');
    } finally {
      setRepushingFor(null);
    }
  };

  // Alternate reissue path — pushes the local tenant row + license to Supabase
  // using the broader `/supabase/repush` endpoint. Useful when both tenant
  // metadata and license token need to be re-issued atomically.
  const reissueToSupabase = async (tenant: any) => {
    setRepushingId(tenant.id);
    try {
      const res = await api.post(`/tenants/${tenant.id}/supabase/repush`);
      if (res.data?.ok) {
        addToast('success', 'Supabase Reissue Successful', res.data.message || `Tenant ${tenant.name} pushed to Supabase Cloud`);
        await refreshCloudFor(tenant.id);
        onRefresh();
      } else {
        addToast('error', 'Supabase Reissue Failed', res.data?.error || 'Failed to push row to Supabase Cloud');
      }
    } catch (err: any) {
      addToast('error', 'Supabase Reissue Failed', err.response?.data?.error || err.message || 'Push request failed');
    } finally {
      setRepushingId(null);
    }
  };

  // Lazy-load the cloud sync state for every visible tenant on mount
  // and whenever the tenant list reference changes (after a refresh).
  useEffect(() => {
    if (tenants.length > 0) {
      refreshAllCloud();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tenants.map((t) => t.id).join(',')]);

  const filteredTenants = tenants.filter(t => {
    const q = searchQuery.toLowerCase();
    const matchesQuery =
      t.name.toLowerCase().includes(q) ||
      t.code.toLowerCase().includes(q) ||
      (t.contact_email && t.contact_email.toLowerCase().includes(q));

    const isOverridden = t.license?.status === 'overridden';
    const isExpired = !!t.is_expired;
    const subStatus = cloudState[t.id]?.state || t.supabase_status || 'unconfigured';

    const matchesStatus =
      statusFilter === 'ALL' ? true :
      statusFilter === 'OVERRIDDEN' ? isOverridden :
      statusFilter === 'EXPIRED' ? isExpired && !isOverridden :
      statusFilter === 'ACTIVE' ? !isExpired || isOverridden :
      statusFilter === 'CLOUD_SYNCED' ? subStatus === 'in_sync' || subStatus === 'synced' :
      statusFilter === 'LOCAL_ONLY' ? subStatus === 'not_pushed' || subStatus === 'local_only' :
      statusFilter === 'CLOUD_MISMATCH' ? subStatus === 'drift' || subStatus === 'mismatched' :
      true;

    return matchesQuery && matchesStatus;
  });

  const exportDirectoryCsv = () => {
    if (tenants.length === 0) return;
    const headers = ['ID', 'Name', 'Code', 'Contact Email', 'Phone', 'Learners', 'License Status', 'Term', 'Start Date', 'End Date'];
    const rows = tenants.map(t => [
      t.id,
      t.name,
      t.code,
      t.contact_email || '',
      t.phone || '',
      t.student_count || 0,
      t.license?.status || (t.is_expired ? 'EXPIRED' : 'ACTIVE'),
      t.license?.term_name || 'Term 1',
      t.license?.start_date || '',
      t.license?.end_date || '',
    ]);
    const csvContent = [headers.join(','), ...rows.map(r => r.map(c => `"${c}"`).join(','))].join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `schools_directory_${new Date().toISOString().slice(0, 10)}.csv`;
    link.click();
    URL.revokeObjectURL(url);
    addToast('success', 'Directory Exported', 'Downloaded CSV registry file');
  };

  const openProfile = (tenant: any) => {
    setSelectedTenant(tenant);
    setShowProfileModal(true);
  };

  const openLicense = (tenant: any) => {
    setSelectedTenant(tenant);
    setShowLicenseModal(true);
  };

  const openOverride = (tenant: any) => {
    setSelectedTenant(tenant);
    setShowOverrideModal(true);
  };

  return (
    <div className="bg-card border border-border rounded-3xl overflow-hidden shadow-xl">
      {/* Toolbar */}
      <div className="p-6 border-b border-border flex flex-wrap items-center justify-between gap-4 bg-muted/30">
        <div>
          <h2 className="text-lg font-bold text-foreground">Subscribing Schools Registry</h2>
          <p className="text-xs text-muted-foreground mt-0.5">
            Manage tenants, issue termly cryptographic licenses, and grant emergency overrides
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <div className="relative min-w-[240px]">
            <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <input
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search name, code, email..."
              className="form-input pl-10 text-xs font-mono"
            />
          </div>
          <select
            value={statusFilter}
            onChange={e => setStatusFilter(e.target.value as StatusFilter)}
            className="py-2 px-3 bg-background border border-border rounded-xl text-xs font-mono text-foreground focus:outline-none"
          >
            <option value="ALL">All Statuses</option>
            <option value="ACTIVE">Active Licenses</option>
            <option value="EXPIRED">Expired Licenses</option>
            <option value="OVERRIDDEN">Emergency Overrides</option>
            <option value="CLOUD_SYNCED">Cloud Synced</option>
            <option value="LOCAL_ONLY">Local Only (Unsynced)</option>
            <option value="CLOUD_MISMATCH">Cloud Mismatch</option>
          </select>
          <button
            onClick={refreshAllCloud}
            disabled={tenants.length === 0}
            className="flex items-center gap-1.5 px-3 py-2 bg-muted hover:bg-muted/80 text-foreground rounded-xl text-xs font-bold transition-all border border-border shadow-sm disabled:opacity-50"
            title="Re-fetch each tenant's Supabase cloud license"
          >
            <RefreshCw size={14} className={refreshingCloudFor !== null ? 'animate-spin' : ''} />
            Refresh Cloud
          </button>
          <button
            onClick={exportDirectoryCsv}
            className="flex items-center gap-1.5 px-3 py-2 bg-muted hover:bg-muted/80 text-foreground rounded-xl text-xs font-bold transition-all border border-border shadow-sm"
            title="Export Registry CSV"
          >
            <Download size={14} /> Export CSV
          </button>
          <button
            onClick={() => setShowOnboardModal(true)}
            className="flex items-center gap-1.5 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-xl text-xs font-bold transition-all shadow-sm"
          >
            <PlusCircle size={14} /> Onboard School
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="ng-table w-full text-left text-xs border-collapse">
          <thead className="ng-table-header">
            <tr>
              <th className="py-4 px-6 font-bold">School Name</th>
              <th className="py-4 px-4 font-bold">Code</th>
              <th className="py-4 px-4 font-bold">Enrolled Learners</th>
              <th className="py-4 px-4 font-bold">Term License Status</th>
              <th className="py-4 px-4 font-bold">Cloud Sync</th>
              <th className="py-4 px-4 font-bold">Valid Dates</th>
              <th className="py-4 px-6 font-bold text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border/60">
            {filteredTenants.length > 0 ? (
              filteredTenants.map(t => {
                const lic = t.license;
                const isExpired = !!t.is_expired;
                const isOverridden = lic?.status === 'overridden';
                const cloud = cloudState[t.id];
                const cloudStateLabel = cloudStateLabelFor(cloud?.state);
                return (
                  <tr key={t.id} className="ng-table-row">
                    <td className="ng-table-cell">
                      <button
                        onClick={() => openProfile(t)}
                        className="font-bold text-foreground text-sm hover:text-primary transition-colors text-left"
                      >
                        {t.name}
                      </button>
                      <div className="text-[0.7rem] text-muted-foreground font-mono">
                        {t.contact_email || 'No email registered'}
                      </div>
                    </td>
                    <td className="ng-table-cell">
                      <div className="flex flex-col gap-1">
                        <span className="font-mono px-2 py-0.5 rounded bg-muted text-primary font-bold border border-border inline-block w-fit">
                          {t.code}
                        </span>
                        <div className="flex items-center gap-1.5 font-mono text-[0.65rem] text-muted-foreground">
                          <span className="truncate max-w-[125px]" title={`Tenant ID: ${t.id}`}>ID: {t.id}</span>
                          <button
                            type="button"
                            onClick={(e) => handleCopyTenantId(t.id, e)}
                            className="p-0.5 text-muted-foreground hover:text-primary transition-colors shrink-0"
                            title="Copy Tenant ID to clipboard"
                          >
                            {copiedIdMap[t.id] ? <Check size={11} className="text-emerald-500" /> : <Copy size={11} />}
                          </button>
                        </div>
                      </div>
                    </td>
                    <td className="ng-table-cell font-mono">
                      {t.student_count} / {lic?.max_students || 1000}
                    </td>
                    <td className="ng-table-cell">
                      {isOverridden ? (
                        <span className="ng-table-badge bg-primary/10 text-primary border-primary/20">
                          <ShieldAlert size={12} /> OVERRIDDEN
                        </span>
                      ) : !isExpired ? (
                        <span className="ng-table-badge bg-emerald-500/10 text-emerald-500 border-emerald-500/20">
                          <CheckCircle2 size={12} /> ACTIVE ({lic?.term_name || 'Term 1'})
                        </span>
                      ) : (
                        <span className="ng-table-badge bg-rose-500/10 text-rose-500 border-rose-500/20">
                          <AlertTriangle size={12} /> EXPIRED
                        </span>
                      )}
                    </td>
                    <td className="ng-table-cell">
                      {cloud ? (
                        <div className="flex items-center gap-1.5">
                          <span className={`ng-table-badge ${cloudStateLabel.cls}`}>
                            {cloudStateLabel.Icon && <cloudStateLabel.Icon size={11} />}
                            {cloudStateLabel.text}
                          </span>
                          <button
                            onClick={() => refreshCloudFor(t.id)}
                            disabled={refreshingCloudFor === t.id}
                            className="p-1 text-muted-foreground hover:text-foreground disabled:opacity-50"
                            title="Refresh cloud sync state"
                          >
                            {refreshingCloudFor === t.id
                              ? <Loader2 size={11} className="animate-spin" />
                              : <RefreshCw size={11} />}
                          </button>
                        </div>
                      ) : (
                        <span className="text-[0.7rem] text-muted-foreground font-mono">checkingΓÇª</span>
                      )}
                    </td>
                    <td className="ng-table-cell font-mono text-muted-foreground text-[0.7rem]">
                      {lic ? `${lic.start_date} to ${lic.end_date}` : 'No license'}
                    </td>
                    <td className="ng-table-cell text-right">
                      <div className="flex justify-end items-center gap-2">
                        <button
                          onClick={() => repushToCloud(t.id, t.name)}
                          disabled={repushingFor === t.id || !cloud || cloud.state === 'in_sync'}
                          className="px-2.5 py-1.5 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-500 rounded-lg text-xs font-mono font-semibold transition-colors border border-emerald-500/30 disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1"
                          title={
                            !cloud
                              ? 'Loading cloud stateΓÇª'
                              : cloud.state === 'in_sync'
                              ? 'Already in sync with Supabase'
                              : 'Re-push current local license to Supabase Cloud'
                          }
                        >
                          {repushingFor === t.id
                            ? <Loader2 size={11} className="animate-spin" />
                            : <Cloud size={11} />}
                          Re-push
                        </button>
                        <button
                          onClick={() => reissueToSupabase(t)}
                          disabled={repushingId === t.id}
                          className="px-2.5 py-1.5 bg-primary/10 hover:bg-primary/20 text-primary rounded-lg text-xs font-mono font-semibold transition-colors border border-primary/30 disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1"
                          title="Reissue and push local tenant row to Supabase Cloud"
                        >
                          {repushingId === t.id
                            ? <Loader2 size={11} className="animate-spin" />
                            : <UploadCloud size={11} />}
                          Reissue Cloud
                        </button>
                        <button
                          onClick={() => openProfile(t)}
                          className="p-1.5 bg-muted hover:bg-muted/80 text-foreground rounded-lg text-xs font-mono font-semibold transition-colors border border-border inline-flex items-center justify-center"
                          title="Inspect School Profile"
                        >
                          <Eye size={14} />
                        </button>
                        <button
                          onClick={() => openLicense(t)}
                          className="px-3 py-1.5 bg-muted hover:bg-muted/80 text-foreground rounded-lg text-xs font-mono font-semibold transition-colors border border-border"
                        >
                          Renew License
                        </button>
                        <button
                          onClick={() => openOverride(t)}
                          className="px-3 py-1.5 bg-amber-500/10 hover:bg-amber-500/20 text-amber-500 rounded-lg text-xs font-mono font-semibold transition-colors border border-amber-500/30"
                        >
                          Override
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan={7} className="py-12 text-center text-muted-foreground font-mono">
                  No subscribing school tenants found.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Modals */}
      <TenantProfileModal
        open={showProfileModal && !!selectedTenant}
        onClose={() => setShowProfileModal(false)}
        tenant={selectedTenant}
        api={api}
        addToast={addToast}
        onSaved={onRefresh}
        onRenewLicense={() => setShowLicenseModal(true)}
        onOverride={() => setShowOverrideModal(true)}
        onSpawnInstance={() => onSpawnInstanceFromProfile?.()}
      />

      <Modal
        open={showOnboardModal}
        onClose={() => setShowOnboardModal(false)}
        title="Onboard Subscribing School"
        subtitle="Register Institution & Issue Term License"
        icon={Building2}
        watermarkIcon={Building2}
        maxWidth="max-w-lg"
      >
        <OnboardSchoolForm
          api={api}
          onSuccess={(res) => {
            const name = typeof res === 'string' ? res : res.tenantName;
            addToast('success', 'School Onboarded & Signed', `${name} registered. Tenant ID generated.`);
            onRefresh();
          }}
          onError={(msg) => addToast('error', 'Onboarding Failed', msg)}
        />
      </Modal>

      <Modal
        open={showLicenseModal && !!selectedTenant}
        onClose={() => setShowLicenseModal(false)}
        title="Issue Term License"
        subtitle={selectedTenant?.name}
        icon={Key}
        watermarkIcon={Key}
        maxWidth="max-w-lg"
      >
        <IssueLicenseForm
          api={api}
          tenant={selectedTenant}
          onSuccess={(message) => {
            setShowLicenseModal(false);
            addToast('success', 'License Key Generated', message);
            onRefresh();
          }}
          onError={(msg) => addToast('error', 'License Generation Failed', msg)}
        />
      </Modal>

      <Modal
        open={showOverrideModal && !!selectedTenant}
        onClose={() => setShowOverrideModal(false)}
        title="Emergency Access Override"
        subtitle={selectedTenant?.name}
        icon={ShieldAlert}
        watermarkIcon={ShieldAlert}
        maxWidth="max-w-md"
      >
        <OverrideForm
          api={api}
          tenant={selectedTenant}
          onSuccess={(message) => {
            setShowOverrideModal(false);
            addToast('info', 'Emergency Override Granted', message);
            onRefresh();
          }}
          onError={(msg) => addToast('error', 'Override Failed', msg)}
        />
      </Modal>
    </div>
  );
}

export default TenantManagement;
