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

interface IssueLicenseFormProps {
  api: any;
  tenant: any;
  onSuccess: (message: string) => void;
  onError: (msg: string) => void;
}

interface LicenseFormState {
  term_name: 'Term 1' | 'Term 2' | 'Term 3' | 'Annual';
  academic_year: string;
  start_date: string;
  end_date: string;
  max_students: number;
  max_staff: number;
}

const todayIso = () => new Date().toISOString().slice(0, 10);
const plusDaysIso = (days: number) => new Date(Date.now() + days * 86400000).toISOString().slice(0, 10);

const INITIAL: LicenseFormState = {
  term_name: 'Term 1',
  academic_year: '2026',
  start_date: todayIso(),
  end_date: plusDaysIso(120),
  max_students: 1000,
  max_staff: 200,
};

export function IssueLicenseForm({ api, tenant, onSuccess, onError }: IssueLicenseFormProps) {
  const [form, setForm] = useState<LicenseFormState>(INITIAL);
  const [submitting, setSubmitting] = useState(false);
  const [copiedKey, setCopiedKey] = useState(false);
  const [issuedResult, setIssuedResult] = useState<any>(null);

  const handleCopyKey = (key: string) => {
    navigator.clipboard.writeText(key);
    setCopiedKey(true);
    setTimeout(() => setCopiedKey(false), 2000);
  };

  const handleDownloadArtifact = async (licId?: string) => {
    if (!tenant?.id) return;
    try {
      const endpoint = licId
        ? `/tenants/${tenant.id}/licenses/${licId}/download`
        : `/tenants/${tenant.id}/licenses/download`;
      const res = await api.get(endpoint, { 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'}_${(form.term_name || 'TERM').replace(/\s+/g, '')}_${form.academic_year}.lic.json`;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (err: any) {
      alert(`Download failed: ${err.message || 'Could not download artifact'}`);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!tenant) return;
    setSubmitting(true);
    try {
      const res = await api.post(`/tenants/${tenant.id}/licenses`, form);
      const data = res?.data || {};
      setIssuedResult({
        licId: data.id,
        licenseKey: data.license_key,
        licenseToken: data.license_token,
        artifact: data.artifact
      });
      onSuccess(`Issued ${form.term_name} signed token for ${tenant.name}`);
    } catch (err: any) {
      onError(err.response?.data?.error || err.message || 'License generation failed');
    } finally {
      setSubmitting(false);
    }
  };

  if (issuedResult) {
    return (
      <div className="space-y-4 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">Term License Issued & Signed</h3>
            <p className="text-xs text-muted-foreground font-mono">
              {tenant?.name} ({form.term_name} {form.academic_year})
            </p>
          </div>
        </div>

        <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-amber-400 flex items-center gap-1.5 font-mono">
              <Key size={14} /> Cryptographic License Key
            </span>
            <button
              type="button"
              onClick={() => handleCopyKey(issuedResult.licenseKey)}
              className="px-2.5 py-1 rounded-lg bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 font-mono text-xs font-bold transition-all flex items-center gap-1 border border-amber-500/30"
            >
              {copiedKey ? <Check size={12} className="text-emerald-400" /> : <Copy size={12} />}
              <span>{copiedKey ? 'Copied Key' : 'Copy Key'}</span>
            </button>
          </div>
          <div className="p-3 rounded-xl bg-slate-900 border border-slate-800 font-mono text-xs font-bold text-amber-300 select-all break-all">
            {issuedResult.licenseKey}
          </div>
        </div>

        <div className="flex items-center gap-3 pt-2">
          <button
            type="button"
            onClick={() => handleDownloadArtifact(issuedResult.licId)}
            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 Artifact (.lic.json)</span>
          </button>
          <button
            type="button"
            onClick={() => setIssuedResult(null)}
            className="py-2.5 px-4 bg-muted hover:bg-muted/80 text-foreground font-bold text-xs rounded-xl border border-border"
          >
            Renew Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid grid-cols-2 gap-3">
        <Field label="Term Name">
          <select
            value={form.term_name}
            onChange={e => setForm({ ...form, term_name: e.target.value as LicenseFormState['term_name'] })}
            className="form-input text-xs font-mono"
          >
            <option value="Term 1">Term 1</option>
            <option value="Term 2">Term 2</option>
            <option value="Term 3">Term 3</option>
            <option value="Annual">Annual License</option>
          </select>
        </Field>
        <Field label="Academic Year">
          <input
            type="text"
            value={form.academic_year}
            onChange={e => setForm({ ...form, academic_year: e.target.value })}
            className="form-input text-xs font-mono"
            placeholder="2026"
          />
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <Field label="Start Date">
          <input
            type="date"
            value={form.start_date}
            onChange={e => setForm({ ...form, start_date: e.target.value })}
            className="form-input text-xs font-mono"
          />
        </Field>
        <Field label="End Date">
          <input
            type="date"
            value={form.end_date}
            onChange={e => setForm({ ...form, end_date: e.target.value })}
            className="form-input text-xs font-mono"
          />
        </Field>
      </div>
      <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 ? 'Generating…' : 'Generate Cryptographic License Key'}
      </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 IssueLicenseForm;
