import React, { useState } from 'react';
import { RefreshCw, Copy, Check, CheckCircle2, Download, Key, ShieldCheck } from 'lucide-react';

interface OnboardSchoolFormProps {
  api: any;
  onSuccess: (result: { tenantName: string; tenantId: string; resultData?: any }) => void;
  onError: (msg: string) => void;
}

interface OnboardFormState {
  id: string;
  name: string;
  code: string;
  contact_email: string;
  phone: string;
  address: string;
  max_students: number;
  max_staff: number;
}

function generateUuid(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    return crypto.randomUUID();
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

export function OnboardSchoolForm({ api, onSuccess, onError }: OnboardSchoolFormProps) {
  const [form, setForm] = useState<OnboardFormState>(() => ({
    id: generateUuid(),
    name: '',
    code: '',
    contact_email: '',
    phone: '',
    address: '',
    max_students: 1000,
    max_staff: 200,
  }));

  const [submitting, setSubmitting] = useState(false);
  const [copiedId, setCopiedId] = useState(false);
  const [copiedToken, setCopiedToken] = useState(false);
  const [successData, setSuccessData] = useState<any>(null);

  const handleRegenerateId = () => {
    setForm(prev => ({ ...prev, id: generateUuid() }));
  };

  const handleCopyId = (idToCopy: string) => {
    navigator.clipboard.writeText(idToCopy);
    setCopiedId(true);
    setTimeout(() => setCopiedId(false), 2000);
  };

  const handleCopyToken = (tokenToCopy: string) => {
    navigator.clipboard.writeText(tokenToCopy);
    setCopiedToken(true);
    setTimeout(() => setCopiedToken(false), 2000);
  };

  const handleDownloadArtifact = async (tenantId: string, tenantCode: string) => {
    try {
      const res = await api.get(`/tenants/${tenantId}/licenses/download`, {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `license_${tenantCode}_TERM1_2026.lic.json`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (err: any) {
      alert(`Download failed: ${err.message || 'Could not download license artifact'}`);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const res = await api.post('/tenants', form);
      const data = res?.data || {};
      setSuccessData({
        tenantName: form.name,
        tenantId: data.tenant_id || form.id,
        tenantCode: data.code || form.code || 'SCH-1001',
        licenseKey: data.license_key,
        licenseToken: data.license_token,
        artifact: data.artifact
      });
      onSuccess({
        tenantName: form.name,
        tenantId: data.tenant_id || form.id,
        resultData: data
      });
    } catch (err: any) {
      onError(err.response?.data?.error || err.message || 'Onboarding failed');
    } finally {
      setSubmitting(false);
    }
  };

  if (successData) {
    return (
      <div className="space-y-5 animate-fadeIn">
        <div className="p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/30 flex items-center gap-3">
          <CheckCircle2 size={24} className="text-emerald-500 shrink-0" />
          <div>
            <h3 className="text-sm font-bold text-emerald-500">School Instance Registered & Signed</h3>
            <p className="text-xs text-muted-foreground font-mono">
              Give this Tenant ID to school administrators for local server provisioning.
            </p>
          </div>
        </div>

        {/* Tenant ID Badge Section */}
        <div className="p-4 rounded-2xl bg-slate-950 border border-slate-800 space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-xs font-bold uppercase tracking-wider text-sky-400 flex items-center gap-1.5">
              <ShieldCheck size={14} /> Generated Tenant ID (Instance Scope)
            </span>
            <button
              type="button"
              onClick={() => handleCopyId(successData.tenantId)}
              className="px-3 py-1 rounded-lg bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 font-mono text-xs font-bold transition-all flex items-center gap-1 border border-emerald-500/30"
            >
              {copiedId ? <Check size={12} /> : <Copy size={12} />}
              <span>{copiedId ? 'Copied ID' : 'Copy Tenant ID'}</span>
            </button>
          </div>
          <div className="p-3 rounded-xl bg-slate-900 border border-slate-800 font-mono text-sm font-bold text-emerald-300 break-all select-all">
            {successData.tenantId}
          </div>
        </div>

        {/* Credentials Details */}
        <div className="grid grid-cols-2 gap-3 text-xs font-mono">
          <div className="p-3 rounded-xl bg-muted/40 border border-border">
            <span className="text-muted-foreground block text-[0.68rem] uppercase font-bold">School Name</span>
            <span className="font-bold text-foreground truncate block">{successData.tenantName}</span>
          </div>
          <div className="p-3 rounded-xl bg-muted/40 border border-border">
            <span className="text-muted-foreground block text-[0.68rem] uppercase font-bold">School Code</span>
            <span className="font-bold text-primary block">{successData.tenantCode}</span>
          </div>
        </div>

        {/* License Token & Artifact Download */}
        {successData.licenseKey && (
          <div className="space-y-2">
            <div className="flex items-center justify-between text-xs font-mono">
              <span className="text-muted-foreground font-bold flex items-center gap-1">
                <Key size={13} className="text-amber-500" /> License Key
              </span>
              <button
                type="button"
                onClick={() => handleCopyToken(successData.licenseKey)}
                className="text-primary hover:underline flex items-center gap-1 text-[0.7rem]"
              >
                {copiedToken ? <Check size={11} className="text-emerald-500" /> : <Copy size={11} />}
                <span>{copiedToken ? 'Copied' : 'Copy Key'}</span>
              </button>
            </div>
            <div className="p-3 rounded-xl bg-slate-950 border border-slate-800 font-mono text-[0.68rem] text-amber-300 break-all select-all">
              {successData.licenseKey}
            </div>
          </div>
        )}

        <div className="pt-2 flex items-center gap-3">
          <button
            type="button"
            onClick={() => handleDownloadArtifact(successData.tenantId, successData.tenantCode)}
            className="flex-1 py-2.5 px-3 bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs rounded-xl transition-all flex items-center justify-center gap-1.5 shadow-sm"
          >
            <Download size={14} />
            <span>Download License (.lic.json)</span>
          </button>
          <button
            type="button"
            onClick={() => setSuccessData(null)}
            className="py-2.5 px-4 bg-muted hover:bg-muted/80 text-foreground font-bold text-xs rounded-xl border border-border"
          >
            Onboard Another
          </button>
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {/* Generated Tenant ID Field */}
      <Field label="Tenant ID (Auto-Generated Instance Scope)">
        <div className="flex items-center gap-2">
          <input
            type="text"
            required
            value={form.id}
            onChange={e => setForm({ ...form, id: e.target.value })}
            className="form-input text-xs font-mono bg-slate-950/60 text-sky-400 font-bold tracking-tight border-sky-900/50"
            placeholder="5b39bcb5-506a-456d-b7cb-91730b397cc1"
          />
          <button
            type="button"
            onClick={handleRegenerateId}
            className="p-2.5 rounded-xl bg-muted hover:bg-muted/80 text-foreground border border-border transition-colors shrink-0"
            title="Generate new Tenant ID"
          >
            <RefreshCw size={14} />
          </button>
          <button
            type="button"
            onClick={() => handleCopyId(form.id)}
            className="p-2.5 rounded-xl bg-muted hover:bg-muted/80 text-primary border border-border transition-colors shrink-0"
            title="Copy Tenant ID"
          >
            {copiedId ? <Check size={14} className="text-emerald-500" /> : <Copy size={14} />}
          </button>
        </div>
        <p className="text-[0.68rem] text-muted-foreground font-mono mt-1">
          Unique UUID scoping database isolation & cryptographic signatures for this school.
        </p>
      </Field>

      <Field label="School Name" required>
        <input
          type="text"
          required
          value={form.name}
          onChange={e => setForm({ ...form, name: e.target.value })}
          placeholder="e.g. St. Georges High School"
          className="form-input text-xs font-mono"
        />
      </Field>

      <div className="grid grid-cols-2 gap-3">
        <Field label="School Code">
          <input
            type="text"
            value={form.code}
            onChange={e => setForm({ ...form, code: e.target.value })}
            placeholder="SCH-1001"
            className="form-input text-xs font-mono"
          />
        </Field>
        <Field label="Contact Email">
          <input
            type="email"
            value={form.contact_email}
            onChange={e => setForm({ ...form, contact_email: e.target.value })}
            placeholder="admin@school.ac.zw"
            className="form-input text-xs font-mono"
          />
        </Field>
      </div>

      <Field label="Contact Phone">
        <input
          type="tel"
          value={form.phone}
          onChange={e => setForm({ ...form, phone: e.target.value })}
          placeholder="+263 77 123 4567"
          className="form-input text-xs font-mono"
        />
      </Field>

      <Field label="Address">
        <input
          type="text"
          value={form.address}
          onChange={e => setForm({ ...form, address: e.target.value })}
          placeholder="123 Borrowdale Road, Harare"
          className="form-input text-xs font-mono"
        />
      </Field>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Max Learner Cap">
          <input
            type="number"
            min={1}
            value={form.max_students}
            onChange={e => setForm({ ...form, max_students: parseInt(e.target.value, 10) || 0 })}
            className="form-input text-xs font-mono"
          />
        </Field>
        <Field label="Max Staff Cap">
          <input
            type="number"
            min={1}
            value={form.max_staff}
            onChange={e => setForm({ ...form, max_staff: parseInt(e.target.value, 10) || 0 })}
            className="form-input text-xs font-mono"
          />
        </Field>
      </div>

      <button
        type="submit"
        disabled={submitting}
        className="w-full py-3 bg-primary hover:bg-primary-dark text-white font-bold text-xs uppercase tracking-wider rounded-xl transition-all mt-4 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
      >
        {submitting ? 'Registering…' : 'Confirm & Issue Initial License'}
      </button>
    </form>
  );
}

function Field({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-bold uppercase tracking-wider text-muted-foreground mb-1">
        {label}
        {required && <span className="text-rose-500 ml-1">*</span>}
      </label>
      {children}
    </div>
  );
}

export default OnboardSchoolForm;
