'use client';

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

type Supplier = {
  id: number; name: string; contactName: string | null; phone: string | null; email: string | null;
  address: string | null; category: string | null; isActive: boolean; _count: { purchaseOrders: number };
};
const emptyForm = { name: '', contactName: '', phone: '', email: '', address: '', category: '', notes: '' };

export default function SuppliersPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/suppliers', accessToken, appSecretProof);
      setSuppliers(d.suppliers || []);
    } 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 submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.name) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/suppliers', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify(form) });
      show('success', 'Supplier added.');
      setForm(emptyForm); setShowForm(false);
      load();
    } catch { show('error', 'Could not add that supplier.'); }
    finally { setSaving(false); }
  }

  async function toggleActive(s: Supplier) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/suppliers/${s.id}/active`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ isActive: !s.isActive }) });
      load();
    } catch { show('error', 'Could not update that supplier.'); }
  }

  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">Suppliers &bull; admin.lussavara.co.tz</h1>
        <button onClick={() => setShowForm(true)} className="bg-brand-red text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03]">+ Add Supplier</button>
      </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">Contact</th>
              <th className="p-3 text-left">Category</th><th className="p-3 text-left">Orders</th>
              <th className="p-3 text-left">Status</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {suppliers.map((s) => (
                <tr key={s.id} className="border-t border-brand-border hover:bg-brand-bg">
                  <td className="p-3 font-semibold">{s.name}<br /><span className="text-gray-400 font-normal">{s.address || ''}</span></td>
                  <td className="p-3">{s.contactName || '—'}<br /><span className="text-gray-400">{s.phone || s.email || ''}</span></td>
                  <td className="p-3">{s.category || '—'}</td>
                  <td className="p-3">{s._count.purchaseOrders}</td>
                  <td className="p-3">{s.isActive ? <span className="text-emerald-600">Active</span> : <span className="text-gray-400">Inactive</span>}</td>
                  <td className="p-3"><button onClick={() => toggleActive(s)} className="text-brand-red">{s.isActive ? 'Deactivate' : 'Reactivate'}</button></td>
                </tr>
              ))}
              {suppliers.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-gray-400">No suppliers registered yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="Add Supplier" onClose={() => setShowForm(false)}>
          <form onSubmit={submit} className="space-y-2">
            <input required placeholder="Supplier name" 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">
              <input placeholder="Contact person" value={form.contactName} onChange={(e) => setForm({ ...form, contactName: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              <input placeholder="Category" 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" />
              <input placeholder="Phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              <input placeholder="Email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            </div>
            <input placeholder="Address" value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
            <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 Supplier'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
