'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';
import LineItemBuilder, { LineItem, ProductLookup, computeTotals, toProductsJson } from '@/components/LineItemBuilder';

type OrderItem = { description: string; qty: number };
type OrderRow = {
  id: number; orderNo: string; client: { name: string; phone: string };
  subtotalTzs: string; vatTzs: string; totalTzs: string; paymentStatus: string; paymentMethod: string | null;
  paymentRef: string | null; deliveryType: string | null; deliveryAddress: string | null; status: string;
  productsJson: OrderItem[];
};
type ClientLookup = { id: number; name: string; company: string | null; phone: string };

const STATUS_STYLE: Record<string, string> = {
  NEW: 'bg-gray-100 text-gray-700', PACKED: 'bg-brand-charcoal text-white',
  OUT_FOR_DELIVERY: 'bg-blue-100 text-blue-700', DELIVERED: 'bg-green-100 text-green-700',
  CANCELLED: 'bg-red-100 text-red-700',
};
const emptyForm = { clientId: '', paymentMethod: 'CASH', deliveryType: 'PICKUP', deliveryAddress: '' };

export default function OrdersPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [orders, setOrders] = useState<OrderRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showForm, setShowForm] = useState(false);
  const [clients, setClients] = useState<ClientLookup[]>([]);
  const [products, setProducts] = useState<ProductLookup[]>([]);
  const [form, setForm] = useState(emptyForm);
  const [items, setItems] = useState<LineItem[]>([]);
  const [saving, setSaving] = useState(false);

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

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.clientId || items.length === 0) return;
    setSaving(true);
    try {
      const { subtotalTzs, vatTzs, totalTzs } = computeTotals(items);
      const d = await adminApiFetch('/admin/orders', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          clientId: Number(form.clientId), productsJson: toProductsJson(items),
          subtotalTzs, vatTzs, totalTzs, paymentMethod: form.paymentMethod,
          deliveryType: form.deliveryType, deliveryAddress: form.deliveryType === 'DELIVERY' ? form.deliveryAddress : undefined,
        }),
      });
      show('success', `${d.order.orderNo} created.`);
      setForm(emptyForm);
      setItems([]);
      setShowForm(false);
      load();
    } catch { show('error', 'Could not create that order.'); }
    finally { setSaving(false); }
  }

  async function updateStatus(id: number, orderNo: string, status: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/orders/${id}/status`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ status }) });
      setOrders((o) => o.map((row) => row.id === id ? { ...row, status } : row));
      show('success', `${orderNo} updated to ${status.replace(/_/g, ' ')}.`);
    } catch { show('error', 'Could not update that 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">Orders &bull; LUS-ORD &bull; {orders.length}</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 Order</button>
      </div>

      {loading ? <TableSkeleton rows={4} cols={4} /> : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {orders.map((o) => (
            <div key={o.id} className="bg-white border border-brand-border rounded-xl p-4 transition-all hover:shadow-md animate-fadeInUp">
              <div className="flex justify-between items-start mb-2">
                <div>
                  <p className="font-bold text-sm">{o.orderNo}</p>
                  <p className="text-xs text-gray-500">{o.client.phone} &bull; {o.productsJson?.map((i) => `${i.description} ${i.qty}pcs`).join(', ')}</p>
                </div>
                <select value={o.status} onChange={(e) => updateStatus(o.id, o.orderNo, e.target.value)}
                  className={`text-[10px] rounded-full px-2 py-1 border-0 shrink-0 transition-colors ${STATUS_STYLE[o.status]}`}>
                  {Object.keys(STATUS_STYLE).map((s) => <option key={s} value={s}>{s.replace(/_/g, ' ')}</option>)}
                </select>
              </div>

              <div className="grid grid-cols-3 gap-2 bg-brand-bg rounded-lg p-2.5 my-2 text-xs">
                <div><p className="text-gray-400">Subtotal</p><p className="font-semibold">{(Number(o.subtotalTzs) / 1e6).toFixed(2)}M</p></div>
                <div><p className="text-gray-400">VAT 18%</p><p className="font-semibold">{Number(o.vatTzs).toLocaleString()}</p></div>
                <div><p className="text-gray-400">Total</p><p className="font-bold">{(Number(o.totalTzs) / 1e6).toFixed(2)}M</p></div>
              </div>

              <div className="flex justify-between text-xs">
                <span className={o.paymentStatus === 'PAID' ? 'text-green-600' : 'text-yellow-600'}>
                  Paid: {o.paymentMethod || '—'} {o.paymentRef ? o.paymentRef : o.paymentStatus}
                </span>
                <span className="text-gray-400">{o.deliveryType === 'DELIVERY' ? (o.deliveryAddress || 'Delivery') : 'Pickup'}</span>
              </div>
            </div>
          ))}
          {orders.length === 0 && <p className="text-sm text-gray-400 col-span-2 text-center py-8">No orders yet.</p>}
        </div>
      )}

      {showForm && (
        <Modal title="New Order" onClose={() => setShowForm(false)} wide>
          <form onSubmit={submit} className="space-y-3">
            <select required value={form.clientId} onChange={(e) => setForm({ ...form, clientId: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-sm">
              <option value="">Select client…</option>
              {clients.map((c) => <option key={c.id} value={c.id}>{c.name} {c.company && `• ${c.company}`}</option>)}
            </select>

            <div className="grid grid-cols-2 gap-2">
              <select value={form.paymentMethod} onChange={(e) => setForm({ ...form, paymentMethod: e.target.value })}
                className="border border-brand-border rounded-lg px-2 py-1.5 text-sm">
                {['CASH', 'MPESA', 'TIGO_PESA', 'BANK'].map((m) => <option key={m} value={m}>{m.replace('_', ' ')}</option>)}
              </select>
              <select value={form.deliveryType} onChange={(e) => setForm({ ...form, deliveryType: e.target.value })}
                className="border border-brand-border rounded-lg px-2 py-1.5 text-sm">
                <option value="PICKUP">Pickup</option><option value="DELIVERY">Delivery</option>
              </select>
            </div>
            {form.deliveryType === 'DELIVERY' && (
              <input placeholder="Delivery address" value={form.deliveryAddress} onChange={(e) => setForm({ ...form, deliveryAddress: e.target.value })}
                className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-sm animate-fadeIn" />
            )}

            <LineItemBuilder items={items} onChange={setItems} products={products} />

            <button disabled={saving || !form.clientId || items.length === 0} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {saving ? 'Creating…' : 'Create Order'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
