'use client';

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

type POR = {
  id: number; poNumber: string; supplier: string; status: string; totalCostTzs: string | null;
  expectedDeliveryDate: string | null; createdAt: string; itemsJson: { productId?: number; sku?: string; name?: string; qty: number }[];
  supplierRef: { id: number; name: string } | null;
};
type SupplierLookup = { id: number; name: string; category: string | null };
type ProductLookup = { id: number; sku: string; name: string; stockQty: number };
type LineItem = { productId: number; sku: string; name: string; qty: number; unitCostTzs: number };

const LABEL: Record<string, string> = { DRAFT: 'Draft', SENT: 'Sent', RECEIVED: 'Received', CANCELLED: 'Cancelled' };
const BADGE: Record<string, string> = {
  DRAFT: 'bg-gray-100 text-gray-600', SENT: 'bg-blue-100 text-blue-700',
  RECEIVED: 'bg-emerald-100 text-emerald-700', CANCELLED: 'bg-red-100 text-red-700',
};

export default function PurchaseOrdersPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [pos, setPos] = useState<POR[]>([]);
  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 [suppliers, setSuppliers] = useState<SupplierLookup[]>([]);
  const [products, setProducts] = useState<ProductLookup[]>([]);
  const [supplierId, setSupplierId] = useState('');
  const [freeSupplier, setFreeSupplier] = useState('');
  const [items, setItems] = useState<LineItem[]>([]);
  const [expected, setExpected] = useState('');
  const [notes, setNotes] = useState('');
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/purchase-orders', accessToken, appSecretProof);
      setPos(d.purchaseOrders || []);
      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 [s, p] = await Promise.all([
        adminApiFetch('/admin/suppliers/lookup', accessToken, appSecretProof),
        adminApiFetch('/admin/purchase-orders/lookups/products', accessToken, appSecretProof),
      ]);
      setSuppliers(s.suppliers || []);
      setProducts(p.products || []);
    } catch { show('error', 'Could not load suppliers/products.'); }
  }

  function addItem(productId: string) {
    const p = products.find((x) => String(x.id) === productId);
    if (!p || items.some((i) => i.productId === p.id)) return;
    setItems((prev) => [...prev, { productId: p.id, sku: p.sku, name: p.name, qty: 10, unitCostTzs: 0 }]);
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || items.length === 0 || (!supplierId && !freeSupplier.trim())) return;
    setSaving(true);
    try {
      const d = await adminApiFetch('/admin/purchase-orders', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          supplierId: supplierId ? Number(supplierId) : undefined,
          supplier: !supplierId ? freeSupplier : undefined,
          itemsJson: items,
          expectedDeliveryDate: expected || undefined,
          notes: notes || undefined,
        }),
      });
      show('success', `${d.purchaseOrder.poNumber} created.`);
      setItems([]); setSupplierId(''); setFreeSupplier(''); setExpected(''); setNotes('');
      setShowForm(false);
      load();
    } catch { show('error', 'Could not create that purchase order.'); }
    finally { setSaving(false); }
  }

  async function setStatus(id: number, status: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/purchase-orders/${id}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      show('success', status === 'RECEIVED' ? 'Marked received — stock levels updated.' : `Marked ${LABEL[status].toLowerCase()}.`);
      load();
    } catch { show('error', 'Could not update that purchase order.'); }
  }

  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">Purchase Orders &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]">+ New Purchase Order</button>
      </div>

      {loading ? <StatCardSkeleton count={4} /> : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {['DRAFT', 'SENT', 'RECEIVED', 'CANCELLED'].map((s) => (
            <div key={s} className="bg-white border border-brand-border rounded-xl p-4">
              <p className="text-[10px] uppercase text-gray-400">{LABEL[s]}</p>
              <p className="text-lg font-bold">{funnel[s] ?? 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">PO No</th><th className="p-3 text-left">Supplier</th>
              <th className="p-3 text-left">Items</th><th className="p-3 text-left">Cost</th>
              <th className="p-3 text-left">Expected</th><th className="p-3 text-left">Status</th><th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {pos.map((po) => (
                <tr key={po.id} className="border-t border-brand-border hover:bg-brand-bg">
                  <td className="p-3 font-semibold">{po.poNumber}</td>
                  <td className="p-3">{po.supplierRef?.name || po.supplier}</td>
                  <td className="p-3 text-gray-500">{(po.itemsJson || []).map((i) => `${i.name || i.sku || 'item'} x${i.qty}`).join(', ')}</td>
                  <td className="p-3">{po.totalCostTzs ? `TZS ${Number(po.totalCostTzs).toLocaleString()}` : '—'}</td>
                  <td className="p-3">{po.expectedDeliveryDate ? new Date(po.expectedDeliveryDate).toLocaleDateString() : '—'}</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded-full text-[10px] ${BADGE[po.status]}`}>{LABEL[po.status]}</span></td>
                  <td className="p-3 space-x-2">
                    {po.status === 'DRAFT' && <button onClick={() => setStatus(po.id, 'SENT')} className="text-blue-600 font-semibold">Mark Sent</button>}
                    {(po.status === 'DRAFT' || po.status === 'SENT') && <button onClick={() => setStatus(po.id, 'RECEIVED')} className="text-emerald-600 font-semibold">Receive</button>}
                    {po.status !== 'RECEIVED' && po.status !== 'CANCELLED' && <button onClick={() => setStatus(po.id, 'CANCELLED')} className="text-brand-red">Cancel</button>}
                  </td>
                </tr>
              ))}
              {pos.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-gray-400">No purchase orders yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <Modal title="New Purchase Order" onClose={() => setShowForm(false)} wide>
          <form onSubmit={submit} className="space-y-3">
            <div className="grid grid-cols-2 gap-2">
              <select value={supplierId} onChange={(e) => setSupplierId(e.target.value)} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">— Type a supplier name instead —</option>
                {suppliers.map((s) => <option key={s.id} value={s.id}>{s.name}{s.category ? ` (${s.category})` : ''}</option>)}
              </select>
              <input placeholder="Or free-text supplier name" value={freeSupplier} onChange={(e) => setFreeSupplier(e.target.value)} disabled={!!supplierId} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs disabled:bg-gray-50" />
            </div>
            <div>
              <label className="text-[10px] text-gray-400 uppercase">Add product line</label>
              <select onChange={(e) => { addItem(e.target.value); e.target.value = ''; }} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
                <option value="">Select a product to add…</option>
                {products.map((p) => <option key={p.id} value={p.id}>{p.name} ({p.sku}) — stock {p.stockQty}</option>)}
              </select>
            </div>
            {items.length > 0 && (
              <div className="border border-brand-border rounded-lg divide-y divide-brand-border">
                {items.map((it, idx) => (
                  <div key={it.productId} className="flex items-center gap-2 p-2 text-xs">
                    <span className="flex-1">{it.name} ({it.sku})</span>
                    <input type="number" min={1} value={it.qty} onChange={(e) => setItems((prev) => prev.map((x, i) => i === idx ? { ...x, qty: Number(e.target.value) } : x))} className="w-16 border border-brand-border rounded px-1 py-0.5" placeholder="Qty" />
                    <input type="number" min={0} value={it.unitCostTzs} onChange={(e) => setItems((prev) => prev.map((x, i) => i === idx ? { ...x, unitCostTzs: Number(e.target.value) } : x))} className="w-24 border border-brand-border rounded px-1 py-0.5" placeholder="Unit cost" />
                    <button type="button" onClick={() => setItems((prev) => prev.filter((_, i) => i !== idx))} className="text-brand-red">✕</button>
                  </div>
                ))}
              </div>
            )}
            <div className="grid grid-cols-2 gap-2">
              <div>
                <label className="text-[10px] text-gray-400 uppercase">Expected delivery</label>
                <input type="date" value={expected} onChange={(e) => setExpected(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
              </div>
              <input placeholder="Notes" value={notes} onChange={(e) => setNotes(e.target.value)} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs mt-4" />
            </div>
            <button disabled={saving || items.length === 0} className="w-full bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Creating…' : 'Create Purchase Order'}</button>
          </form>
        </Modal>
      )}
    </div>
  );
}
