import { useEffect, useMemo, useState } from 'react';
import {
  Plus, RefreshCw, Search, AlertCircle, Loader2, X,
  Tag, ChevronLeft, ChevronRight, Play, Trash2,
  Percent, DollarSign, Receipt,
} from 'lucide-react';
import { useFinanceStore, Discount } from '../../store/finance';
import { useFinanceEngineStore } from '../../store/finance-engine';
import { Modal, ModalBody } from '../../components/ui/Modal';

const PAGE_SIZE = 25;

const scopeLabel: Record<string, string> = {
  all: 'All students',
  student: 'Specific student',
  group: 'Student group',
  fee_group: 'Specific fee group',
};

const scopeBadge: Record<string, string> = {
  all: 'bg-purple-50 text-purple-700 border-purple-200',
  student: 'bg-blue-50 text-blue-700 border-blue-200',
  group: 'bg-amber-50 text-amber-700 border-amber-200',
  fee_group: 'bg-emerald-50 text-emerald-700 border-emerald-200',
};

export default function Discounts() {
  const {
    discounts, loading, error,
    fetchDiscounts, createDiscount, updateDiscount, deleteDiscount,
  } = useFinanceStore();
  const {
    lastApply, busy: engineBusy, error: engineError,
    applyDiscount, revokeDiscount,
  } = useFinanceEngineStore();

  const [scope, setScope] = useState('');
  const [academicYear, setAcademicYear] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [editor, setEditor] = useState<{ row?: Discount; creating?: boolean } | null>(null);
  const [applyModal, setApplyModal] = useState<Discount | null>(null);
  const [confirmRevoke, setConfirmRevoke] = useState<Discount | null>(null);
  const [banner, setBanner] = useState<{ kind: 'ok' | 'err'; msg: string } | null>(null);

  useEffect(() => {
    fetchDiscounts({ scope: scope || undefined, academic_year: academicYear || undefined });
  }, [scope, academicYear, fetchDiscounts]);

  const filtered = useMemo(() => {
    if (!search.trim()) return discounts;
    const needle = search.toLowerCase();
    return discounts.filter((d) =>
      (d.name || '').toLowerCase().includes(needle) ||
      (d.reason || '').toLowerCase().includes(needle),
    );
  }, [discounts, search]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageRows = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  const save = async (data: Partial<Discount>) => {
    if (editor?.row && !editor.creating) {
      const r = await updateDiscount(editor.row.uid, data);
      if (r) setEditor(null);
    } else {
      const r = await createDiscount(data);
      if (r) setEditor(null);
    }
  };

  const onRevoke = async (d: Discount) => {
    const r = await revokeDiscount(d.uid);
    if (r) {
      setBanner({ kind: 'ok', msg: `Revoked ${d.name}; ${r.removed} fee link(s) cleared.` });
      await fetchDiscounts();
    } else {
      setBanner({ kind: 'err', msg: 'Failed to revoke.' });
    }
    setConfirmRevoke(null);
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Discounts</h1>
          <p className="text-text-muted mt-1 text-lg">
            Apply a percentage or fixed discount at the student, group, fee-group, or universal level.
          </p>
        </div>
        <button
          onClick={() => setEditor({ creating: true })}
          className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
        >
          <Plus size={18} /> New Discount
        </button>
      </div>

      {banner && (
        <div className={`rounded-2xl border p-4 flex items-center gap-3 text-sm ${
          banner.kind === 'ok' ? 'bg-emerald-50 border-emerald-200 text-emerald-700' : 'bg-red-50 border-red-200 text-red-700'
        }`}>
          {banner.kind === 'ok' ? <Tag size={18} /> : <AlertCircle size={18} />}
          <span className="flex-1">{banner.msg}</span>
          <button onClick={() => setBanner(null)} className="text-xs font-bold underline">Dismiss</button>
        </div>
      )}

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="relative sm:col-span-2">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input type="text" placeholder="Search name, reason…" value={search} onChange={(e) => { setSearch(e.target.value); setPage(0); }} className="w-full pl-9 pr-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
          </div>
          <select value={scope} onChange={(e) => { setScope(e.target.value); setPage(0); }} className="px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
            <option value="">All scopes</option>
            {Object.keys(scopeLabel).map((s) => <option key={s} value={s}>{scopeLabel[s]}</option>)}
          </select>
        </div>
        <p className="text-[0.65rem] mt-3 text-text-muted">{loading ? 'Loading…' : `${filtered.length} discount${filtered.length === 1 ? '' : 's'}`}</p>
      </div>

      {error && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
        </div>
      )}

      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/80 border-b border-border">
              <tr>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Discount</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Type</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Value</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Scope</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Year</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((d) => (
                  <tr key={d.uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md bg-primary/10 text-primary"><Tag size={14} /></div>
                        <div>
                          <p className="text-[0.85rem] font-semibold text-text">{d.name}</p>
                          {d.reason && <p className="text-[0.65rem] text-text-muted italic">{d.reason}</p>}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${
                        d.kind === 'percent' ? 'bg-rose-50 text-rose-700 border-rose-200' : 'bg-blue-50 text-blue-700 border-blue-200'
                      }`}>{d.kind}</span>
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-text whitespace-nowrap">
                      {d.kind === 'percent' ? `${Number(d.value)}%` : `$${Number(d.value).toFixed(2)}`}
                    </td>
                    <td className="px-6 py-4">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${scopeBadge[d.scope] || 'bg-muted text-text-muted'}`}>{scopeLabel[d.scope] || d.scope}</span>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-muted">{d.academic_year || '—'}</td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-1">
                        <button onClick={() => setApplyModal(d)} className="p-2 rounded-lg hover:bg-emerald-500 hover:text-white text-emerald-600 transition-all" title="Apply / re-apply discount" aria-label="Apply discount">
                          <Play size={16} />
                        </button>
                        <button onClick={() => setEditor({ row: d, creating: false })} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="Edit" aria-label="Edit">
                          <RefreshCw size={16} />
                        </button>
                        <button onClick={() => setConfirmRevoke(d)} className="p-2 rounded-lg hover:bg-red-500 hover:text-white text-text-muted transition-all" title="Revoke (undo links)" aria-label="Revoke discount">
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={6} className="px-6 py-10 text-center text-text-muted text-sm">No discounts yet — create one to apply.</td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="px-6 py-4 border-t border-border bg-muted/30 flex items-center justify-between">
          <span className="text-[0.7rem] font-bold text-text-muted">Page {page + 1} of {totalPages}</span>
          <div className="inline-flex items-center gap-2">
            <button disabled={page === 0} onClick={() => setPage((p) => Math.max(0, p - 1))} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              <ChevronLeft size={14} /> Prev
            </button>
            <button disabled={page + 1 >= totalPages} onClick={() => setPage((p) => p + 1)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              Next <ChevronRight size={14} />
            </button>
          </div>
        </div>
      </div>

      {editor && (
        <DiscountEditor
          initial={editor.row}
          isCreating={!!editor.creating}
          onSave={save}
          onClose={() => setEditor(null)}
        />
      )}

      {applyModal && (
        <ApplyDiscountModal
          discount={applyModal}
          busy={engineBusy}
          onClose={() => setApplyModal(null)}
          onApply={async (body) => {
            const r = await applyDiscount(applyModal.uid, body);
            if (r) {
              setBanner({ kind: 'ok', msg: `Applied to ${r.recipients} student(s); ${r.applied} fee link(s) created.` });
              setApplyModal(null);
            } else {
              setBanner({ kind: 'err', msg: 'Failed to apply discount.' });
            }
          }}
        />
      )}

      {confirmRevoke && (
        <Modal
          open={true}
          onClose={() => setConfirmRevoke(null)}
          title="Revoke discount?"
          icon={Trash2}
          maxWidth="max-w-sm"
          footer={
            <>
              <button onClick={() => setConfirmRevoke(null)} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
              <button onClick={() => onRevoke(confirmRevoke)} disabled={engineBusy} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-red-500 text-white text-sm font-bold hover:bg-red-600 disabled:opacity-40 transition-all">
                {engineBusy ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}
                <span>Revoke</span>
              </button>
            </>
          }
        >
          <ModalBody>
            <p className="text-sm text-text-muted">
              Soft-delete every fee link tied to <strong>{confirmRevoke.name}</strong>. Each fee's <code>discount_amount</code> is recomputed.
            </p>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}

function DiscountEditor({
  initial, isCreating, onSave, onClose,
}: {
  initial?: Discount;
  isCreating: boolean;
  onSave: (data: Partial<Discount>) => Promise<unknown>;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial?.name || '');
  const [reason, setReason] = useState(initial?.reason || '');
  const [kind, setKind] = useState<Discount['kind']>(initial?.kind || 'percent');
  const [value, setValue] = useState(String(initial?.value ?? 10));
  const [scope, setScope] = useState<Discount['scope']>(initial?.scope || 'all');
  const [scopeId, setScopeId] = useState(String(initial?.scope_id ?? ''));
  const [academicYear, setAcademicYear] = useState(initial?.academic_year || '2027');

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    await onSave({
      name: name.trim(),
      reason: reason.trim() || null,
      kind,
      value: Number(value) || 0,
      scope,
      scope_id: scope === 'all' ? null : Number(scopeId) || null,
      academic_year: academicYear.trim() || null,
    });
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={isCreating ? 'New discount' : `Edit ${initial?.name}`}
      icon={Percent}
      maxWidth="max-w-md"
      footer={
        <>
          <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
          <button type="submit" form="discount-form" disabled={!name.trim()} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark disabled:opacity-40 transition-all">
            <span>{isCreating ? 'Create' : 'Save'}</span>
          </button>
        </>
      }
    >
      <ModalBody>
        <form id="discount-form" onSubmit={submit} className="space-y-3">
          <Field label="Name *" value={name} onChange={setName} required />
          <Field label="Reason" value={reason} onChange={setReason} />
          <div className="grid grid-cols-2 gap-3">
            <label className="block">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Kind</span>
              <select value={kind} onChange={(e) => setKind(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
                <option value="percent">Percent</option>
                <option value="fixed">Fixed ($)</option>
              </select>
            </label>
            <Field label={kind === 'percent' ? 'Percent %' : 'Amount $'} type="number" value={value} onChange={setValue} />
          </div>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Scope</span>
            <select value={scope} onChange={(e) => setScope(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
              {Object.keys(scopeLabel).map((s) => <option key={s} value={s}>{scopeLabel[s]}</option>)}
            </select>
          </label>
          {scope !== 'all' && (
            <Field label={scope === 'group' ? 'Group UID (or numeric ID)' : scope === 'student' ? 'Student UID (or numeric ID)' : 'Fee group ID'} value={scopeId} onChange={setScopeId} />
          )}
          <Field label="Academic year" value={academicYear} onChange={setAcademicYear} />
        </form>
      </ModalBody>
    </Modal>
  );
}

function ApplyDiscountModal({
  discount, busy, onClose, onApply,
}: {
  discount: Discount;
  busy: boolean;
  onClose: () => void;
  onApply: (body: any) => Promise<unknown>;
}) {
  const [scope, setScope] = useState(discount.scope);
  const [scopeUid, setScopeUid] = useState('');
  const [classId, setClassId] = useState('');
  const [academicYear, setAcademicYear] = useState(discount.academic_year || '');
  const [capPercent, setCapPercent] = useState('90');

  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    const body: any = { cap_percent: Number(capPercent) || 90, academic_year: academicYear || undefined };
    if (scope !== 'all') {
      if (scope === 'student' || scope === 'group' || scope === 'fee_group') {
        if (scope === 'student' || scope === 'group') {
          if (!scopeUid.trim()) return;
          body.scope_uid = scopeUid.trim();
        } else if (scope === 'fee_group') {
          if (!classId.trim()) return;
          body.scope_uid = classId.trim();
        }
      }
    }
    body.scope = scope;
    onApply(body);
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={`Apply ${discount.name}`}
      icon={Play}
      maxWidth="max-w-md"
      footer={
        <>
          <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
          <button type="submit" form="apply-discount-form" disabled={busy} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-500 text-white text-sm font-bold hover:bg-emerald-600 disabled:opacity-40 transition-all">
            {busy ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
            <span>Apply</span>
          </button>
        </>
      }
    >
      <ModalBody>
        <form id="apply-discount-form" onSubmit={submit}>
          <p className="text-sm text-text-muted mb-3">
            {discount.kind === 'percent' ? `${Number(discount.value)}% off` : `$${Number(discount.value).toFixed(2)} off`} for each fee line that matches the scope.
            Capped at <strong>{capPercent || 90}%</strong> total discount per fee line (defense against stacking).
          </p>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Apply to</span>
            <select value={scope} onChange={(e) => setScope(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
              {Object.keys(scopeLabel).map((s) => <option key={s} value={s}>{scopeLabel[s]}</option>)}
            </select>
          </label>
          {(scope === 'student' || scope === 'group') && (
            <label className="block mt-3">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">{scope === 'student' ? 'Student UID' : 'Student group UID'}</span>
              <input value={scopeUid} onChange={(e) => setScopeUid(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary/30" />
            </label>
          )}
          {scope === 'fee_group' && (
            <label className="block mt-3">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Fee group ID</span>
              <input type="number" value={classId} onChange={(e) => setClassId(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
            </label>
          )}
          <div className="grid grid-cols-2 gap-3 mt-3">
            <Field label="Academic year" value={academicYear} onChange={setAcademicYear} />
            <Field label="Cap %" type="number" value={capPercent} onChange={setCapPercent} />
          </div>
        </form>
      </ModalBody>
    </Modal>
  );
}

function Field({ label, value, onChange, type = 'text', required }: {
  label: string; value: string; onChange: (v: string) => void; type?: string; required?: boolean;
}) {
  return (
    <label className="block">
      <span className="text-xs font-bold uppercase tracking-wider text-text-muted">{label}</span>
      <input type={type} required={required} value={value} onChange={(e) => onChange(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
    </label>
  );
}
