'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch, adminApiUploadFile } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { TableSkeleton, StatCardSkeleton } from '@/components/Skeletons';
import Modal from '@/components/Modal';

type Cert = {
  id: number; name: string; category: string; holderType: string; expiryDate: string; issuedDate: string | null;
  documentUrl: string | null; notes: string | null; computedStatus: string;
  employee: { id: number; name: string } | null; product: { id: number; name: string; sku: string } | null;
};
type Employee = { id: number; name: string };
type Product = { id: number; name: string; sku: string };

const CATEGORY_LABEL: Record<string, string> = { REGISTRATION: 'Registration', INSURANCE: 'Insurance', STAFF_LICENSE: 'Staff License', PRODUCT_CERTIFICATION: 'Product Certification' };
const STATUS_BADGE: Record<string, string> = { VALID: 'bg-emerald-100 text-emerald-700', EXPIRING_SOON: 'bg-amber-100 text-amber-700', EXPIRED: 'bg-red-100 text-red-700' };
const STATUS_LABEL: Record<string, string> = { VALID: 'Valid', EXPIRING_SOON: 'Expiring Soon', EXPIRED: 'Expired' };
const emptyForm = { name: '', category: 'REGISTRATION', holderType: 'COMPANY', employeeId: '', productId: '', issuedDate: '', expiryDate: '', notes: '' };

export default function CompliancePage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [certs, setCerts] = useState<Cert[]>([]);
  const [funnel, setFunnel] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showForm, setShowForm] = useState(false);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [form, setForm] = useState(emptyForm);
  const [file, setFile] = useState<File | null>(null);
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/compliance', accessToken, appSecretProof);
      setCerts(d.certificates || []);
      setFunnel(d.funnel || {});
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function openForm() {
    setShowForm(true);
    if (!accessToken || !appSecretProof) return;
    try {
      const [e, p] = await Promise.all([
        adminApiFetch('/admin/compliance/lookups/employees', accessToken, appSecretProof),
        adminApiFetch('/admin/compliance/lookups/products', accessToken, appSecretProof),
      ]);
      setEmployees(e.employees || []);
      setProducts(p.products || []);
    } catch { show('error', 'Could not load employees/products.'); }
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.name || !form.expiryDate) return;
    setSaving(true);
    try {
      let documentUrl: string | undefined;
      if (file) {
        const uploaded = await adminApiUploadFile('/admin/compliance/upload-document', accessToken, appSecretProof, file, 'document');
        documentUrl = uploaded.url;
      }
      await adminApiFetch('/admin/compliance', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          name: form.name, category: form.category, holderType: form.holderType,
          employeeId: form.holderType === 'EMPLOYEE' && form.employeeId ? Number(form.employeeId) : undefined,
          productId: form.holderType === 'PRODUCT' && form.productId ? Number(form.productId) : undefined,
          issuedDate: form.issuedDate || undefined, expiryDate: form.expiryDate,
          documentUrl, notes: form.notes || undefined,
        }),
      });
      show('success', 'Certificate added.');
      setForm(emptyForm); setFile(null); setShowForm(false);
      load();
    } catch { show('error', 'Could not add that certificate.'); }
    finally { setSaving(false); }
  }

  async function remove(id: number) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/compliance/${id}`, accessToken, appSecretProof, { method: 'DELETE' });
      load();
    } catch { show('error', 'Could not delete that record.'); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-xl font-bold">Compliance Tracker &bull; admin.lussavara.co.tz</h1>
        <button onClick={openForm} className="bg-brand-red text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03]">+ Add Certificate</button>
      </div>

      {loading ? <StatCardSkeleton count={3} /> : (
        <div className="grid grid-cols-3 gap-3">
          <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4"><p className="text-[10px] uppercase text-emerald-600">Valid</p><p className="text-lg font-bold text-emerald-700">{funnel.VALID ?? 0}</p></div>
          <div className="bg-amber-50 border border-amber-200 rounded-xl p-4"><p className="text-[10px] uppercase text-amber-600">Expiring within 60d</p><p className="text-lg font-bold text-amber-700">{funnel.EXPIRING_SOON ?? 0}</p></div>
          <div className="bg-red-50 border border-red-200 rounded-xl p-4"><p className="text-[10px] uppercase text-red-500">Expired</p><p className="text-lg font-bold text-red-700">{funnel.EXPIRED ?? 0}</p></div>
        </div>
      )}

      {loading ? <TableSkeleton rows={6} cols={6} /> : (
        <div className="bg-white rounded-xl border border-brand-border overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg"><tr>
              <th className="p-3 text-left">Name</th><th className="p-3 text-left">Category</th>
              <th className="p-3 text-left">Holder</th><th className="p-3 text-left">Expiry</th>
              <th className="p-3 text-left">Status</th><th className="p-3 text-left">Document</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {certs.map((c) => (
                <tr key={c.id} className="border-t border-brand-border hover:bg-brand-bg">
                  <td className="p-3 font-semibold">{c.name}</td>
                  <td className="p-3">{CATEGORY_LABEL[c.category]}</td>
                  <td className="p-3">{c.employee?.name || c.product?.name || 'LUSSAVARA Co. Ltd'}</td>
                  <td className="p-3">{new Date(c.expiryDate).toLocaleDateString()}</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${STATUS_BADGE[c.computedStatus]}`}>{STATUS_LABEL[c.computedStatus]}</span></td>
                  <td className="p-3">{c.documentUrl ? <a href={c.documentUrl} target="_blank" rel="noreferrer" className="text-brand-red">View</a> : '—'}</td>
                  <td className="p-3"><button onClick={() => remove(c.id)} className="text-brand-red">Delete</button></td>
                </tr>
              ))}
              {certs.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-gray-400">No certificates tracked yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="Add Certificate / Registration" onClose={() => setShowForm(false)}>
          <form onSubmit={submit} className="space-y-2">
            <input required placeholder="Name (e.g. CRB Registration)" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <div className="grid grid-cols-2 gap-2">
              <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                {Object.entries(CATEGORY_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
              <select value={form.holderType} onChange={(e) => setForm({ ...form, holderType: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="COMPANY">Company-wide</option>
                <option value="EMPLOYEE">Staff member</option>
                <option value="PRODUCT">Product</option>
              </select>
            </div>
            {form.holderType === 'EMPLOYEE' && (
              <select value={form.employeeId} onChange={(e) => setForm({ ...form, employeeId: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">Select employee…</option>
                {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
              </select>
            )}
            {form.holderType === 'PRODUCT' && (
              <select value={form.productId} onChange={(e) => setForm({ ...form, productId: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">Select product…</option>
                {products.map((p) => <option key={p.id} value={p.id}>{p.name} ({p.sku})</option>)}
              </select>
            )}
            <div className="grid grid-cols-2 gap-2">
              <div><label className="text-[10px] text-gray-400 uppercase">Issued</label><input type="date" value={form.issuedDate} onChange={(e) => setForm({ ...form, issuedDate: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" /></div>
              <div><label className="text-[10px] text-gray-400 uppercase">Expires</label><input required type="date" value={form.expiryDate} onChange={(e) => setForm({ ...form, expiryDate: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" /></div>
            </div>
            <div>
              <label className="text-[10px] text-gray-400 uppercase">Document (optional)</label>
              <input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className="text-[11px]" />
            </div>
            <textarea placeholder="Notes" value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" rows={2} />
            <button disabled={saving} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Add Certificate'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
