import { useState, useEffect } from 'react';
import api from '../utils/api';
import { fmt, fmtD, NOW, addD, toLocal, REFERRAL_BONUS } from '../utils/helpers';
import { Icons } from '../components/icons/Icons';
import { Badge, VipBadge, ClientName } from '../components/ui/Badge';
import Modal from '../components/ui/Modal';
import Confirm from '../components/ui/Confirm';
import Field from '../components/ui/Field';
import PhoneInput from '../components/ui/PhoneInput';
import SearchSelect from '../components/ui/SearchSelect';
import jsPDF from 'jspdf';
import 'jspdf-autotable';
import OrderDetailModal from '../components/ui/OrderDetailModal';

export default function Orders({ products, clients, orders, paymentMethods, refetch, prefill, prefillProduct }) {
  const [modal, setModal] = useState(prefill || prefillProduct ? 'new' : null);
  const [filter, setFilter] = useState('all');
  const [orderSort, setOrderSort] = useState('newest');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [orderSearch, setOrderSearch] = useState('');
  const [cfm, setCfm] = useState(null);
  const [viewOrder, setViewOrder] = useState(null);
  const [shipCfm, setShipCfm] = useState(null);
  const [errors, setErrors] = useState({});
  const [successOrder, setSuccessOrder] = useState(null);
  const [oC, setOC] = useState(prefill || '');
  const [oI, setOI] = useState(prefillProduct ? [{ productId: prefillProduct, qty: '' }] : [{ productId: '', qty: '' }]);
  const [oDT, setODT] = useState('none');
  const [oDV, setODV] = useState(0);
  const [oCP, setOCP] = useState('');
  const [oM, setOM] = useState(paymentMethods[0] || '');
  const [oNote, setONote] = useState('');
  const [oShipAddr, setOShipAddr] = useState('');
  const [oFuE, setOFuE] = useState(false);
  const [oFuD, setOFuD] = useState('');
  const [oFuN, setOFuN] = useState('Check progress & ask about refill');
  const [showNC, setShowNC] = useState(false);
  const [nc, setNc] = useState({ name: '', phone: '', email: '', address: '', allergies: '', notes: '', birth_date: '' });
  const [oRef, setORef] = useState('');
  const [vipDiscOn, setVipDiscOn] = useState(true);
  const [oAllergies, setOAllergies] = useState('');

  const SHORTCUTS = [{ l: '1W', d: 7 }, { l: '2W', d: 14 }, { l: '3W', d: 21 }, { l: '4W', d: 28 }, { l: '5W', d: 35 }, { l: '6W', d: 42 }, { l: '8W', d: 56 }];
  const selClient = clients.find((c) => c.id === oC);

  const handleCC = (cid) => { setOC(cid); const cl = clients.find((c) => c.id === cid); if (cl) { setOShipAddr(cl.address || ''); setVipDiscOn(!!cl.is_vip); setOAllergies(cl.allergies || ''); } };

  useEffect(() => { if (prefill) { handleCC(prefill); setModal('new'); } }, [prefill]);
  useEffect(() => { if (prefillProduct) { setOI([{ productId: prefillProduct, qty: '' }]); setModal('new'); } }, [prefillProduct]);

  const filtered = orders.filter((o) => {
    if (filter !== 'all') {
      if (filter === 'processing' || filter === 'shipped') { if (!(o.delivery_status === filter && o.status === 'confirmed')) return false; }
      else { if (o.status !== filter) return false; }
    }
    if (dateFrom) { const d = toLocal(o.order_date); if (d < dateFrom) return false; }
    if (dateTo) { const d = toLocal(o.order_date); if (d > dateTo) return false; }
    if (orderSearch.trim()) {
      const q = orderSearch.toLowerCase();
      const cl = clients.find((c) => c.id === o.client_id);
      const clientName = (cl?.name || '').toLowerCase();
      const itemNames = (o.items || []).map((i) => products.find((p) => p.id === i.product_id)?.name || '').join(' ').toLowerCase();
      const orderId = (o.id || '').toLowerCase();
      const payMethod = (o.payment_method || '').toLowerCase();
      if (!clientName.includes(q) && !itemNames.includes(q) && !orderId.includes(q) && !payMethod.includes(q)) return false;
    }
    return true;
  }).sort((a, b) => orderSort === 'oldest'
    ? (a.order_date || '').localeCompare(b.order_date || '')
    : (b.order_date || '').localeCompare(a.order_date || '')
  );

  const calc = () => {
    const sub = oI.reduce((s, i) => { const p = products.find((x) => x.id === i.productId); return s + (p ? parseFloat(p.retail_price) * (+i.qty || 0) : 0); }, 0);
    let vd = 0; if (selClient?.is_vip && vipDiscOn) vd = sub * 0.1;
    let av = sub - vd, ed = 0, totalPct = 0;
    if (oDT === 'percent') { ed = av * (+oDV || 0) / 100; totalPct = sub > 0 ? (vd + ed) / sub * 100 : 0; }
    else if (oDT === 'fixed') { ed = +oDV || 0; totalPct = sub > 0 ? (vd + ed) / sub * 100 : 0; }
    else if (oDT === 'custom') { const t = +oCP || 0; return { sub, vd, ed: 0, t, totalDisc: sub - t, totalPct: sub > 0 ? (sub - t) / sub * 100 : 0 }; }
    else { totalPct = sub > 0 ? vd / sub * 100 : 0; }
    return { sub, vd, ed, t: Math.max(0, av - ed), totalDisc: vd + ed, totalPct };
  };

  const saveNC = async () => {
    const e = {};
    if (!nc.name?.trim()) e.ncName = 'Name is required';
    if (!nc.phone?.trim()) e.ncPhone = 'Phone is required';
    if (!nc.email?.trim()) e.ncEmail = 'Email is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(nc.email)) e.ncEmail = 'Invalid email format';
    if (!nc.address?.trim()) e.ncAddress = 'Address is required';
    if (!nc.allergies?.trim()) e.ncAllergies = 'Allergies is required (or type "None")';
    if (!nc.birth_date) e.ncBirth = 'Date of birth is required';
    if (Object.keys(e).length > 0) { setErrors(e); return; }
    try { const res = await api.post('/clients', { ...nc, birth_date: nc.birth_date || null, is_vip: false, referred_by: oRef || null }); setOC(res.data.id); setOShipAddr(nc.address || ''); setOAllergies(nc.allergies || ''); setShowNC(false); setNc({ name: '', phone: '', email: '', address: '', allergies: '', notes: '', birth_date: '' }); setErrors({}); refetch(); } catch (err) { alert(err.response?.data?.error || 'Error'); }
  };

  const validate = () => { const e = {}; if (!oC) e.client = 'Please select a client'; if (oI.some((i) => !i.productId)) e.products = 'Select all products'; if (oI.some((i) => !i.qty || +i.qty < 1)) e.products = 'Qty must be ≥ 1'; setErrors(e); return Object.keys(e).length === 0; };

  const submit = async () => {
    if (!validate()) return;
    const { sub, t: total, totalDisc, totalPct } = calc();
    const items = oI.map((i) => { const p = products.find((x) => x.id === i.productId); return { product_id: i.productId, qty: +i.qty, unit_price: parseFloat(p.retail_price), line_total: parseFloat(p.retail_price) * +i.qty }; });
    for (const i of items) { const p = products.find((x) => x.id === i.product_id); if (p.stock_qty < i.qty) { alert(`Not enough stock for ${p.name}! Available: ${p.stock_qty}`); return; } }
    try {
      const res = await api.post('/orders', { client_id: oC, items, subtotal: sub, discount_pct: Math.round(totalPct), discount_amt: totalDisc, total, payment_method: oM, shipping_address: oShipAddr, notes: oNote, vip_discount_applied: selClient?.is_vip && vipDiscOn, referral_from: oRef || null, followUp: oFuE && oFuD ? { date: oFuD, note: oFuN } : null, allergies_update: selClient && oAllergies !== selClient.allergies ? oAllergies : undefined });
      setModal(null); resetForm(); refetch();
      setSuccessOrder(res.data);
    } catch (err) { alert(err.response?.data?.error || 'Error creating order'); }
  };

  const resetForm = () => { setOI([{ productId: '', qty: '' }]); setODT('none'); setODV(0); setOCP(''); setOC(''); setONote(''); setOShipAddr(''); setOFuE(false); setOFuD(''); setORef(''); setVipDiscOn(true); setOAllergies(''); setErrors({}); };
  const handleCancel = async () => { try { await api.put(`/orders/${cfm.o.id}/cancel`); setCfm(null); refetch(); } catch {} };
  const handleRefund = async () => { try { await api.put(`/orders/${cfm.o.id}/refund`); setCfm(null); refetch(); } catch {} };
  const handleDelivery = async (id, status) => { try { await api.put(`/orders/${id}/delivery`, { status }); refetch(); } catch {} };

  const { sub, vd, ed, t: total, totalDisc, totalPct } = calc();

  // Get already selected product IDs (excluding current index)
  const getSelectedIds = (excludeIdx) => oI.filter((_, i) => i !== excludeIdx).map((i) => i.productId).filter(Boolean);

  // Get max qty for a product
  const getMaxQty = (productId) => {
    const p = products.find((x) => x.id === productId);
    return p ? p.stock_qty : 999;
  };

  // Export orders to PDF
  const exportPDF = () => {
    const doc = new jsPDF({ orientation: 'landscape' });
    doc.setFontSize(18); doc.setTextColor(59, 130, 246);
    doc.text('PeptideOS - Orders Report', 14, 18);
    doc.setFontSize(10); doc.setTextColor(100);
    doc.text(`Generated: ${new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}`, 14, 25);
    doc.text(`Filter: ${filter === 'all' ? 'All' : filter} | Sort: ${orderSort} | Total: ${filtered.length} orders`, 14, 31);
    doc.autoTable({
      startY: 37,
      head: [['#', 'Order ID', 'Date', 'Client', 'Products', 'Qty', 'Subtotal', 'Discount', 'Total', 'Payment', 'Status', 'Delivery']],
      body: filtered.map((o, idx) => {
        const cl = clients.find((c) => c.id === o.client_id);
        const itemsStr = (o.items || []).map((i) => { const p = products.find((x) => x.id === i.product_id); return `${p?.name || '?'} (${p?.mg}mg/${p?.ml}ml)`; }).join(', ');
        const qtyStr = (o.items || []).map((i) => i.qty).join(', ');
        return [idx + 1, o.id, fmtD(o.order_date), cl?.name || '?', itemsStr.length > 45 ? itemsStr.slice(0, 45) + '...' : itemsStr, qtyStr, `$${parseFloat(o.subtotal).toFixed(2)}`, parseFloat(o.discount_amt) > 0 ? `-$${parseFloat(o.discount_amt).toFixed(2)}` : '-', `$${parseFloat(o.total).toFixed(2)}`, o.payment_method, o.status, o.delivery_status];
      }),
      styles: { fontSize: 7, cellPadding: 2 },
      headStyles: { fillColor: [59, 130, 246], textColor: 255, fontStyle: 'bold', fontSize: 8 },
      alternateRowStyles: { fillColor: [245, 247, 250] },
      columnStyles: { 0: { cellWidth: 8 }, 6: { halign: 'right' }, 7: { halign: 'right' }, 8: { halign: 'right', fontStyle: 'bold' } },
    });
    const totalRev = filtered.filter((o) => o.status === 'confirmed').reduce((s, o) => s + parseFloat(o.total), 0);
    const finalY = doc.lastAutoTable.finalY + 8;
    doc.setFontSize(10); doc.setTextColor(40);
    doc.text(`Total Revenue (confirmed): $${totalRev.toFixed(2)}`, 14, finalY);
    doc.text(`Total Orders: ${filtered.length}`, 140, finalY);
    const pageCount = doc.internal.getNumberOfPages();
    for (let i = 1; i <= pageCount; i++) { doc.setPage(i); doc.setFontSize(8); doc.setTextColor(150); doc.text(`PeptideOS Orders Report — Page ${i} of ${pageCount}`, doc.internal.pageSize.getWidth() / 2, doc.internal.pageSize.getHeight() - 8, { align: 'center' }); }
    doc.save('PeptideOS-Orders.pdf');
  };

  // Export orders to Excel via backend
  const exportExcel = async () => {
    try { const res = await api.get('/reports/export', { responseType: 'blob' }); const url = URL.createObjectURL(new Blob([res.data])); const a = document.createElement('a'); a.href = url; a.download = 'PeptideOS-Orders.xlsx'; a.click(); } catch {}
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-1">
        <div><h1 className="text-xl font-bold mb-0.5">Orders</h1><p className="text-t2 text-xs mb-5">{orders.length} total</p></div>
        <div className="flex gap-1.5">
          <button className="bg-gr text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-gr/90" onClick={exportExcel}><Icons.Download /> Excel</button>
          <button className="bg-rd text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-rd/90" onClick={exportPDF}><Icons.Download /> PDF</button>
          <button className="bg-ac text-white px-3.5 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1.5 hover:bg-ac/90" onClick={() => { setModal('new'); setErrors({}); }}><Icons.Plus /> New Order</button>
        </div>
      </div>

      {/* Search & Filters */}
      <div className="flex gap-2 mb-3 items-center flex-wrap">
        <div className="flex items-center gap-1.5 bg-s2 border border-bd rounded-md px-2.5 py-1 min-w-[200px]">
          <Icons.Search />
          <input className="bg-transparent border-none text-t1 text-[12px] w-full outline-none" placeholder="Search client, product, order ID, payment..." value={orderSearch} onChange={(e) => setOrderSearch(e.target.value)} />
        </div>
        <select className="bg-s2 border border-bd rounded-md text-t1 text-[12px] px-3 py-1.5 outline-none" value={filter} onChange={(e) => setFilter(e.target.value)}>
          <option value="all">All Status</option>
          <option value="confirmed">Confirmed</option>
          <option value="processing">Processing</option>
          <option value="shipped">Shipped</option>
          <option value="cancelled">Cancelled</option>
          <option value="refunded">Refunded</option>
        </select>
        <select className="bg-s2 border border-bd rounded-md text-t1 text-[12px] px-3 py-1.5 outline-none" value={orderSort} onChange={(e) => setOrderSort(e.target.value)}>
          <option value="newest">Newest First</option>
          <option value="oldest">Oldest First</option>
        </select>
        <div className="flex items-center gap-1.5">
          <input type="date" className="bg-s2 border border-bd rounded-md text-t1 text-[11px] px-2 py-1 outline-none w-[120px]" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} />
          <span className="text-t3 text-[11px]">→</span>
          <input type="date" className="bg-s2 border border-bd rounded-md text-t1 text-[11px] px-2 py-1 outline-none w-[120px]" value={dateTo} onChange={(e) => setDateTo(e.target.value)} />
          {(dateFrom || dateTo) && (<button className="text-[10px] text-rd hover:text-rd/80" onClick={() => { setDateFrom(''); setDateTo(''); }}>Clear</button>)}
        </div>
        <span className="text-[11px] text-t3 ml-auto">{filtered.length} results</span>
      </div>

      <div className="bg-s1 border border-bd rounded-[10px] p-4 mb-3">
        <div className="overflow-x-auto">
          <table className="w-full"><thead><tr>
            {['#', 'Client', 'Date', 'Items', 'Total', 'Ship', 'Status', ''].map((h) => (<th key={h} className="text-left p-2 text-[10px] font-bold uppercase text-t2 border-b border-bd whitespace-nowrap">{h}</th>))}
          </tr></thead><tbody>
            {filtered.map((o) => { const cl = clients.find((c) => c.id === o.client_id); return (
              <tr key={o.id} className="cursor-pointer hover:bg-s2/50" onClick={() => setViewOrder(o)}>
                <td className="p-2 border-b border-bd text-[11px] text-t2">#{o.id}</td>
                <td className="p-2 border-b border-bd"><ClientName client={cl} /></td>
                <td className="p-2 border-b border-bd whitespace-nowrap">
                  <div className="text-[13px]">{fmtD(o.order_date)}</div>
                  {o.created_at && <div className="text-[9px] text-t3">{new Date(o.created_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}</div>}
                </td>
                <td className="p-2 border-b border-bd text-[11px] max-w-[160px]">{(o.items || []).map((i) => `${products.find((x) => x.id === i.product_id)?.name || '?'} ×${i.qty}`).join(', ')}</td>
                <td className="p-2 border-b border-bd font-bold">{fmt(o.total)}{parseFloat(o.discount_amt) > 0 && <div className="text-[9px] text-yl">-{fmt(o.discount_amt)}</div>}</td>
                <td className="p-2 border-b border-bd" onClick={(e) => e.stopPropagation()}>
                  {o.status === 'confirmed' ? (<select className={`text-[10px] px-1.5 py-0.5 font-bold rounded-full border-none outline-none ${o.delivery_status === 'shipped' ? 'bg-ac/15 text-ac' : 'bg-or/15 text-or'}`} value={o.delivery_status} onChange={(e) => { if (e.target.value === 'shipped') setShipCfm({ id: o.id }); else handleDelivery(o.id, e.target.value); }}><option value="processing">Processing</option><option value="shipped">Shipped</option></select>) : <Badge s={o.status} />}
                </td>
                <td className="p-2 border-b border-bd"><Badge s={o.status} /></td>
                <td className="p-2 border-b border-bd" onClick={(e) => e.stopPropagation()}>
                  {o.status === 'confirmed' && (<div className="flex gap-1">
                    <button className="px-1.5 py-0.5 rounded text-[10px] border border-bd text-t2 hover:bg-s2" onClick={() => setViewOrder(o)}><Icons.Eye /></button>
                    <button className="px-1.5 py-0.5 rounded text-[10px] border border-bd text-yl hover:bg-s2" onClick={() => setCfm({ t: 'cancel', o })}>Cancel</button>
                    <button className="px-1.5 py-0.5 rounded text-[10px] border border-bd text-rd hover:bg-s2" onClick={() => setCfm({ t: 'refund', o })}>Refund</button>
                  </div>)}
                </td>
              </tr>); })}
          </tbody></table>
        </div>
      </div>

      <OrderDetailModal open={!!viewOrder} order={viewOrder} products={products} clients={clients} onClose={() => setViewOrder(null)} />
      <Confirm open={!!shipCfm} onClose={() => setShipCfm(null)} icon="🚚" title="Mark as Shipped?" desc="Confirm shipped?" cStyle="s" cLabel="Yes, Shipped" details={[{ i: '📦', t: 'Package on the way' }]} onConfirm={() => { handleDelivery(shipCfm.id, 'shipped'); setShipCfm(null); }} />
      <Confirm open={cfm?.t === 'cancel'} onClose={() => setCfm(null)} icon="⚠️" title="Cancel Order?" desc={`Cancel #${cfm?.o?.id}?`} cStyle="w" cLabel="Yes, Cancel" details={[{ i: '📦', t: 'Stock RETURNED', c: '#22c55e' }, { i: '🔄', t: 'Restorable', c: '#3b82f6' }]} onConfirm={handleCancel} />
      <Confirm open={cfm?.t === 'refund'} onClose={() => setCfm(null)} icon="🛡️" title="Refund Order?" desc={`Refund #${cfm?.o?.id}?`} cStyle="d" cLabel="Yes, Refund" details={[{ i: '⚠️', t: 'Stock NOT returned', c: '#ef4444' }, { i: '📉', t: 'Recorded as LOSS', c: '#ef4444' }]} onConfirm={handleRefund} />

      {/* NEW ORDER MODAL */}
      <Modal open={modal === 'new'} onClose={() => setModal(null)} title="New Order" w={600}>
        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="text-[11px] font-bold text-ac uppercase mb-2">Client</div>
          {!showNC ? (<>
            <div className="flex gap-2">
              <SearchSelect
                className="flex-1"
                value={oC}
                onChange={(val) => handleCC(val)}
                placeholder="Search client by name or phone..."
                options={clients.filter((c) => !c.is_deleted).map((c) => ({
                  value: c.id,
                  label: c.name,
                  searchText: `${c.name} ${c.phone || ''} ${c.email || ''}`,
                  data: c,
                }))}
                renderOption={(opt) => (
                  <div>
                    <div className="font-semibold flex items-center gap-1">
                      {opt.data.is_vip ? <span className="text-gold"><Icons.Crown /></span> : null}
                      {opt.data.name}
                    </div>
                    <div className="text-[11px] text-t2">{opt.data.phone}{opt.data.email ? ` · ${opt.data.email}` : ''}</div>
                  </div>
                )}
                renderSelected={(opt) => (
                  <span className="flex items-center gap-1">
                    {opt.data.is_vip ? <span className="text-gold"><Icons.Crown /></span> : null}
                    <span className="text-t1 font-semibold">{opt.data.name}</span>
                    <span className="text-t2 text-[11px]">— {opt.data.phone}</span>
                  </span>
                )}
              />
              <button className="px-3 py-1.5 rounded-md border border-bd text-t2 text-xs font-semibold whitespace-nowrap hover:bg-s1" onClick={() => setShowNC(true)}><Icons.Plus /> New</button>
            </div>
            {errors.client && <div className="text-[11px] text-rd mt-0.5">{errors.client}</div>}
            {selClient && (<div className="mt-1.5"><div className="text-[11px] text-t2 flex items-center gap-1"><Icons.Map /> {selClient.address || 'No address'}</div>{selClient.is_vip ? <div className="mt-1 flex items-center gap-1.5"><VipBadge /><span className="text-[11px] text-gold">Auto 10% VIP discount</span></div> : null}</div>)}
          </>) : (
            <div className="bg-bg rounded-md p-2.5 border border-ac/30">
              <div className="text-[11px] font-bold text-ac mb-1.5">Quick Add Client</div>
              <div className="flex gap-2.5 mb-2.5">
                <Field label="Name" required error={errors.ncName}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={nc.name} onChange={(e) => setNc({ ...nc, name: e.target.value })} /></Field>
                <Field label="Phone" required error={errors.ncPhone}><PhoneInput value={nc.phone} onChange={(v) => setNc({ ...nc, phone: v })} /></Field>
              </div>
              <div className="flex gap-2.5 mb-2.5">
                <Field label="Email" required error={errors.ncEmail}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={nc.email} onChange={(e) => setNc({ ...nc, email: e.target.value })} placeholder="name@email.com" /></Field>
                <Field label="Address" required error={errors.ncAddress}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={nc.address} onChange={(e) => setNc({ ...nc, address: e.target.value })} /></Field>
              </div>
              <div className="flex gap-2.5 mb-2.5">
                <Field label="Date of Birth" required error={errors.ncBirth}><input type="date" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={nc.birth_date || ''} onChange={(e) => setNc({ ...nc, birth_date: e.target.value })} /></Field>
                <Field label="Allergies" required error={errors.ncAllergies}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={nc.allergies} onChange={(e) => setNc({ ...nc, allergies: e.target.value })} placeholder="e.g. Penicillin (or None)" /></Field>
              </div>
              <Field label="Notes (optional)"><textarea className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] min-h-[36px] resize-y" value={nc.notes} onChange={(e) => setNc({ ...nc, notes: e.target.value })} placeholder="Client notes..." /></Field>
              <div className="flex gap-1.5 justify-end">
                <button className="px-3 py-1.5 rounded-md border border-bd text-t2 text-xs font-semibold" onClick={() => setShowNC(false)}>Cancel</button>
                <button className="bg-gr text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1" onClick={saveNC}><Icons.Check /> Save & Select</button>
              </div>
            </div>
          )}
        </div>

        {selClient && (<div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="flex justify-between items-center text-[11px] font-bold text-ac uppercase mb-2"><span>Allergies</span><span className="text-[10px] text-t2 font-normal normal-case">Update if needed</span></div>
          <input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oAllergies} onChange={(e) => setOAllergies(e.target.value)} />
        </div>)}

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="text-[11px] font-bold text-ac uppercase mb-2">Referral (Optional)</div>
          <SearchSelect
            value={oRef}
            onChange={(val) => setORef(val)}
            placeholder="Search referrer by name..."
            options={clients.filter((c) => !c.is_deleted && c.id !== oC).map((c) => ({
              value: c.id,
              label: c.name,
              searchText: `${c.name} ${c.phone || ''}`,
              data: c,
            }))}
            renderOption={(opt) => (
              <div className="flex items-center gap-1.5">
                {opt.data.is_vip ? <span className="text-gold"><Icons.Crown /></span> : null}
                <span>{opt.data.name}</span>
                <span className="text-[11px] text-t2">{opt.data.phone}</span>
              </div>
            )}
            renderSelected={(opt) => (
              <span className="flex items-center gap-1">
                {opt.data.is_vip ? <span className="text-gold"><Icons.Crown /></span> : null}
                <span className="text-t1">{opt.data.name}</span>
              </span>
            )}
          />
          {oRef && <div className="mt-1.5 p-1.5 px-2.5 bg-pr/10 rounded-md text-xs text-pr flex items-center gap-1"><Icons.Star /> {clients.find((c) => c.id === oRef)?.name} gets <strong>$75 referral bonus</strong></div>}
        </div>

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="text-[11px] font-bold text-ac uppercase mb-2">Products</div>
          {errors.products && <div className="text-[11px] text-rd mb-1">{errors.products}</div>}
          {oI.map((item, idx) => {
            const maxQty = getMaxQty(item.productId);
            const selectedIds = getSelectedIds(idx);
            const availableProducts = products.filter((p) => p.stock_qty > 0 && (!selectedIds.includes(p.id) || p.id === item.productId));
            return (
              <div key={idx} className="flex gap-1.5 mb-1.5 items-center">
                <SearchSelect
                  className="flex-[3]"
                  value={item.productId}
                  onChange={(val) => { const n = [...oI]; n[idx].productId = val; n[idx].qty = ''; setOI(n); }}
                  placeholder="Search product..."
                  options={availableProducts.map((p) => ({
                    value: p.id,
                    label: p.name,
                    searchText: `${p.name} ${p.description || ''} ${p.batch || ''} ${p.supplier || ''}`,
                    data: p,
                  }))}
                  renderOption={(opt) => (
                    <div>
                      <div className="font-semibold">{opt.data.name}</div>
                      <div className="text-[11px] text-t2">
                        {opt.data.mg}mg/{opt.data.ml}ml · {fmt(opt.data.retail_price)} · <span className={opt.data.stock_qty <= opt.data.low_threshold ? 'text-rd' : 'text-gr'}>stk: {opt.data.stock_qty}</span>
                      </div>
                    </div>
                  )}
                  renderSelected={(opt) => (
                    <span className="text-t1">
                      {opt.data.name} <span className="text-t2 text-[11px]">— {fmt(opt.data.retail_price)}</span>
                    </span>
                  )}
                />
                <input type="number" min="1" max={maxQty} className="w-[70px] p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] flex-shrink-0" value={item.qty} placeholder="Qty"
                  onChange={(e) => { const n = [...oI]; const raw = e.target.value; if (raw === '') { n[idx].qty = ''; } else { const val = Math.min(parseInt(raw) || 0, maxQty); n[idx].qty = val; } setOI(n); }} />
                {item.productId && <span className="text-[9px] text-t3 whitespace-nowrap flex-shrink-0">max:{maxQty}</span>}
                {oI.length > 1 && <span className="cursor-pointer text-rd self-center flex-shrink-0" onClick={() => setOI(oI.filter((_, i) => i !== idx))}><Icons.X /></span>}
              </div>
            );
          })}
          <button className="px-3 py-1 rounded-md border border-bd text-t2 text-[11px] font-semibold mt-1 hover:bg-s1" onClick={() => setOI([...oI, { productId: '', qty: '' }])}><Icons.Plus /> Add</button>
        </div>

        {selClient?.is_vip ? (<div className="bg-gold/5 rounded-md p-3 mb-3 border border-gold/30">
          <div className="flex justify-between items-center">
            <div className="text-[11px] font-bold text-gold uppercase flex items-center gap-1"><Icons.Crown /> VIP 10%</div>
            <button className={`px-2.5 py-1 rounded text-[11px] font-semibold ${vipDiscOn ? 'bg-gradient-to-br from-gold to-or text-white' : 'border border-bd text-t2'}`} onClick={() => setVipDiscOn(!vipDiscOn)}>{vipDiscOn ? 'ON ✓' : 'OFF'}</button>
          </div>
        </div>) : null}

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="text-[11px] font-bold text-ac uppercase mb-2">Additional Discount</div>
          <div className="flex gap-1.5 mb-2 flex-wrap">
            {[{ k: 'none', l: 'None' }, { k: 'percent', l: '%' }, { k: 'fixed', l: '$ Fixed' }, { k: 'custom', l: 'Custom' }].map((dd) => (
              <button key={dd.k} className={`px-2.5 py-1 rounded text-[11px] font-semibold ${oDT === dd.k ? 'bg-ac text-white' : 'border border-bd text-t2'}`} onClick={() => { setODT(dd.k); setODV(0); setOCP(''); }}>{dd.l}</button>
            ))}
          </div>
          {oDT === 'percent' && <Field label="Extra %"><input type="number" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oDV} onChange={(e) => setODV(e.target.value)} /></Field>}
          {oDT === 'fixed' && <Field label="Amount ($)"><input type="number" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oDV} onChange={(e) => setODV(e.target.value)} /></Field>}
          {oDT === 'custom' && <Field label="Custom Total ($)"><input type="number" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oCP} onChange={(e) => setOCP(e.target.value)} /></Field>}
        </div>

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="text-[11px] font-bold text-ac uppercase mb-2">Payment & Shipping</div>
          <Field label="Method"><select className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oM} onChange={(e) => setOM(e.target.value)}>{paymentMethods.map((m) => <option key={m}>{m}</option>)}</select></Field>
          <Field label="Shipping Address"><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oShipAddr} onChange={(e) => setOShipAddr(e.target.value)} /></Field>
        </div>

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="text-[11px] font-bold text-ac uppercase mb-2">Notes</div>
          <textarea className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] min-h-[36px] resize-y" value={oNote} onChange={(e) => setONote(e.target.value)} placeholder="Order notes..." />
        </div>

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="flex justify-between items-center mb-2">
            <div className="text-[11px] font-bold text-ac uppercase">Follow-up</div>
            <button className={`px-2.5 py-1 rounded text-[11px] font-semibold ${oFuE ? 'bg-ac text-white' : 'border border-bd text-t2'}`} onClick={() => setOFuE(!oFuE)}>{oFuE ? 'ON ✓' : 'Add'}</button>
          </div>
          {oFuE && (<>
            <div className="flex gap-1.5 flex-wrap mb-2">{SHORTCUTS.map((sc) => (<button key={sc.d} className={`px-2.5 py-1 rounded text-[11px] font-semibold ${oFuD === addD(NOW(), sc.d) ? 'bg-ac text-white' : 'border border-bd text-t2'}`} onClick={() => setOFuD(addD(NOW(), sc.d))}>{sc.l}</button>))}</div>
            <Field label="Date"><input type="date" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oFuD} onChange={(e) => setOFuD(e.target.value)} /></Field>
            {oFuD && <p className="text-[11px] text-ac mb-1.5">📅 {fmtD(oFuD)}</p>}
            <Field label="Note"><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={oFuN} onChange={(e) => setOFuN(e.target.value)} /></Field>
          </>)}
        </div>

        <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
          <div className="flex justify-between text-xs"><span>Subtotal</span><span>{fmt(sub)}</span></div>
          {vd > 0 && <div className="flex justify-between text-xs text-gold"><span>VIP 10%</span><span>-{fmt(vd)}</span></div>}
          {ed > 0 && <div className="flex justify-between text-xs text-yl"><span>Extra Discount</span><span>-{fmt(ed)}</span></div>}
          {totalDisc > 0 && <div className="flex justify-between text-[11px] text-t2"><span>Total Discount</span><span>-{fmt(totalDisc)} ({Math.round(totalPct)}%)</span></div>}
          {oRef && <div className="flex justify-between text-xs text-pr"><span>Referral Bonus</span><span>-$75</span></div>}
          <div className="flex justify-between text-base font-bold mt-1 pt-1 border-t border-bd"><span>Total</span><span>{fmt(total)}</span></div>
        </div>

        <div className="flex justify-end gap-2">
          <button className="px-3.5 py-1.5 rounded-md border border-bd text-t2 text-xs font-semibold hover:bg-s2" onClick={() => setModal(null)}>Cancel</button>
          <button className="bg-ac text-white px-3.5 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-ac/90" onClick={submit}><Icons.Check /> Confirm Order</button>
        </div>
      </Modal>

      {/* Success Notification */}
      {successOrder && (
        <div className="fixed inset-0 bg-black/65 flex items-center justify-center z-50" onClick={() => setSuccessOrder(null)}>
          <div className="bg-s1 border border-bd rounded-[10px] p-6 max-w-[400px] text-center" onClick={(e) => e.stopPropagation()}>
            <div className="w-14 h-14 rounded-full bg-gr/15 flex items-center justify-center mx-auto mb-4">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#22c55e" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <h3 className="text-lg font-bold mb-1">Order Created!</h3>
            <p className="text-t2 text-[13px] mb-1">Order <span className="text-ac font-bold">#{successOrder.id}</span> has been placed successfully.</p>
            <p className="text-t2 text-xs mb-4">
              Client: <span className="text-t1 font-semibold">{clients.find((c) => c.id === successOrder.client_id)?.name}</span> · Total: <span className="text-gr font-bold">{fmt(successOrder.total)}</span>
            </p>
            <div className="flex gap-2 justify-center">
              <button className="px-4 py-2 rounded-md border border-bd text-t2 text-xs font-semibold hover:bg-s2" onClick={() => setSuccessOrder(null)}>Close</button>
              <button className="bg-ac text-white px-4 py-2 rounded-md text-xs font-semibold flex items-center gap-1.5 hover:bg-ac/90" onClick={() => { setViewOrder(successOrder); setSuccessOrder(null); }}>
                <Icons.Eye /> View Detail
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
