import React, { useEffect, useState } from 'react';
import {
  Building2, Key, ShieldCheck, ShieldAlert, Copy, Check, Server, Mail,
  Phone, Activity, Pencil, Cloud, CloudOff, UploadCloud, RefreshCw, Loader2, AlertCircle, CheckCircle2, Download
} from 'lucide-react';
import { Modal } from './ui/Modal';

interface TenantProfileModalProps {
  open: boolean;
  onClose: () => void;
  tenant: any;
  api: any;
  onRenewLicense: () => void;
  onOverride: () => void;
  onSpawnInstance: () => void;
  onSaved?: () => void;
  addToast?: (kind: 'success' | 'error' | 'info', title: string, message?: string) => void;
}

const tenantForm = (tenant: any) => ({
  name: tenant?.name || '',
  code: tenant?.code || '',
  contact_email: tenant?.contact_email || '',
  phone: tenant?.phone || '',
  address: tenant?.address || '',
  status: tenant?.status || 'active'
});

export function TenantProfileModal({
  open,
  onClose,
  tenant,
  api,
  onRenewLicense,
  onOverride,
  onSpawnInstance,
  onSaved,
  addToast
}: TenantProfileModalProps) {
  const [copied, setCopied] = useState(false);
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState(tenantForm(tenant));
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [repushing, setRepushing] = useState(false);
  const [cloudInfo, setCloudInfo] = useState<{
    state: string;
    cloudEnd?: string;
    localEnd?: string;
    error?: string;
  } | null>(null);
  const [cloudLoading, setCloudLoading] = useState(false);
  const [repushBusy, setRepushBusy] = useState(false);
  const [copiedTenantId, setCopiedTenantId] = useState(false);

  const handleCopyTenantId = () => {
    if (tenant?.id) {
      navigator.clipboard.writeText(tenant.id);
      setCopiedTenantId(true);
      setTimeout(() => setCopiedTenantId(false), 2000);
    }
  };

  useEffect(() => {
    setForm(tenantForm(tenant));
    setEditing(false);
    setSaving(false);
    setSaveError(null);
    setCloudInfo(null);
  }, [tenant]);

  useEffect(() => {
    if (!tenant?.id || !open) return;
    let cancelled = false;
    (async () => {
      setCloudLoading(true);
      try {
        const res = await api.get(`/tenants/${tenant.id}/licenses/cloud`);
        if (cancelled) return;
        if (res?.data) {
          setCloudInfo({
            state: res.data.sync_state || 'unknown',
            cloudEnd: res.data.cloud?.end_date,
            localEnd: res.data.local?.end_date,
            error: res.data.cloud_error
          });
        }
      } catch (_) {
        if (!cancelled) setCloudInfo({ state: 'unknown' });
      } finally {
        if (!cancelled) setCloudLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [tenant?.id, open, api]);

  const repushToCloud = async () => {
    if (!tenant?.id) return;
    setRepushBusy(true);
    try {
      const res = await api.post(`/tenants/${tenant.id}/licenses/repush`, {});
      if (res?.data?.ok) {
        addToast?.('success', 'Re-pushed to Supabase', `${tenant.name} license synced to cloud.`);
        const refresh = await api.get(`/tenants/${tenant.id}/licenses/cloud`);
        if (refresh?.data) {
          setCloudInfo({
            state: refresh.data.sync_state || 'unknown',
            cloudEnd: refresh.data.cloud?.end_date,
            localEnd: refresh.data.local?.end_date,
            error: refresh.data.cloud_error
          });
        }
        onSaved?.();
      } 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 {
      setRepushBusy(false);
    }
  };

  const handleDownloadArtifact = async () => {
    if (!tenant?.id) return;
    try {
      const res = await api.get(`/tenants/${tenant.id}/licenses/download`, {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      const fileName = `license_${tenant.code || 'SCH'}_${(lic?.term_name || 'TERM').replace(/\s+/g, '')}_${lic?.academic_year || '2026'}.lic.json`;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      addToast?.('success', 'Artifact Downloaded', `Downloaded ${fileName} for offline ingestion.`);
    } catch (err: any) {
      addToast?.('error', 'Download Failed', err?.response?.data?.error || err?.message || 'Could not download artifact');
    }
  };

  if (!tenant) return null;

  const lic = tenant.license;
  const isExpired = tenant.is_expired;
  const isOverridden = lic?.status === 'overridden';
  const subStatus = tenant.supabase_status || 'unconfigured';
  const studentCount = tenant.student_count || 0;
  const studentCap = lic?.max_students || 1000;
  const studentPct = Math.min(100, Math.round((studentCount / studentCap) * 100));
  const staffCount = tenant.staff_count || 0;
  const staffCap = lic?.max_staff || 200;
  const staffPct = Math.min(100, Math.round((staffCount / staffCap) * 100));

  const handleCopyToken = () => {
    if (lic?.license_key) {
      navigator.clipboard.writeText(lic.license_key);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };


  const startEditing = () => {
    setForm(tenantForm(tenant));
    setSaveError(null);
    setEditing(true);
  };

  const cancelEditing = () => {
    setForm(tenantForm(tenant));
    setSaveError(null);
    setEditing(false);
  };

  const saveChanges = async () => {
    setSaving(true);
    setSaveError(null);
    try {
      await api.put(`/tenants/${tenant.id}`, form);
      setEditing(false);
      onSaved?.();
      addToast?.('success', 'School Updated', `${form.name} details saved successfully`);
    } catch (err: any) {
      setSaveError(err.response?.data?.error || err.message || 'Failed to update school');
    } finally {
      setSaving(false);
    }
  };

  const handleReissueToSupabase = async () => {
    setRepushing(true);
    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 cloud`);
        onSaved?.();
      } else {
        addToast?.('error', 'Supabase Reissue Failed', res.data?.error || 'Push failed');
      }
    } catch (err: any) {
      addToast?.('error', 'Supabase Reissue Failed', err.response?.data?.error || err.message || 'Push request failed');
    } finally {
      setRepushing(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={tenant.name}
      subtitle={`Tenant ID: ${tenant.id} | Code: ${tenant.code}`}
      icon={Building2}
      watermarkIcon={Building2}
      maxWidth="max-w-2xl"
    >
      {editing ? (
        <div className="space-y-5">
          {saveError && (
            <div className="p-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-500 text-xs font-mono">
              {saveError}
            </div>
          )}
          <div className="grid grid-cols-2 gap-4">
            {[
              ['name', 'School Name'],
              ['code', 'School Code'],
              ['contact_email', 'Contact Email'],
              ['phone', 'Contact Phone'],
              ['address', 'Address']
            ].map(([field, label]) => (
              <label key={field} className={field === 'address' ? 'col-span-2 space-y-1.5' : 'space-y-1.5'}>
                <span className="text-xs font-bold text-muted-foreground">{label}</span>
                <input
                  value={form[field as keyof typeof form]}
                  onChange={e => setForm({ ...form, [field]: e.target.value })}
                  className="form-input text-xs font-mono"
                />
              </label>
            ))}
            <label className="col-span-2 space-y-1.5">
              <span className="text-xs font-bold text-muted-foreground">Status</span>
              <select
                value={form.status}
                onChange={e => setForm({ ...form, status: e.target.value })}
                className="form-input text-xs font-mono"
              >
                <option value="active">Active</option>
                <option value="suspended">Suspended</option>
                <option value="inactive">Inactive</option>
              </select>
            </label>
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <button onClick={cancelEditing} disabled={saving} className="py-2.5 px-4 bg-muted hover:bg-muted/80 text-foreground rounded-xl text-xs font-bold border border-border">
              Cancel
            </button>
            <button onClick={saveChanges} disabled={saving} className="py-2.5 px-4 bg-primary hover:bg-primary-dark disabled:opacity-50 text-white rounded-xl text-xs font-bold">
              {saving ? 'Saving...' : 'Save Changes'}
            </button>
          </div>
        </div>
      ) : (
        <div className="space-y-6">
          <div className={`p-4 rounded-2xl border flex items-center justify-between ${isOverridden ? 'bg-amber-500/10 border-amber-500/30 text-amber-500' : !isExpired ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-500' : 'bg-rose-500/10 border-rose-500/30 text-rose-500'}`}>
            <div className="flex items-center gap-3">
              {isOverridden ? <ShieldAlert size={22} /> : !isExpired ? <ShieldCheck size={22} /> : <Activity size={22} />}
              <div>
                <h4 className="text-xs font-black uppercase tracking-wider">{isOverridden ? 'Emergency Access Override Active' : !isExpired ? 'Active Term License Valid' : 'Term License Expired (Read-Only Mode)'}</h4>
                <p className="text-[0.7rem] opacity-80 mt-0.5 font-mono">{lic ? `Term: ${lic.term_name || 'Term 1'} (${lic.start_date} to ${lic.end_date})` : 'No active license token issued'}</p>
              </div>
            </div>
            <span className="text-[0.65rem] font-mono font-bold px-2.5 py-1 rounded-full bg-background border border-current uppercase">{lic?.status || 'UNLICENSED'}</span>
          </div>

          {/* Tenant ID Badge Banner */}
          <div className="p-3.5 rounded-2xl bg-slate-950 border border-slate-800 space-y-1">
            <div className="flex items-center justify-between">
              <span className="text-[0.68rem] font-bold uppercase tracking-wider text-sky-400 font-mono flex items-center gap-1.5">
                <Building2 size={13} /> Tenant ID (Instance Scope)
              </span>
              <button
                type="button"
                onClick={handleCopyTenantId}
                className="px-2.5 py-1 rounded-lg bg-sky-500/20 hover:bg-sky-500/30 text-sky-400 font-mono text-[0.7rem] font-bold transition-all flex items-center gap-1 border border-sky-500/30"
              >
                {copiedTenantId ? <Check size={11} className="text-emerald-400" /> : <Copy size={11} />}
                <span>{copiedTenantId ? 'Copied Tenant ID' : 'Copy Tenant ID'}</span>
              </button>
            </div>
            <div className="font-mono text-xs font-bold text-slate-100 select-all break-all">
              {tenant.id}
            </div>
          </div>

          {/* Cloud Source Indicator Panel */}
          <div className="p-4 rounded-2xl bg-muted/40 border border-border space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Cloud size={16} className="text-primary" />
                <h4 className="text-xs font-bold uppercase tracking-wider text-foreground">Cloud Source Indicator</h4>
              </div>
              {subStatus === 'synced' ? (
                <span className="text-[0.65rem] font-mono font-bold px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/30 flex items-center gap-1">
                  <Cloud size={11} /> CLOUD SYNCED
                </span>
              ) : subStatus === 'local_only' ? (
                <span className="text-[0.65rem] font-mono font-bold px-2.5 py-1 rounded-full bg-amber-500/10 text-amber-500 border border-amber-500/30 flex items-center gap-1">
                  <CloudOff size={11} /> LOCAL ONLY (UNSYNCED)
                </span>
              ) : subStatus === 'mismatched' ? (
                <span className="text-[0.65rem] font-mono font-bold px-2.5 py-1 rounded-full bg-purple-500/10 text-purple-500 border border-purple-500/30 flex items-center gap-1">
                  <RefreshCw size={11} /> CLOUD MISMATCH
                </span>
              ) : (
                <span className="text-[0.65rem] font-mono font-bold px-2.5 py-1 rounded-full bg-muted text-muted-foreground border border-border flex items-center gap-1">
                  <Cloud size={11} /> UNCONFIGURED
                </span>
              )}
            </div>
            <div className="grid grid-cols-2 gap-3 text-[0.7rem] font-mono text-muted-foreground">
              <div>Dedicated Storage Bucket: <strong className="text-foreground font-bold">tenant-{tenant.id}</strong></div>
              <div>Cloud Sync Target: <strong className="text-foreground font-bold">tenants & tenant_licenses</strong></div>
            </div>
            <div className="pt-1 flex items-center justify-between gap-3 border-t border-border/50">
              <p className="text-[0.68rem] text-muted-foreground">
                Push local row & latest license token directly to Supabase Cloud infrastructure.
              </p>
              <button
                onClick={handleReissueToSupabase}
                disabled={repushing}
                className="py-1.5 px-3 bg-primary hover:bg-primary/90 text-primary-foreground rounded-xl text-xs font-bold transition-all border border-primary flex items-center gap-1.5 disabled:opacity-50 shrink-0"
              >
                <UploadCloud size={13} className={repushing ? 'animate-spin' : ''} />
                <span>{repushing ? 'Reissuing...' : 'Reissue from Supabase'}</span>
              </button>
            </div>
          </div>

          {/* Cloud distribution state — read by tenant servers with anon key */}
          <div className="rounded-2xl border border-border p-4 bg-muted/30 space-y-2">
            <div className="flex items-center justify-between gap-3 flex-wrap">
              <div className="flex items-center gap-2">
                <Cloud size={14} className="text-sky-500" />
                <h4 className="text-xs font-black uppercase tracking-wider text-muted-foreground">Supabase Cloud Distribution</h4>
                {cloudLoading ? (
                  <Loader2 size={12} className="animate-spin text-muted-foreground" />
                ) : cloudInfo?.state === 'in_sync' ? (
                  <span className="px-2 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-500 text-[0.6rem] font-mono font-bold flex items-center gap-1">
                    <CheckCircle2 size={10} /> IN SYNC
                  </span>
                ) : cloudInfo?.state === 'drift' ? (
                  <span className="px-2 py-0.5 rounded-full bg-rose-500/10 border border-rose-500/20 text-rose-500 text-[0.6rem] font-mono font-bold flex items-center gap-1">
                    <AlertCircle size={10} /> DRIFT
                  </span>
                ) : cloudInfo?.state === 'not_pushed' ? (
                  <span className="px-2 py-0.5 rounded-full bg-amber-500/10 border border-amber-500/20 text-amber-500 text-[0.6rem] font-mono font-bold flex items-center gap-1">
                    <Cloud size={10} /> NOT PUSHED
                  </span>
                ) : cloudInfo?.state === 'cloud_only' ? (
                  <span className="px-2 py-0.5 rounded-full bg-sky-500/10 border border-sky-500/20 text-sky-500 text-[0.6rem] font-mono font-bold flex items-center gap-1">
                    <Cloud size={10} /> CLOUD ONLY
                  </span>
                ) : (
                  <span className="px-2 py-0.5 rounded-full bg-muted/40 border border-border text-muted-foreground text-[0.6rem] font-mono font-bold">
                    UNKNOWN
                  </span>
                )}
              </div>
              <button
                onClick={repushToCloud}
                disabled={repushBusy || cloudInfo?.state === 'in_sync'}
                className="px-3 py-1 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-500 rounded-lg text-[0.7rem] font-mono font-semibold transition-colors border border-emerald-500/30 disabled:opacity-40 disabled:cursor-not-allowed flex items-center gap-1"
                title={cloudInfo?.state === 'in_sync' ? 'Already in sync with Supabase' : 'Re-push current local license to Supabase Cloud'}
              >
                {repushBusy
                  ? <Loader2 size={11} className="animate-spin" />
                  : <Cloud size={11} />}
                Re-push to Cloud
              </button>
            </div>
            <p className="text-[0.7rem] text-muted-foreground font-mono">
              {cloudInfo?.state === 'in_sync' && 'Local SQLite and Supabase cloud hold the same license row. Tenant servers will fetch it via the anon key.'}
              {cloudInfo?.state === 'drift' && 'Local and cloud rows differ. Use Re-push to align them.'}
              {cloudInfo?.state === 'not_pushed' && 'Tenant server cannot fetch this license from Supabase yet. Re-push to publish it.'}
              {cloudInfo?.state === 'cloud_only' && 'Cloud has a row but local SQLite does not.'}
              {cloudInfo?.error ? `Last error: ${cloudInfo.error}` : null}
            </p>
          </div>

          <div className="grid grid-cols-2 gap-4 text-xs font-mono">
            <div className="p-3.5 rounded-xl bg-muted/40 border border-border space-y-1">
              <span className="text-muted-foreground flex items-center gap-1.5"><Mail size={12} /> Contact Email:</span>
              <p className="font-bold text-foreground truncate">{tenant.contact_email || 'N/A'}</p>
            </div>
            <div className="p-3.5 rounded-xl bg-muted/40 border border-border space-y-1">
              <span className="text-muted-foreground flex items-center gap-1.5"><Phone size={12} /> Contact Phone:</span>
              <p className="font-bold text-foreground">{tenant.phone || 'N/A'}</p>
            </div>
          </div>

          <div className="space-y-3">
            <h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Subscribed Capacity Allocation</h4>
            <div className="space-y-1.5">
              <div className="flex justify-between text-xs font-mono"><span className="text-foreground font-bold">Enrolled Student Capacity:</span><span className="text-muted-foreground">{studentCount} / {studentCap} ({studentPct}%)</span></div>
              <div className="w-full h-2 rounded-full bg-muted overflow-hidden"><div className="h-full bg-primary transition-all duration-300" style={{ width: `${studentPct}%` }} /></div>
            </div>
            <div className="space-y-1.5">
              <div className="flex justify-between text-xs font-mono"><span className="text-foreground font-bold">Staff Directory Capacity:</span><span className="text-muted-foreground">{staffCount} / {staffCap} ({staffPct}%)</span></div>
              <div className="w-full h-2 rounded-full bg-muted overflow-hidden"><div className="h-full bg-amber-500 transition-all duration-300" style={{ width: `${staffPct}%` }} /></div>
            </div>
          </div>

          {lic?.license_key && (
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5"><Key size={14} className="text-amber-500" /> Signed Cryptographic License Token</h4>
                <div className="flex items-center gap-3">
                  <button onClick={handleDownloadArtifact} className="flex items-center gap-1 text-[0.7rem] font-mono text-emerald-500 hover:underline">
                    <Download size={12} /><span>Download Artifact (.lic.json)</span>
                  </button>
                  <button onClick={handleCopyToken} className="flex items-center gap-1 text-[0.7rem] font-mono text-primary hover:underline">
                    {copied ? <Check size={12} className="text-emerald-500" /> : <Copy size={12} />}<span>{copied ? 'Copied Token' : 'Copy Token'}</span>
                  </button>
                </div>
              </div>
              <div className="p-3.5 rounded-xl bg-slate-950 border border-slate-800 font-mono text-[0.68rem] text-amber-300/90 break-all select-all max-h-24 overflow-y-auto custom-scrollbar">{lic.license_key}</div>
            </div>
          )}

          <div className="grid grid-cols-4 gap-3 pt-2">
            <button onClick={startEditing} className="py-2.5 px-3 bg-muted hover:bg-muted/80 text-foreground rounded-xl text-xs font-bold border border-border flex items-center justify-center gap-1.5"><Pencil size={14} /> Edit Details</button>
            <button onClick={() => { onClose(); onRenewLicense(); }} className="py-2.5 px-3 bg-primary hover:bg-primary-dark text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-1.5"><Key size={14} /> Renew License</button>
            <button onClick={() => { onClose(); onOverride(); }} className="py-2.5 px-3 bg-amber-500/10 hover:bg-amber-500/20 text-amber-500 rounded-xl text-xs font-bold border border-amber-500/30 flex items-center justify-center gap-1.5"><ShieldAlert size={14} /> Override Access</button>
            <button onClick={() => { onClose(); onSpawnInstance(); }} className="py-2.5 px-3 bg-muted hover:bg-muted/80 text-foreground rounded-xl text-xs font-bold border border-border flex items-center justify-center gap-1.5"><Server size={14} /> Spawn Instance</button>
          </div>
        </div>
      )}
    </Modal>
  );
}

