import React, { useRef, useState } from 'react';
import {
  Wifi,
  WifiOff,
  Database,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  HelpCircle,
  Upload,
  Loader2,
} from 'lucide-react';
import { useLicenseStore, LicenseSource, LicenseStatus } from '../store/license';

type Source = LicenseSource;
type Status = LicenseStatus;

const SOURCE_COPY: Record<
  Source,
  { label: string; tone: string; icon: React.ComponentType<any> }
> = {
  supabase: {
    label: 'License verified via Cloud Provider',
    tone: 'border-emerald-300/60 bg-emerald-50 text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200 dark:border-emerald-800/60',
    icon: Wifi,
  },
  local: {
    label: 'License from local cache — provider server unreachable',
    tone: 'border-blue-300/60 bg-blue-50 text-blue-900 dark:bg-blue-950/40 dark:text-blue-200 dark:border-blue-800/60',
    icon: Database,
  },
  cache: {
    label: 'License from local offline cache',
    tone: 'border-slate-300/60 bg-slate-50 text-slate-900 dark:bg-slate-900/40 dark:text-slate-200 dark:border-slate-800/60',
    icon: Database,
  },
  none: {
    label: 'No license record found on server',
    tone: 'border-rose-300/60 bg-rose-50 text-rose-900 dark:bg-rose-950/40 dark:text-rose-200 dark:border-rose-800/60',
    icon: WifiOff,
  },
  unknown: {
    label: 'License source unverified',
    tone: 'border-amber-300/60 bg-amber-50 text-amber-900 dark:bg-amber-950/40 dark:text-amber-200 dark:border-amber-800/60',
    icon: HelpCircle,
  },
};

const STATUS_COPY: Record<
  Status,
  { label: string; tone: string; icon: React.ComponentType<any> }
> = {
  active: {
    label: 'Term License Active',
    tone: 'border-emerald-400/40 bg-emerald-100/70 text-emerald-950 dark:bg-emerald-900/60 dark:text-emerald-100',
    icon: CheckCircle2,
  },
  expired: {
    label: 'Term License Expired (Read-Only Mode)',
    tone: 'border-rose-400/40 bg-rose-100/70 text-rose-950 dark:bg-rose-900/60 dark:text-rose-100',
    icon: AlertTriangle,
  },
  invalid: {
    label: 'License Token Invalid / Signature Mismatch',
    tone: 'border-rose-400/40 bg-rose-100/70 text-rose-950 dark:bg-rose-900/60 dark:text-rose-100',
    icon: XCircle,
  },
  missing: {
    label: 'No Active License',
    tone: 'border-rose-400/40 bg-rose-100/70 text-rose-950 dark:bg-rose-900/60 dark:text-rose-100',
    icon: AlertTriangle,
  },
  unsupported: {
    label: 'License unsupported',
    tone: 'border-amber-300/60 bg-amber-50 text-amber-900 dark:bg-amber-950/40 dark:text-amber-200',
    icon: AlertTriangle,
  },
  unknown: {
    label: 'License status pending',
    tone: 'border-slate-200/60 bg-slate-50 text-slate-900 dark:bg-slate-900/40 dark:text-slate-200',
    icon: Wifi,
  },
};

export const LicenseSourceBanner: React.FC = () => {
  const source = useLicenseStore((s) => s.source) as Source;
  const status = useLicenseStore((s) => s.status);
  const bootstrap = useLicenseStore((s) => s.bootstrap);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  const sourceCfg = SOURCE_COPY[source] || SOURCE_COPY.unknown;
  const statusCfg = STATUS_COPY[status] || STATUS_COPY.unknown;
  const SourceIcon = sourceCfg.icon;
  const StatusIcon = statusCfg.icon;

  const isFallback = source === 'local';
  const isHappy = source === 'supabase' && status === 'active';

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const text = await file.text();
      const payload = JSON.parse(text);

      const res = await fetch('/api/license/ingest', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const data = await res.json();
      if (res.ok && data.ok) {
        alert(`License Ingested Successfully!\nTerm: ${data.license?.term_name || 'Active'} (${data.license?.academic_year || '2026'})\nValid until: ${data.license?.end_date || 'N/A'}`);
        if (bootstrap) await bootstrap();
      } else {
        alert(`License Ingestion Failed: ${data.error || data.message || 'Invalid file format'}`);
      }
    } catch (err: any) {
      alert(`Upload Failed: ${err.message || 'Invalid JSON artifact file'}`);
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  return (
    <div
      className={`mb-6 rounded-2xl border px-4 py-3 flex items-start gap-3 justify-between shadow-sm ${sourceCfg.tone}`}
      role="status"
      aria-live="polite"
    >
      <div className="flex items-start gap-3 flex-1 min-w-0">
        <SourceIcon size={18} className="shrink-0 mt-0.5" aria-hidden="true" />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <p className="text-sm font-semibold leading-snug">{sourceCfg.label}</p>
            <span className={`hidden md:inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider ${statusCfg.tone}`}>
              <StatusIcon size={11} aria-hidden="true" />
              {statusCfg.label}
            </span>
          </div>
          {isFallback && (
            <p className="text-xs mt-1 opacity-80">
              The SuperAdmin issued your term license to provider server. The tenant server has
              cached it locally so the school can keep running when the cloud is offline.
              Renewing is automatic on the next provider server fetch.
            </p>
          )}
          {isHappy && (
            <p className="text-xs mt-1 opacity-80">
              Cloud connection active. SuperAdmin term license key and capacity quotas are in sync with Supabase Cloud.
            </p>
          )}
        </div>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept=".json,.lic"
        onChange={handleFileChange}
        className="hidden"
      />
      <button
        type="button"
        onClick={() => fileInputRef.current?.click()}
        disabled={uploading}
        className="shrink-0 px-3 py-1.5 rounded-xl bg-white/80 dark:bg-slate-900/80 hover:bg-white dark:hover:bg-slate-900 border border-current text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm disabled:opacity-50 cursor-pointer"
        title="Upload offline license artifact (.lic.json) issued by SuperAdmin"
      >
        {uploading ? <Loader2 size={13} className="animate-spin" /> : <Upload size={13} />}
        <span>{uploading ? 'Ingesting...' : 'Ingest License (.lic.json)'}</span>
      </button>
    </div>
  );
};

export default LicenseSourceBanner;
