import { useState, useEffect } from 'react';
import api from '../utils/api';
import { fmt, fmtD, stockColor, NOW, toLocal } from '../utils/helpers';
import { Icons } from '../components/icons/Icons';
import { StockBadge, Badge } from '../components/ui/Badge';
import { useAuth } from '../context/AuthContext';
import Modal from '../components/ui/Modal';
import Confirm from '../components/ui/Confirm';
import Field from '../components/ui/Field';
import OrderDetailModal from '../components/ui/OrderDetailModal';

export default function Inventory({ products, orders, clients, refetch, nav }) {
  const { hasRole } = useAuth();
  const [search, setSearch] = useState('');
  const [modal, setModal] = useState(null);
  const [form, setForm] = useState({});
  const [delCfm, setDelCfm] = useState(null);
  const [formErrors, setFormErrors] = useState({});
  const [saveCfm, setSaveCfm] = useState(false);
  const [detailProd, setDetailProd] = useState(null);
  const [detailFilter, setDetailFilter] = useState('all');
  const [detailSearch, setDetailSearch] = useState('');
  const [viewOrder, setViewOrder] = useState(null);
  const [viewLossReport, setViewLossReport] = useState(null);
  const [stockHistory, setStockHistory] = useState([]);
  const [filterRoute, setFilterRoute] = useState('all');
  const [restockInfo, setRestockInfo] = useState({});

  // Stock reduction report (cashier)
  const [reportModal, setReportModal] = useState(null);
  const [reportForm, setReportForm] = useState({ reduction_type: '', qty: 1, description: '' });
  const [reportPhotos, setReportPhotos] = useState({ photo_1: null, photo_2: null });
  const [reportPreviews, setReportPreviews] = useState({ photo_1: null, photo_2: null });
  const [reportErrors, setReportErrors] = useState({});
  const [reportConfirm, setReportConfirm] = useState(false);
  const [reportSubmitting, setReportSubmitting] = useState(false);

  const [lossData, setLossData] = useState({});

  const fetchRestock = async () => {
    try { const res = await api.get('/stock/latest-restock'); setRestockInfo(res.data); } catch {}
  };
  const fetchLossData = async () => {
    try {
      const res = await api.get('/stock-reports');
      const perProduct = {};
      res.data.forEach((r) => {
        if (!perProduct[r.product_id]) perProduct[r.product_id] = { total: 0, pending: 0, reports: [] };
        perProduct[r.product_id].total += r.qty;
        if (r.status === 'pending') perProduct[r.product_id].pending += r.qty;
        perProduct[r.product_id].reports.push(r);
      });
      setLossData(perProduct);
    } catch {}
  };
  useEffect(() => { fetchRestock(); fetchLossData(); }, [products]);

  const today = NOW();
  const confirmedToday = (orders || []).filter((o) => o.status === 'confirmed' && toLocal(o.order_date) === today);

  // Calc today's sold qty per product
  const todaySold = {};
  confirmedToday.forEach((o) => (o.items || []).forEach((i) => {
    todaySold[i.product_id] = (todaySold[i.product_id] || 0) + i.qty;
  }));

  // Calc all-time sold qty per product
  const allSold = {};
  (orders || []).filter((o) => o.status === 'confirmed').forEach((o) => (o.items || []).forEach((i) => {
    allSold[i.product_id] = (allSold[i.product_id] || 0) + i.qty;
  }));

  const totalProducts = products.length;
  const totalStock = products.reduce((s, p) => s + p.stock_qty, 0);
  const totalSoldToday = Object.values(todaySold).reduce((s, v) => s + v, 0);
  const totalOrdersToday = confirmedToday.length;
  const totalLoss = Object.values(lossData).reduce((s, v) => s + v.total, 0);

  const list = products
    .filter((p) => p.name.toLowerCase().includes(search.toLowerCase()))
    .filter((p) => filterRoute === 'all' || p.route === filterRoute);

  const validateProduct = () => {
    const e = {};
    if (!form.name?.trim()) e.name = 'Product name is required';
    if (!form.description?.trim()) e.description = 'Description is required';
    if (!form.mg || parseFloat(form.mg) <= 0) e.mg = 'Must be > 0';
    if (!form.ml || parseFloat(form.ml) <= 0) e.ml = 'Must be > 0';
    if (!form.cost_price || parseFloat(form.cost_price) <= 0) e.cost_price = 'Must be > 0';
    if (!form.retail_price || parseFloat(form.retail_price) <= 0) e.retail_price = 'Must be > 0';
    if (form.stock_qty === '' || form.stock_qty === undefined || parseInt(form.stock_qty) < 0) e.stock_qty = 'Must be ≥ 0';
    if (!form.batch?.trim()) e.batch = 'Batch/Lot is required';
    if (!form.expiry) e.expiry = 'Expiry date is required';
    if (!form.supplier?.trim()) e.supplier = 'Supplier is required';
    if (!form.low_threshold || parseInt(form.low_threshold) < 0) e.low_threshold = 'Must be ≥ 0';
    if (parseInt(form.low_threshold) > parseInt(form.stock_qty)) e.low_threshold = `Cannot exceed stock qty (${form.stock_qty})`;
    // added_date is auto-set, no validation needed
    if (parseFloat(form.retail_price) <= parseFloat(form.cost_price)) e.retail_price = 'Must be higher than cost price';
    setFormErrors(e);
    return Object.keys(e).length === 0;
  };

  const save = async () => {
    if (!validateProduct()) return;
    try {
      const payload = {
        name: form.name, description: form.description || '',
        mg: parseFloat(form.mg) || 0, ml: parseFloat(form.ml) || 0, route: form.route || 'SQ',
        cost_price: parseFloat(form.cost_price) || 0, retail_price: parseFloat(form.retail_price) || 0,
        stock_qty: parseInt(form.stock_qty) || 0, batch: form.batch || '',
        expiry: form.expiry || null, supplier: form.supplier || '', low_threshold: parseInt(form.low_threshold) || 5,
      };
      if (modal === 'add') {
        payload.added_date = NOW();
        await api.post('/products', payload);
      } else {
        // Only update added_date if stock qty changed (restock)
        const oldQty = form._original_stock_qty;
        const newQty = parseInt(form.stock_qty) || 0;
        payload.added_date = (newQty !== oldQty) ? NOW() : (form.added_date || null);
        await api.put(`/products/${form.id}`, payload);
      }
      setModal(null);
      refetch();
      fetchRestock();
    } catch (err) {
      alert(err.response?.data?.error || 'Error saving product');
    }
  };

  const handleDelete = async () => {
    try { await api.delete(`/products/${delCfm.id}`); setDelCfm(null); refetch(); } catch {}
  };

  const openDetail = async (p) => {
    setDetailProd(p);
    setDetailFilter('all');
    setDetailSearch('');
    try {
      const res = await api.get(`/stock/${p.id}`);
      setStockHistory(res.data);
    } catch { setStockHistory([]); }
  };

  // Get orders that contain this product
  const getProductOrders = (productId) => {
    return (orders || []).filter((o) => o.status === 'confirmed' && (o.items || []).some((i) => i.product_id === productId))
      .sort((a, b) => (b.order_date || '').localeCompare(a.order_date || ''));
  };

  // Get loss records (cancelled/refunded orders with this product)

  // Auto-generate batch code from name, mg, route, supplier
  // Generate batch: Product-mg/ml-Route-Supplier
  const generateBatch = (f) => {
    const name = (f.name || '').trim();
    const mg = f.mg;
    const ml = f.ml;
    const route = (f.route || '').trim();
    const supplier = (f.supplier || '').trim();
    if (!name || !mg || !ml || !route || !supplier) return '';
    return `${name}-${mg}/${ml}-${route}-${supplier}`;
  };

  // Update form and auto-generate batch if conditions met
  const updateForm = (updates) => {
    const newForm = { ...form, ...updates };
    if (!newForm._batchManual && modal === 'add') {
      const autoBatch = generateBatch(newForm);
      if (autoBatch) newForm.batch = autoBatch;
    }
    setForm(newForm);
  };

  const openAdd = () => {
    const today = NOW();
    setForm({ name: '', description: '', mg: '', ml: '', route: 'SQ', cost_price: '', retail_price: '', stock_qty: '', batch: '', expiry: '', supplier: '', low_threshold: 5, added_date: today });
    setFormErrors({});
    setModal('add');
  };

  const openEdit = (p) => {
    const editForm = { ...p, expiry: toLocal(p.expiry), added_date: toLocal(p.added_date), _original_stock_qty: p.stock_qty };
    setForm({ ...editForm, _original: { ...editForm } });
    setFormErrors({});
    setModal(p);
  };

  const hasChanges = () => {
    if (modal === 'add') return true;
    if (!form._original) return true;
    const o = form._original;
    const fields = ['name', 'description', 'mg', 'ml', 'route', 'cost_price', 'retail_price', 'stock_qty', 'batch', 'expiry', 'supplier', 'low_threshold'];
    return fields.some((f) => String(form[f] ?? '') !== String(o[f] ?? ''));
  };

  // === Stock Reduction Report functions (cashier) ===
  const REDUCTION_TYPES = [
    { value: 'lost', label: 'Lost' },
    { value: 'accidentally_damaged', label: 'Accidentally Damaged' },
    { value: 'burned', label: 'Burned' },
    { value: 'broken', label: 'Broken' },
    { value: 'expired', label: 'Expired' },
    { value: 'contaminated', label: 'Contaminated' },
    { value: 'spillage', label: 'Spillage' },
    { value: 'recalled', label: 'Recalled' },
    { value: 'other', label: 'Other' },
  ];

  const openReportModal = (p) => {
    setReportModal(p);
    setReportForm({ reduction_type: '', qty: 1, description: '' });
    setReportPhotos({ photo_1: null, photo_2: null });
    setReportPreviews({ photo_1: null, photo_2: null });
    setReportErrors({});
    setReportConfirm(false);
  };

  const handleReportPhoto = (field, file) => {
    if (!file) return;
    setReportPhotos(prev => ({ ...prev, [field]: file }));
    const reader = new FileReader();
    reader.onload = (e) => setReportPreviews(prev => ({ ...prev, [field]: e.target.result }));
    reader.readAsDataURL(file);
  };

  const validateReport = () => {
    const e = {};
    if (!reportForm.reduction_type) e.reduction_type = 'Select a type';
    if (!reportForm.qty || parseInt(reportForm.qty) < 1) e.qty = 'Must be at least 1';
    if (!reportForm.description?.trim()) e.description = 'Description is required';
    setReportErrors(e);
    return Object.keys(e).length === 0;
  };

  const submitReport = async () => {
    if (!reportModal) return;
    setReportSubmitting(true);
    try {
      const fd = new FormData();
      fd.append('product_id', reportModal.id);
      fd.append('reduction_type', reportForm.reduction_type);
      fd.append('qty', reportForm.qty);
      fd.append('description', reportForm.description);
      if (reportPhotos.photo_1) fd.append('photo_1', reportPhotos.photo_1);
      if (reportPhotos.photo_2) fd.append('photo_2', reportPhotos.photo_2);
      await api.post('/stock-reports', fd, { headers: { 'Content-Type': 'multipart/form-data' } });
      setReportModal(null);
      setReportConfirm(false);
      refetch();
      fetchLossData();
    } catch (err) {
      alert(err.response?.data?.error || 'Error submitting report');
    } finally {
      setReportSubmitting(false);
    }
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-1">
        <div>
          <h1 className="text-xl font-bold mb-0.5">Inventory</h1>
          <p className="text-t2 text-xs mb-5">{products.length} products</p>
        </div>
        {hasRole('master_admin', 'supplier') && (
          <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={openAdd}>
            <Icons.Plus /> Add Product
          </button>
        )}
      </div>

      {/* Summary Cards */}
      <div className="flex gap-2.5 flex-wrap mb-4">
        {[
          { l: 'Total Products', v: totalProducts, c: 'border-l-ac' },
          { l: 'Total Stock', v: totalStock, c: 'border-l-gr' },
          { l: 'Sold Today', v: totalSoldToday, c: totalSoldToday > 0 ? 'border-l-or' : 'border-l-t3' },
          { l: 'Orders Today', v: totalOrdersToday, c: totalOrdersToday > 0 ? 'border-l-ac' : 'border-l-t3' },
          { l: 'Total Loss', v: totalLoss, c: totalLoss > 0 ? 'border-l-rd' : 'border-l-t3' },
        ].map((s, i) => (
          <div key={i} className={`bg-s1 border border-bd rounded-[10px] py-3 px-4 flex-1 min-w-[120px] border-l-[3px] ${s.c}`}>
            <div className="text-[10px] text-t2 mb-0.5">{s.l}</div>
            <div className="text-lg font-bold">{s.v}</div>
          </div>
        ))}
      </div>

      <div className="flex gap-2 mb-3 flex-wrap items-center">
        <div className="flex items-center gap-2 bg-s2 border border-bd rounded-md px-2.5 py-1 flex-1 max-w-[280px]">
          <Icons.Search />
          <input className="bg-transparent border-none text-t1 text-[13px] w-full outline-none" placeholder="Search products..." value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        <select className="bg-s2 border border-bd rounded-md text-t1 text-[11px] px-2.5 py-1.5 outline-none" value={filterRoute} onChange={(e) => setFilterRoute(e.target.value)}>
          <option value="all">All Routes</option>
          <option value="SQ">SQ Only</option>
          <option value="IM">IM Only</option>
        </select>
      </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>
                {['Product', 'Added', 'Dose', 'Route', 'Cost', 'Retail', 'Stock', 'Last Restock', 'Today', 'Total Sold', 'Loss', 'Batch', 'Supplier', ''].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>
              {list.map((p) => {
                const sc = stockColor(p.stock_qty, p.low_threshold);
                const rowBg = sc === 'rd' ? 'bg-rd/5' : sc === 'yl' ? 'bg-yl/5' : '';
                return (
                  <tr key={p.id} className={`${rowBg} cursor-pointer hover:bg-s2/50`} onClick={() => openDetail(p)}>
                    <td className="p-2 border-b border-bd font-semibold text-[13px]">{p.name}</td>
                    <td className="p-2 border-b border-bd text-[11px] text-t2 whitespace-nowrap">{fmtD(p.added_date)}</td>
                    <td className="p-2 border-b border-bd text-[13px]">{p.mg}mg/{p.ml}ml</td>
                    <td className="p-2 border-b border-bd text-[13px]">
                      <span className="bg-ac/15 text-ac px-2 py-0.5 rounded-full text-[10px] font-bold">{p.route}</span>
                    </td>
                    <td className="p-2 border-b border-bd text-[13px]">{fmt(p.cost_price)}</td>
                    <td className="p-2 border-b border-bd text-[13px] font-semibold">{fmt(p.retail_price)}</td>
                    <td className="p-2 border-b border-bd text-[13px]"><StockBadge q={p.stock_qty} t={p.low_threshold} /></td>
                    <td className="p-2 border-b border-bd text-[11px]">
                      {restockInfo[p.id] ? (
                        <div>
                          <div className={`font-semibold ${restockInfo[p.id].type === 'in' ? 'text-gr' : 'text-rd'}`}>
                            {restockInfo[p.id].type === 'in' ? '+' : '-'}{restockInfo[p.id].qty}
                          </div>
                          <div className="text-t3 text-[9px]">{new Date(restockInfo[p.id].last_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
                        </div>
                      ) : <span className="text-t3">—</span>}
                    </td>
                    <td className="p-2 border-b border-bd text-[13px] text-center">
                      {todaySold[p.id] ? <span className="text-or font-bold">{todaySold[p.id]}</span> : <span className="text-t3">0</span>}
                    </td>
                    <td className="p-2 border-b border-bd text-[13px] text-center">
                      {allSold[p.id] ? <span className="text-ac font-semibold">{allSold[p.id]}</span> : <span className="text-t3">0</span>}
                    </td>
                    <td className="p-2 border-b border-bd text-[13px] text-center">
                      {lossData[p.id] ? (
                        <span className="text-rd font-bold" title={`${lossData[p.id].pending} pending`}>
                          {lossData[p.id].total}
                          {lossData[p.id].pending > 0 && <span className="text-[9px] text-yl ml-0.5">({lossData[p.id].pending}⏳)</span>}
                        </span>
                      ) : <span className="text-t3">0</span>}
                    </td>
                    <td className="p-2 border-b border-bd text-[11px] text-t2">{p.batch}</td>
                    <td className="p-2 border-b border-bd text-[11px] text-t2">{p.supplier || '—'}</td>
                    <td className="p-2 border-b border-bd" onClick={(e) => e.stopPropagation()}>
                      <div className="flex gap-1.5 items-center" style={{ position: 'relative', zIndex: 10 }}>
                        {hasRole('master_admin', 'cashier') && (
                          <button type="button" className="text-gr hover:text-gr/80 p-1 rounded hover:bg-gr/10" title="New Order" onClick={(e) => { e.stopPropagation(); e.preventDefault(); nav('orders', null, p.id); }}><Icons.Cart /></button>
                        )}
                        {hasRole('master_admin', 'supplier') && (
                          <button type="button" className="text-t2 hover:text-ac p-1 rounded hover:bg-ac/10" title="Edit" onClick={(e) => { e.stopPropagation(); e.preventDefault(); openEdit(p); }}><Icons.Edit /></button>
                        )}
                        {hasRole('master_admin', 'supplier') && (
                          <button type="button" className="text-rd hover:text-rd/80 p-1 rounded hover:bg-rd/10" title="Delete" onClick={(e) => { e.stopPropagation(); e.preventDefault(); setDelCfm(p); }}><Icons.Trash /></button>
                        )}
                        {hasRole('master_admin', 'cashier') && (
                          <button type="button" className="text-or hover:text-or/80 p-1 rounded hover:bg-or/10" title="Report Loss" onClick={(e) => { e.stopPropagation(); e.preventDefault(); openReportModal(p); }}><Icons.Alert /></button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <Confirm open={!!delCfm} onClose={() => setDelCfm(null)} icon="🗑️" title="Delete Product?" desc={`Are you sure you want to delete "${delCfm?.name}"?`} cStyle="d" cLabel="Yes, Delete"
        details={[{ i: '⚠️', t: 'Product will be removed from inventory' }, { i: '🔄', t: 'Can be restored from Settings → Restore Data' }]}
        onConfirm={handleDelete}
      />

      <Confirm open={saveCfm} onClose={() => setSaveCfm(false)} icon="💾" title={modal === 'add' ? 'Add Product?' : 'Save Changes?'}
        desc={modal === 'add' ? `Add "${form.name}" to inventory?` : `Save changes to "${form.name}"?`}
        cStyle="p" cLabel="Yes, Save"
        details={modal !== 'add' && parseInt(form.stock_qty) !== form._original_stock_qty
          ? [{ i: '📦', t: `Stock: ${form._original_stock_qty} → ${form.stock_qty}` }, { i: '📅', t: 'Added date will update to today' }]
          : [{ i: '✅', t: 'Product data will be saved' }]}
        onConfirm={() => { setSaveCfm(false); save(); }}
      />

      <Modal open={!!modal} onClose={() => { setModal(null); setFormErrors({}); }} title={modal === 'add' ? 'Add Product' : 'Edit Product'}>
        <Field label="Product Name" required error={formErrors.name}>
          {modal === 'add' ? (
            <input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.name || ''} onChange={(e) => updateForm({ name: e.target.value })} />
          ) : (
            <div className="w-full p-1.5 px-2.5 bg-s2/50 border border-bd rounded-md text-t1 text-[13px] opacity-70 cursor-not-allowed">{form.name}</div>
          )}
        </Field>
        <Field label="Description" required error={formErrors.description}>
          <input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.description || ''} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Brief product description" />
        </Field>
        <div className="flex gap-2.5 mb-2.5">
          <Field label="Dosage (mg)" required error={formErrors.mg}><input type="number" min="0" step="0.01" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.mg || ''} onChange={(e) => updateForm({ mg: e.target.value })} /></Field>
          <Field label="Volume (ml)" required error={formErrors.ml}><input type="number" min="0" step="0.01" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.ml || ''} onChange={(e) => updateForm({ ml: e.target.value })} /></Field>
          <Field label="Route" required>
            <select className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.route || 'SQ'} onChange={(e) => updateForm({ route: e.target.value })}>
              <option>SQ</option><option>IM</option>
            </select>
          </Field>
        </div>
        <div className="flex gap-2.5 mb-2.5">
          <Field label="Cost Price ($)" required error={formErrors.cost_price}><input type="number" min="0" step="0.01" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.cost_price || ''} onChange={(e) => setForm({ ...form, cost_price: e.target.value })} /></Field>
          <Field label="Retail Price ($)" required error={formErrors.retail_price}><input type="number" min="0" step="0.01" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.retail_price || ''} onChange={(e) => setForm({ ...form, retail_price: e.target.value })} /></Field>
          <Field label="Stock Qty" required error={formErrors.stock_qty}><input type="number" min="0" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.stock_qty ?? ''} onChange={(e) => setForm({ ...form, stock_qty: e.target.value })} /></Field>
        </div>
        <div className="flex gap-2.5 mb-2.5">
          <Field label="Batch / Lot" required error={formErrors.batch}>
            <div className="flex gap-1 items-center">
              <input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.batch || ''}
                onChange={(e) => setForm({ ...form, batch: e.target.value, _batchManual: true })}
                placeholder={modal === 'add' ? 'Auto-generated or type manually' : 'Batch code'} />
              {form.batch && (
                <button type="button" className="text-rd hover:text-rd/80 p-1 flex-shrink-0" title="Clear batch" onClick={() => setForm({ ...form, batch: '', _batchManual: false })}>
                  <Icons.X />
                </button>
              )}
            </div>
            {modal === 'add' && !form.batch && (
              <div className="text-[9px] text-t3 mt-0.5">Fill name, dosage, route & supplier to auto-generate</div>
            )}
          </Field>
          <Field label="Expiry Date" required error={formErrors.expiry}><input type="date" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.expiry || ''} onChange={(e) => setForm({ ...form, expiry: e.target.value })} /></Field>
        </div>
        <div className="flex gap-2.5 mb-2.5">
          <Field label="Supplier" required error={formErrors.supplier}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.supplier || ''} onChange={(e) => updateForm({ supplier: e.target.value })} /></Field>
          <Field label="Low Stock Threshold" required error={formErrors.low_threshold}><input type="number" min="0" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.low_threshold ?? ''} onChange={(e) => setForm({ ...form, low_threshold: e.target.value })} /></Field>
        </div>
        {modal === 'add' ? (
          <div className="text-[11px] text-t2 mb-3 p-2 bg-s2 rounded-md flex items-center gap-1.5">
            📅 Date added will be set automatically to <span className="text-ac font-semibold">{NOW()}</span>
          </div>
        ) : (
          <div className="text-[11px] text-t2 mb-3 p-2 bg-s2 rounded-md flex items-center gap-1.5">
            📅 Added: <span className="text-t1 font-semibold">{fmtD(form.added_date)}</span>
            {parseInt(form.stock_qty) !== form._original_stock_qty && (
              <span className="text-gr ml-2">→ Will update to {NOW()} (stock changed)</span>
            )}
          </div>
        )}
        <div className="text-[11px] text-t2 mb-3 p-2 bg-s2 rounded-md">
          🔴 Red: ≤ {form.low_threshold || 5} &nbsp; 🟡 Yellow: ≤ {Math.round((+(form.low_threshold || 5)) * 1.2 + (+(form.low_threshold || 5)))} &nbsp; 🟢 Green: above
        </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={`px-3.5 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 ${hasChanges() ? 'bg-ac text-white hover:bg-ac/90 cursor-pointer' : 'bg-t3/30 text-t3 cursor-not-allowed'}`} disabled={!hasChanges()} onClick={() => { if (hasChanges() && validateProduct()) setSaveCfm(true); }}><Icons.Check /> Save</button>
        </div>
      </Modal>

      {/* Product Overview Modal */}
      <Modal open={!!detailProd} onClose={() => setDetailProd(null)} title="Product Detail" w={600}>
        {detailProd && (() => {
          const p = detailProd;
          const prodOrders = getProductOrders(p.id);
          // prodLosses from cancelled/refunded orders (kept for reference)
          const totalQtySold = prodOrders.reduce((s, o) => s + (o.items || []).filter((i) => i.product_id === p.id).reduce((x, i) => x + i.qty, 0), 0);
          // Revenue = sum of order totals (after discount) for orders containing this product
          const totalRevenue = prodOrders.reduce((s, o) => {
            const orderSubtotal = parseFloat(o.subtotal) || 0;
            const orderTotal = parseFloat(o.total) || 0;
            const itemLineTotal = (o.items || []).filter((i) => i.product_id === p.id).reduce((x, i) => x + parseFloat(i.line_total), 0);
            // Proportional: if this product's line_total is 50% of subtotal, revenue = 50% of discounted total
            const proportion = orderSubtotal > 0 ? itemLineTotal / orderSubtotal : 0;
            return s + (orderTotal * proportion);
          }, 0);

          return (
            <>
              {/* Product Info Header */}
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h2 className="text-lg font-bold">{p.name}</h2>
                  <p className="text-t2 text-xs">{p.description || '—'}</p>
                </div>
                <StockBadge q={p.stock_qty} t={p.low_threshold} />
              </div>

              {/* Product Details Grid */}
              <div className="grid grid-cols-3 gap-2 mb-4">
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Dose</div>
                  <div className="text-sm font-bold">{p.mg}mg/{p.ml}ml</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Route</div>
                  <div className="text-sm font-bold">{p.route}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Batch</div>
                  <div className="text-sm font-bold">{p.batch || '—'}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Cost</div>
                  <div className="text-sm font-bold">{fmt(p.cost_price)}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Retail</div>
                  <div className="text-sm font-bold text-gr">{fmt(p.retail_price)}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Margin</div>
                  <div className="text-sm font-bold text-ac">{fmt(p.retail_price - p.cost_price)}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Supplier</div>
                  <div className="text-sm font-bold">{p.supplier || '—'}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Expiry</div>
                  <div className="text-sm font-bold">{fmtD(p.expiry)}</div>
                </div>
                <div className="bg-s2 rounded-md p-2.5 border border-bd text-center">
                  <div className="text-[10px] text-t2">Added</div>
                  <div className="text-sm font-bold">{fmtD(p.added_date)}</div>
                </div>
              </div>

              {/* Summary Stats */}
              {(() => {
                const prodReports = lossData[p.id]?.reports || [];
                const totalLossQty = lossData[p.id]?.total || 0;
                return (
                  <>
                    <div className="flex gap-2.5 mb-4">
                      <div className="bg-s2 rounded-md p-3 border border-bd flex-1 text-center border-l-[3px] border-l-gr">
                        <div className="text-[10px] text-t2">Total Sold</div>
                        <div className="text-lg font-bold text-gr">{totalQtySold}</div>
                      </div>
                      <div className="bg-s2 rounded-md p-3 border border-bd flex-1 text-center border-l-[3px] border-l-ac">
                        <div className="text-[10px] text-t2">Revenue</div>
                        <div className="text-lg font-bold text-ac">{fmt(totalRevenue)}</div>
                      </div>
                      <div className="bg-s2 rounded-md p-3 border border-bd flex-1 text-center border-l-[3px] border-l-rd">
                        <div className="text-[10px] text-t2">Loss</div>
                        <div className="text-lg font-bold text-rd">{totalLossQty} <span className="text-[10px] font-normal text-t2">({prodReports.length} reports)</span></div>
                      </div>
                    </div>

                    {/* Filter Tabs + Search */}
                    <div className="flex gap-1.5 mb-2 flex-wrap">
                      {[
                        { k: 'all', l: `All (${stockHistory.length})` },
                        { k: 'order', l: `Orders (${prodOrders.length})` },
                        { k: 'loss', l: `Loss (${prodReports.length})` },
                      ].map((f) => (
                        <button key={f.k} className={`px-3 py-1 rounded-md text-[11px] font-semibold border ${detailFilter === f.k ? 'bg-ac text-white border-ac' : 'border-bd text-t2 hover:bg-s2'}`}
                          onClick={() => setDetailFilter(f.k)}>{f.l}</button>
                      ))}
                    </div>
                    <div className="flex items-center gap-1.5 bg-s2 border border-bd rounded-md px-2 py-1 mb-3">
                      <Icons.Search />
                      <input className="bg-transparent border-none text-t1 text-[11px] w-full outline-none"
                        placeholder={detailFilter === 'all' ? 'Search reason, type...' : detailFilter === 'order' ? 'Search client, order ID...' : 'Search type, description...'}
                        value={detailSearch} onChange={(e) => setDetailSearch(e.target.value)} />
                    </div>

                    {/* Filter Content */}
                    <div className="max-h-[250px] overflow-auto">
                      {detailFilter === 'all' && (() => {
                        let items = stockHistory;
                        if (detailSearch.trim()) {
                          const q = detailSearch.toLowerCase();
                          items = items.filter((s) => (s.reason || '').toLowerCase().includes(q) || s.type.includes(q));
                        }
                        return items.length === 0 ? <p className="text-t2 text-xs text-center py-3">No stock history</p> :
                        items.map((s, i) => (
                          <div key={i} className="flex justify-between items-center py-1.5 border-b border-bd text-xs">
                            <div className="flex items-center gap-2">
                              <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${s.type === 'in' ? 'bg-gr/15 text-gr' : s.type === 'out' ? 'bg-or/15 text-or' : 'bg-rd/15 text-rd'}`}>
                                {s.type === 'in' ? 'IN' : s.type === 'out' ? 'OUT' : 'ADJ'}
                              </span>
                              <span className="font-semibold">{s.type === 'in' ? '+' : '-'}{s.qty}</span>
                            </div>
                            <div className="text-right">
                              <div className="text-t2">{s.reason}</div>
                              <div className="text-t3 text-[9px]">{new Date(s.created_at).toLocaleString()}</div>
                            </div>
                          </div>
                        ));
                      })()}

                      {detailFilter === 'order' && (() => {
                        let items = prodOrders;
                        if (detailSearch.trim()) {
                          const q = detailSearch.toLowerCase();
                          items = items.filter((o) => {
                            const cl = (clients || []).find((c) => c.id === o.client_id);
                            return (cl?.name || '').toLowerCase().includes(q) || o.id.toLowerCase().includes(q) || fmtD(o.order_date).toLowerCase().includes(q);
                          });
                        }
                        return items.length === 0 ? <p className="text-t2 text-xs text-center py-3">No orders found</p> :
                        items.map((o) => {
                          const item = (o.items || []).find((i) => i.product_id === p.id);
                          const cl = (clients || []).find((c) => c.id === o.client_id);
                          const hasDisc = parseFloat(o.discount_amt) > 0;
                          return (
                            <div key={o.id} className="flex justify-between items-center py-2 border-b border-bd text-xs cursor-pointer hover:bg-s2/50 rounded px-1" onClick={() => setViewOrder(o)}>
                              <div>
                                <div className="font-semibold">#{o.id} · {cl?.name || '?'}</div>
                                <div className="text-t2">
                                  Qty: <span className="text-or font-bold">{item?.qty}</span>
                                  {' · '}Total: <span className="text-gr font-bold">{fmt(o.total)}</span>
                                  {hasDisc && <span className="text-yl ml-1">(-{fmt(o.discount_amt)})</span>}
                                </div>
                                <div className="text-t3 text-[9px] mt-0.5">
                                  {o.payment_method} · <Badge s={o.delivery_status} />
                                </div>
                              </div>
                              <div className="text-right flex items-center gap-2">
                                <div>
                                  <Badge s={o.status} />
                                  <div className="text-t3 text-[9px] mt-0.5">{fmtD(o.order_date)}</div>
                                </div>
                                <Icons.Eye />
                              </div>
                            </div>
                          );
                        });
                      })()}

                      {detailFilter === 'loss' && (() => {
                        let items = prodReports;
                        if (detailSearch.trim()) {
                          const q = detailSearch.toLowerCase();
                          items = items.filter((r) => (r.reduction_type || '').toLowerCase().includes(q) || (r.description || '').toLowerCase().includes(q) || (r.reporter_name || '').toLowerCase().includes(q) || (r.status || '').toLowerCase().includes(q));
                        }
                        return items.length === 0 ? <p className="text-t2 text-xs text-center py-3">No loss reports found</p> :
                        items.map((r) => (
                          <div key={r.id} className="flex justify-between items-center py-2 border-b border-bd text-xs cursor-pointer hover:bg-s2/50 rounded px-1" onClick={() => setViewLossReport(r)}>
                            <div>
                              <div className="font-semibold flex items-center gap-1.5">
                                <span className={`px-1.5 py-0.5 rounded-full text-[9px] font-bold ${r.status === 'pending' ? 'bg-yl/15 text-yl' : r.status === 'processed' ? 'bg-ac/15 text-ac' : 'bg-gr/15 text-gr'}`}>{r.status}</span>
                                {r.reduction_type?.replace(/_/g, ' ')}
                              </div>
                              <div className="text-t2 mt-0.5">Qty: <span className="text-rd font-bold">{r.qty}</span> — {r.description?.slice(0, 40)}{r.description?.length > 40 ? '...' : ''}</div>
                            </div>
                            <div className="text-right flex items-center gap-2">
                              <div className="text-t3 text-[9px]">{new Date(r.created_at).toLocaleString()}</div>
                              <Icons.Eye />
                            </div>
                          </div>
                        ));
                      })()}
                    </div>
                  </>
                );
              })()}
            </>
          );
        })()}
      </Modal>

      {/* Stock Reduction Report Modal (cashier) */}
      <Modal open={!!reportModal && !reportConfirm} onClose={() => setReportModal(null)} title="Report Stock Reduction" w={500}>
        {reportModal && (
          <>
            <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
              <div className="text-[11px] font-bold text-ac uppercase mb-1">Product</div>
              <div className="text-sm font-bold">{reportModal.name}</div>
              <div className="text-xs text-t2">{reportModal.mg}mg/{reportModal.ml}ml &middot; Batch: {reportModal.batch} &middot; Route: {reportModal.route}</div>
              <div className="text-xs text-t2">Current stock: <span className="font-semibold text-t1">{reportModal.stock_qty}</span></div>
            </div>
            <Field label="Reduction Type" required error={reportErrors.reduction_type}>
              <input
                list="reduction-types-dl"
                type="text"
                className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]"
                value={reportForm.reduction_type}
                onChange={(e) => setReportForm({ ...reportForm, reduction_type: e.target.value })}
                placeholder="Pilih atau ketik custom (mis. 'water damage')"
              />
              <datalist id="reduction-types-dl">
                {REDUCTION_TYPES.map((t) => <option key={t.value} value={t.label} />)}
              </datalist>
              <div className="text-[10px] text-t3 mt-1">Bisa pilih dari suggestion atau ketik custom sendiri</div>
            </Field>
            <Field label="Quantity" required error={reportErrors.qty}>
              <input type="number" min="1" max={reportModal.stock_qty} className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={reportForm.qty} onChange={(e) => setReportForm({ ...reportForm, qty: e.target.value })} />
            </Field>
            <Field label="Description" required error={reportErrors.description}>
              <textarea className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] min-h-[80px] resize-y" value={reportForm.description} onChange={(e) => setReportForm({ ...reportForm, description: e.target.value })} placeholder="Describe what happened..." />
            </Field>
            <div className="flex gap-3 mb-3">
              <Field label="Photo 1 (optional)" error={reportErrors.photo_1}>
                <label className="block cursor-pointer">
                  {reportPreviews.photo_1 ? (
                    <img src={reportPreviews.photo_1} alt="Preview 1" className="w-full h-[100px] object-cover rounded-md border border-bd mb-1" />
                  ) : (
                    <div className="w-full h-[100px] bg-s2 border border-bd border-dashed rounded-md flex items-center justify-center text-t3 text-xs mb-1">
                      <Icons.Camera /> <span className="ml-1">Click to upload</span>
                    </div>
                  )}
                  <input type="file" accept="image/*" className="hidden" onChange={(e) => handleReportPhoto('photo_1', e.target.files[0])} />
                </label>
              </Field>
              <Field label="Photo 2 (optional)" error={reportErrors.photo_2}>
                <label className="block cursor-pointer">
                  {reportPreviews.photo_2 ? (
                    <img src={reportPreviews.photo_2} alt="Preview 2" className="w-full h-[100px] object-cover rounded-md border border-bd mb-1" />
                  ) : (
                    <div className="w-full h-[100px] bg-s2 border border-bd border-dashed rounded-md flex items-center justify-center text-t3 text-xs mb-1">
                      <Icons.Camera /> <span className="ml-1">Click to upload</span>
                    </div>
                  )}
                  <input type="file" accept="image/*" className="hidden" onChange={(e) => handleReportPhoto('photo_2', e.target.files[0])} />
                </label>
              </Field>
            </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={() => setReportModal(null)}>Cancel</button>
              <button className="bg-or text-white px-3.5 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-or/90" onClick={() => { if (validateReport()) setReportConfirm(true); }}>
                <Icons.Alert /> Submit Report
              </button>
            </div>
          </>
        )}
      </Modal>

      {/* Report Confirm */}
      <Confirm open={reportConfirm} onClose={() => setReportConfirm(false)} title="Submit Report?"
        desc={`Report ${reportForm.qty} unit(s) of "${reportModal?.name}" as ${reportForm.reduction_type}?`}
        cStyle="w" cLabel={reportSubmitting ? 'Submitting...' : 'Yes, Submit'}
        details={[
          { t: `Product: ${reportModal?.name}` },
          { t: `Type: ${reportForm.reduction_type}` },
          { t: `Qty: ${reportForm.qty}` },
          { t: 'Report will be sent to supplier for review' },
        ]}
        onConfirm={submitReport}
      />

      {/* Order Detail Popup */}
      <OrderDetailModal open={!!viewOrder} order={viewOrder} products={products} clients={clients || []} onClose={() => setViewOrder(null)} />

      {/* Loss Report Detail Popup */}
      {viewLossReport && (() => {
        const r = viewLossReport;
        const statusCls = r.status === 'pending' ? 'bg-yl/15 text-yl' : r.status === 'processed' ? 'bg-ac/15 text-ac' : 'bg-gr/15 text-gr';
        return (
          <Modal open={true} onClose={() => setViewLossReport(null)} title="Loss Report Detail" w={500}>
            <div className="flex items-center gap-2 mb-3">
              <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${statusCls}`}>{r.status}</span>
              <span className="text-t3 text-[10px]">{new Date(r.created_at).toLocaleString()}</span>
            </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">Product</div>
              <div className="text-sm font-bold">{r.product_name || '?'}</div>
              <div className="text-xs text-t2">{r.mg}mg/{r.ml}ml · Batch: {r.batch} · {r.route}</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">Reduction Info</div>
              <div className="grid grid-cols-2 gap-2 text-xs">
                <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Type</span><span className="font-semibold capitalize">{r.reduction_type?.replace(/_/g, ' ')}</span></div>
                <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Quantity</span><span className="text-rd font-bold text-base">{r.qty}</span></div>
              </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">Description</div>
              <div className="text-[13px] leading-relaxed">{r.description}</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">Evidence Photos</div>
              <div className="flex gap-2">
                {r.photo_1 && <img src={r.photo_1} alt="Evidence 1" className="w-32 h-32 rounded-md object-cover border border-bd cursor-pointer" onClick={() => window.open(r.photo_1, '_blank')} />}
                {r.photo_2 && <img src={r.photo_2} alt="Evidence 2" className="w-32 h-32 rounded-md object-cover border border-bd cursor-pointer" onClick={() => window.open(r.photo_2, '_blank')} />}
              </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">Reporter</div>
              <div className="text-[13px] font-semibold">{r.reporter_name || r.reporter_username || '?'}</div>
            </div>
            {r.processor_name && (
              <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
                <div className="text-[11px] font-bold text-ac uppercase mb-2">Processed By</div>
                <div className="text-[13px] font-semibold">{r.processor_name}</div>
                {r.processed_at && <div className="text-xs text-t2">{new Date(r.processed_at).toLocaleString()}</div>}
                {r.notes && <div className="text-xs text-t2 mt-1">Notes: {r.notes}</div>}
              </div>
            )}
          </Modal>
        );
      })()}
    </div>
  );
}
