import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes, FaPlus, FaTrash,
  FaSpinner, FaPaperPlane, FaChevronDown, FaChevronRight, FaPencilAlt,
  FaClipboardCheck,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import purchaseReceiptService, { PurchaseReceipt, PurchaseReceiptItem, PurchaseTaxCharge } from '../services/purchaseReceiptService';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';
import { DEFAULT_COMPANY, DEFAULT_CURRENCY, displayTxnCurrency } from '../constants/orgDefaults';

// ── Shared helpers ─────────────────────────────────────────────────────────────
const FL: React.FC<{ children: React.ReactNode; required?: boolean }> = ({ children, required }) => (
  <label className="block text-[11px] font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">
    {children}{required && <span className="text-red-500 ml-0.5">*</span>}
  </label>
);
const RV: React.FC<{ children?: React.ReactNode }> = ({ children }) => (
  <div className="px-3 py-2 text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 rounded min-h-[34px] flex items-center">
    {children || <span className="text-gray-400">-</span>}
  </div>
);
const inputCls  = 'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-green-400';
const numCls    = inputCls + ' text-right';
const inlineNum = 'w-full px-2 py-1 text-sm text-right border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-1 focus:ring-green-400';
const inlineTxt = 'w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 focus:outline-none focus:ring-1 focus:ring-green-400';
const roVal     = 'px-3 py-2 text-sm text-right bg-gray-50 dark:bg-gray-700/60 rounded text-gray-600 dark:text-gray-300';

// ── Collapsible group inside row editor ───────────────────────────────────────
const RGroup: React.FC<{ title: string; children: React.ReactNode; defaultOpen?: boolean }> = ({ title, children, defaultOpen = false }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border-t border-gray-200 dark:border-gray-600 mt-3 pt-1">
      <button type="button" onClick={() => setOpen(o => !o)}
        className="flex items-center gap-2 py-1 text-xs font-semibold text-blue-600 dark:text-blue-400 hover:underline">
        {open ? <FaChevronDown size={9} /> : <FaChevronRight size={9} />}{title}
      </button>
      {open && <div className="mt-2">{children}</div>}
    </div>
  );
};

// ── PR Item Row Editor ─────────────────────────────────────────────────────────
const PRItemRowEditor: React.FC<{
  item: Partial<PurchaseReceiptItem>; rowNo: number;
  onChange: (k: keyof PurchaseReceiptItem, v: any) => void;
  onClose: () => void; onDelete: () => void; onInsertBelow: () => void;
}> = ({ item, rowNo, onChange, onClose, onDelete, onInsertBelow }) => (
  <tr>
    <td colSpan={8} className="p-0">
      <div className="border border-blue-300 dark:border-blue-600 rounded-lg mx-2 my-1 bg-white dark:bg-gray-800 shadow-md">
        {/* Editor header */}
        <div className="flex items-center justify-between px-4 py-2 bg-blue-50 dark:bg-blue-900/30 rounded-t-lg border-b border-blue-200 dark:border-blue-700">
          <span className="text-sm font-semibold text-blue-700 dark:text-blue-300">Editing Row #{rowNo}</span>
          <div className="flex items-center gap-2">
            <button onClick={onInsertBelow} className="px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-600">Insert Below</button>
            <button onClick={onDelete} className="px-2 py-1 text-xs border border-red-300 rounded text-red-500 hover:bg-red-50">Delete</button>
            <button onClick={onClose} className="p-1 text-gray-400 hover:text-gray-600"><FaTimes size={13} /></button>
          </div>
        </div>

        <div className="p-4 space-y-4">
          {/* Item Code + Item Name */}
          <div className="grid grid-cols-2 gap-4">
            <div><FL required>Item Code</FL>
              <LinkField label="Item" hideLabel doctype="Item" value={item.item_code || ''} onChange={v => onChange('item_code', v)} placeholder="Select item…" />
            </div>
            <div><FL>Item Name</FL>
              <input value={item.item_name || ''} onChange={e => onChange('item_name', e.target.value)} className={inputCls} placeholder="Item name…" />
            </div>
          </div>

          {/* Description */}
          <RGroup title="Description" defaultOpen={!!(item.description)}>
            <textarea rows={2} value={item.description || ''} onChange={e => onChange('description', e.target.value)} className={inputCls} placeholder="Description…" />
          </RGroup>

          {/* Received and Accepted */}
          <RGroup title="Received and Accepted" defaultOpen>
            <div className="grid grid-cols-3 gap-3">
              <div><FL required>Received Qty</FL>
                <input type="number" min={0} step="1" value={item.received_qty ?? 0} onChange={e => onChange('received_qty', parseFloat(e.target.value) || 0)} className={numCls} />
              </div>
              <div><FL required>UOM</FL>
                <LinkField label="UOM" hideLabel doctype="UOM" value={item.uom || ''} onChange={v => onChange('uom', v)} placeholder="UOM…" />
              </div>
              <div><FL required>Accepted Qty</FL>
                <input type="number" min={0} step="1" value={item.qty ?? item.received_qty ?? 0} onChange={e => onChange('qty', parseFloat(e.target.value) || 0)} className={numCls} />
              </div>
              <div className="flex items-center gap-2 pt-4">
                <input type="checkbox" checked={!!(item.retain_sample)} onChange={e => onChange('retain_sample', e.target.checked ? 1 : 0)} className="rounded" />
                <span className="text-xs text-gray-600 dark:text-gray-400">Retain Sample</span>
              </div>
              {item.retain_sample ? (
                <div><FL>Sample Quantity</FL>
                  <input type="number" min={0} step="0.001" value={item.sample_quantity ?? 0} onChange={e => onChange('sample_quantity', parseFloat(e.target.value) || 0)} className={numCls} />
                </div>
              ) : null}
              <div><FL>Rejected Qty</FL>
                <input type="number" min={0} step="0.001" value={item.rejected_qty ?? 0} onChange={e => onChange('rejected_qty', parseFloat(e.target.value) || 0)} className={numCls} />
              </div>
            </div>
          </RGroup>

          {/* Rate and Amount */}
          <RGroup title="Rate and Amount" defaultOpen>
            <div className="grid grid-cols-3 gap-3">
              <div><FL>Price List Rate</FL>
                <div className={roVal}>{(item.price_list_rate ?? 0).toFixed(2)}</div>
              </div>
              <div><FL>Price List Rate (Company Currency)</FL>
                <div className={roVal}>{(item.price_list_rate ?? 0).toFixed(2)}</div>
              </div>
              <div><FL>Last Purchase Rate</FL>
                <div className={roVal}>{(item.valuation_rate ?? 0).toFixed(2)}</div>
              </div>
            </div>
          </RGroup>

          {/* Discount and Margin */}
          <RGroup title="Discount and Margin">
            <div className="grid grid-cols-3 gap-3">
              <div><FL required>Rate</FL>
                <input type="number" min={0} step="0.01" value={item.rate ?? 0} onChange={e => onChange('rate', parseFloat(e.target.value) || 0)} className={numCls} />
              </div>
              <div><FL>Rate (Company Currency)</FL>
                <div className={roVal}>{(item.rate ?? 0).toFixed(2)}</div>
              </div>
              <div><FL>Amount</FL>
                <div className="px-3 py-2 text-sm font-semibold text-right bg-gray-50 dark:bg-gray-700/60 rounded">
                  {((item.qty ?? item.received_qty ?? 0) * (item.rate || 0)).toFixed(2)}
                </div>
              </div>
              <div><FL>Amount (Company Currency)</FL>
                <div className={roVal}>{((item.qty ?? item.received_qty ?? 0) * (item.rate || 0)).toFixed(2)}</div>
              </div>
              <div className="flex items-center gap-2 pt-4">
                <input type="checkbox" checked={!!(item.is_free_item)} onChange={e => onChange('is_free_item', e.target.checked ? 1 : 0)} className="rounded" />
                <span className="text-xs text-gray-600 dark:text-gray-400">Is Free Item</span>
              </div>
              <div><FL>Net Rate</FL>
                <div className={roVal}>{(item.net_rate ?? item.rate ?? 0).toFixed(2)}</div>
              </div>
              <div><FL>Net Amount</FL>
                <div className={roVal}>{(item.net_amount ?? 0).toFixed(2)}</div>
              </div>
            </div>
          </RGroup>

          {/* Warehouse and Reference */}
          <RGroup title="Warehouse and Reference" defaultOpen>
            <div className="grid grid-cols-2 gap-3">
              <div><FL>Accepted Warehouse</FL>
                <LinkField label="Warehouse" hideLabel doctype="Warehouse" value={item.warehouse || ''} onChange={v => onChange('warehouse', v)} placeholder="Warehouse…" />
              </div>
              <div><FL>Rejected Warehouse</FL>
                <LinkField label="Warehouse" hideLabel doctype="Warehouse" value={item.rejected_warehouse || ''} onChange={v => onChange('rejected_warehouse', v)} placeholder="Rejected Warehouse…" />
              </div>
              <div className="flex items-center gap-2 pt-4">
                <input type="checkbox" checked={!!(item.allow_zero_valuation_rate)} onChange={e => onChange('allow_zero_valuation_rate', e.target.checked ? 1 : 0)} className="rounded" />
                <span className="text-xs text-gray-600 dark:text-gray-400">Allow Zero Valuation Rate</span>
              </div>
              <div className="flex items-center gap-2 pt-4">
                <input type="checkbox" checked={!!(item.from_warehouse)} onChange={e => onChange('from_warehouse', e.target.checked ? 1 : 0)} className="rounded" />
                <span className="text-xs text-gray-600 dark:text-gray-400">Return Qty from Rejected Warehouse</span>
              </div>
              {item.purchase_order && (
                <div><FL>Purchase Order</FL>
                  <div className={roVal + ' text-left'}>{item.purchase_order}</div>
                </div>
              )}
              <div><FL>Schedule Date</FL>
                <input type="date" value={item.schedule_date || ''} onChange={e => onChange('schedule_date', e.target.value)} className={inputCls} />
              </div>
            </div>
          </RGroup>

          {/* Serial and Batch No */}
          <RGroup title="Serial and Batch No">
            <div className="flex items-center gap-2">
              <input type="checkbox" checked={!!(item.use_serial_batch_fields)} onChange={e => onChange('use_serial_batch_fields', e.target.checked ? 1 : 0)} className="rounded" />
              <span className="text-xs text-gray-600 dark:text-gray-400">Use Serial / Batch Fields</span>
            </div>
          </RGroup>

          {/* Item Weight Details */}
          <RGroup title="Item Weight Details">
            <div className="grid grid-cols-2 gap-3">
              <div><FL>Weight Per Unit</FL>
                <input type="number" min={0} step="0.001" value={item.weight_per_unit ?? 0} onChange={e => onChange('weight_per_unit', parseFloat(e.target.value) || 0)} className={numCls} />
              </div>
              <div><FL>Total Weight</FL>
                <div className={roVal}>{(item.total_weight ?? 0).toFixed(3)}</div>
              </div>
            </div>
          </RGroup>

          {/* Accounting Details */}
          <RGroup title="Accounting Details">
            <div><FL>Expense Account</FL>
              <LinkField label="Expense Account" hideLabel doctype="Account" value={item.expense_account || ''} onChange={v => onChange('expense_account', v)} placeholder="Expense Account…" />
            </div>
          </RGroup>

          {/* Accounting Dimensions */}
          <RGroup title="Accounting Dimensions">
            <div className="grid grid-cols-2 gap-3">
              <div><FL>Cost Center</FL>
                <LinkField label="Cost Center" hideLabel doctype="Cost Center" value={item.cost_center || ''} onChange={v => onChange('cost_center', v)} placeholder="Cost center…" />
              </div>
              <div><FL>Project</FL>
                <LinkField label="Project" hideLabel doctype="Project" value={item.project || ''} onChange={v => onChange('project', v)} placeholder="Project…" />
              </div>
            </div>
          </RGroup>
        </div>
      </div>
    </td>
  </tr>
);

// ── PR Tax Row Editor ──────────────────────────────────────────────────────────
const PRTaxRowEditor: React.FC<{
  tax: Partial<PurchaseTaxCharge>; rowNo: number;
  onChange: (k: keyof PurchaseTaxCharge, v: any) => void;
  onClose: () => void; onDelete: () => void; onInsertBelow: () => void;
}> = ({ tax, rowNo, onChange, onClose, onDelete, onInsertBelow }) => (
  <tr>
    <td colSpan={6} className="p-0">
      <div className="border border-blue-300 dark:border-blue-600 rounded-lg mx-2 my-1 bg-white dark:bg-gray-800 shadow-md">
        <div className="flex items-center justify-between px-4 py-2 bg-blue-50 dark:bg-blue-900/30 rounded-t-lg border-b border-blue-200">
          <span className="text-sm font-semibold text-blue-700 dark:text-blue-300">Editing Row #{rowNo}</span>
          <div className="flex items-center gap-2">
            <button onClick={onInsertBelow} className="px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-50 text-gray-600">Insert Below</button>
            <button onClick={onDelete} className="px-2 py-1 text-xs border border-red-300 rounded text-red-500 hover:bg-red-50">Delete</button>
            <button onClick={onClose} className="p-1 text-gray-400 hover:text-gray-600"><FaTimes size={13} /></button>
          </div>
        </div>
        <div className="p-4 space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div><FL required>Type</FL>
              <select value={tax.charge_type || ''} onChange={e => onChange('charge_type', e.target.value)} className={inputCls}>
                <option value="">Select type…</option>
                <option value="Actual">Actual</option>
                <option value="On Net Total">On Net Total</option>
                <option value="On Previous Row Amount">On Previous Row Amount</option>
                <option value="On Previous Row Total">On Previous Row Total</option>
                <option value="On Item Quantity">On Item Quantity</option>
                <option value="Inter Company Transaction">Inter Company Transaction</option>
              </select>
            </div>
            <div><FL>Description</FL>
              <textarea rows={3} value={tax.description || ''} onChange={e => onChange('description', e.target.value)} className={inputCls} placeholder="Description…" />
            </div>
          </div>
          <div><FL required>Account Head</FL>
            <LinkField label="Account Head" hideLabel doctype="Account" value={tax.account_head || ''} onChange={v => onChange('account_head', v)} placeholder="Account…" />
          </div>
          <div className="flex items-center gap-2">
            <input type="checkbox" checked={!!(tax.included_in_print_rate)} onChange={e => onChange('included_in_print_rate', e.target.checked ? 1 : 0)} className="rounded" />
            <span className="text-xs text-gray-600 dark:text-gray-400">Is this Tax included in Basic Rate?</span>
          </div>
          <p className="text-xs text-blue-500 dark:text-blue-400">If checked, the tax amount will be considered as already included in the Print Rate / Print Amount</p>

          <RGroup title="Accounting Dimensions" defaultOpen>
            <div><FL>Cost Center</FL>
              <LinkField label="Cost Center" hideLabel doctype="Cost Center" value={tax.cost_center || ''} onChange={v => onChange('cost_center', v)} placeholder="Cost center…" />
            </div>
          </RGroup>

          <div className="grid grid-cols-2 gap-4">
            <div><FL required>Tax Rate</FL>
              <input type="number" min={0} step="0.01" value={tax.rate ?? 0} onChange={e => onChange('rate', parseFloat(e.target.value) || 0)} className={numCls} />
            </div>
            <div><FL>Account Currency</FL>
              <input value={tax.account_currency || DEFAULT_CURRENCY} onChange={e => onChange('account_currency', e.target.value)} className={inputCls} />
            </div>
          </div>
        </div>
      </div>
    </td>
  </tr>
);

// ── Page ───────────────────────────────────────────────────────────────────────
const emptyItem = (): Partial<PurchaseReceiptItem> => ({
  item_code: '', item_name: '', received_qty: 0, qty: 0, rejected_qty: 0,
  rate: 0, amount: 0, uom: '', conversion_factor: 1, is_free_item: 0, retain_sample: 0,
});
const emptyTax = (): Partial<PurchaseTaxCharge> => ({
  charge_type: '', account_head: '', rate: 0, account_currency: DEFAULT_CURRENCY, included_in_print_rate: 0,
});

const PurchaseReceiptDetail: React.FC = () => {
  const { prName } = useParams<{ prName: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const isNew = prName === 'new';

  const contextPO       = searchParams.get('po')       || '';
  const contextSupplier = searchParams.get('supplier') || '';
  const contextCompany  = searchParams.get('company')  || DEFAULT_COMPANY;
  const contextProject  = searchParams.get('project')  || '';

  const [doc, setDoc]               = useState<PurchaseReceipt | null>(null);
  const [loading, setLoading]       = useState(!isNew);
  const [saving, setSaving]         = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [isEditing, setIsEditing]   = useState(isNew);
  const [expandedItem, setExpandedItem] = useState<number | null>(null);
  const [expandedTax,  setExpandedTax]  = useState<number | null>(null);

  const today = new Date().toISOString().split('T')[0];

  const [form, setForm] = useState<Partial<PurchaseReceipt>>({
    supplier: contextSupplier, supplier_name: contextSupplier,
    company: contextCompany, project: contextProject,
    posting_date: today, currency: DEFAULT_CURRENCY,
    items: [], taxes: [],
  });

  const syncForm = useCallback((d: PurchaseReceipt) => {
    setForm({
      supplier: d.supplier || '', supplier_name: d.supplier_name || d.supplier || '',
      company: d.company || DEFAULT_COMPANY, project: d.project || '',
      posting_date: d.posting_date || today, currency: d.currency || DEFAULT_CURRENCY,
      set_warehouse: d.set_warehouse || '', cost_center: d.cost_center || '',
      tax_category: (d as any).tax_category || '',
      taxes_and_charges: (d as any).taxes_and_charges || '',
      items: d.items || [], taxes: d.taxes || [],
    });
    setExpandedItem(null); setExpandedTax(null);
  }, [today]);

  // Fetch existing doc
  useEffect(() => {
    if (isNew) return;
    setLoading(true);
    purchaseReceiptService.getPurchaseReceipt(prName!)
      .then(d => { setDoc(d); syncForm(d); })
      .catch(e => toast.error(e.message))
      .finally(() => setLoading(false));
  }, [prName, isNew, syncForm]);

  // Auto-fetch company default currency for new documents
  useEffect(() => {
    const company = form.company;
    if (!isNew || !company) return;
    fetch(`/api/resource/Company/${encodeURIComponent(company)}`, { credentials: 'include' })
      .then(r => r.json()).then(b => {
        if (b.data?.default_currency) {
          const cur = displayTxnCurrency(b.data.default_currency);
          setForm(f => ({ ...f, currency: cur,
            buying_price_list: (f as any).buying_price_list || 'Standard Buying',
            price_list_currency: (f as any).price_list_currency || cur,
          } as any));
        }
      }).catch(() => {});
  }, [form.company, isNew]);

  // Pre-fill from PO when creating new
  useEffect(() => {
    if (!isNew || !contextPO) return;
    fetch(`/api/resource/Purchase Order/${encodeURIComponent(contextPO)}`, { credentials: 'include' })
      .then(r => r.json())
      .then(body => {
        const po = body.data;
        if (!po) return;
        setForm(f => ({
          ...f,
          supplier: po.supplier || f.supplier,
          supplier_name: po.supplier_name || po.supplier || f.supplier_name,
          company: po.company || f.company,
          project: po.project || f.project,
          items: (po.items || []).map((it: any) => ({
            item_code: it.item_code,
            item_name: it.item_name,
            uom: it.uom || it.stock_uom,
            stock_uom: it.stock_uom,
            conversion_factor: it.conversion_factor ?? 1,
            received_qty: it.qty ?? 0,
            qty: it.qty ?? 0,
            rejected_qty: 0,
            rate: it.rate ?? 0,
            amount: (it.qty ?? 0) * (it.rate ?? 0),
            warehouse: it.warehouse || '',
            purchase_order: contextPO,
            purchase_order_item: it.name,
            schedule_date: it.schedule_date || '',
            project: po.project || '',
            cost_center: it.cost_center || '',
            expense_account: it.expense_account || '',
          })),
        }));
      })
      .catch(() => { /* ignore */ });
  }, [isNew, contextPO]);

  const set = (k: keyof PurchaseReceipt, v: any) => setForm(f => ({ ...f, [k]: v }));

  // ── Item helpers ─────────────────────────────────────────────────────────────
  const updateItem = (idx: number, k: keyof PurchaseReceiptItem, v: any) =>
    setForm(f => {
      const items = [...(f.items || [])];
      const updated = { ...items[idx], [k]: v };
      if (k === 'qty' || k === 'received_qty' || k === 'rate') {
        const qty  = parseFloat(String(k === 'qty' || k === 'received_qty' ? v : (updated.qty ?? updated.received_qty))) || 0;
        const rate = parseFloat(String(k === 'rate' ? v : updated.rate)) || 0;
        updated.amount = parseFloat((qty * rate).toFixed(4));
      }
      items[idx] = updated;
      return { ...f, items };
    });

  const handleItemCode = async (idx: number, code: string) => {
    updateItem(idx, 'item_code', code);
    if (!code) return;
    try {
      const r = await fetch(`/api/resource/Item/${encodeURIComponent(code)}`, { credentials: 'include' });
      const body = await r.json(); const d = body.data; if (!d) return;
      setForm(f => {
        const items = [...(f.items || [])];
        items[idx] = {
          ...items[idx],
          item_code: code,
          item_name: d.item_name || code,
          description: d.description || d.item_name || code,
          stock_uom: d.stock_uom || '',
          uom: d.purchase_uom || d.stock_uom || '',
          price_list_rate: d.standard_rate ?? 0,
          rate: items[idx].rate || d.standard_rate || 0,
        };
        return { ...f, items };
      });
    } catch { /* ignore */ }
  };

  const addItem = (afterIdx?: number) => {
    setForm(f => {
      const items = [...(f.items || [])];
      const newItem = emptyItem();
      let newIdx: number;
      if (afterIdx !== undefined) { items.splice(afterIdx + 1, 0, newItem); newIdx = afterIdx + 1; }
      else { items.push(newItem); newIdx = items.length - 1; }
      setTimeout(() => setExpandedItem(newIdx), 0);
      return { ...f, items };
    });
  };
  const removeItem = (idx: number) => {
    setForm(f => { const items = [...(f.items || [])]; items.splice(idx, 1); return { ...f, items }; });
    setExpandedItem(null);
  };

  // ── Tax helpers ──────────────────────────────────────────────────────────────
  const updateTax = (idx: number, k: keyof PurchaseTaxCharge, v: any) =>
    setForm(f => { const taxes = [...(f.taxes || [])]; taxes[idx] = { ...taxes[idx], [k]: v }; return { ...f, taxes }; });

  const addTax = (afterIdx?: number) => {
    setForm(f => {
      const taxes = [...(f.taxes || [])];
      const newTax = emptyTax();
      let newIdx: number;
      if (afterIdx !== undefined) { taxes.splice(afterIdx + 1, 0, newTax); newIdx = afterIdx + 1; }
      else { taxes.push(newTax); newIdx = taxes.length - 1; }
      setTimeout(() => setExpandedTax(newIdx), 0);
      return { ...f, taxes };
    });
  };
  const removeTax = (idx: number) => {
    setForm(f => { const taxes = [...(f.taxes || [])]; taxes.splice(idx, 1); return { ...f, taxes }; });
    setExpandedTax(null);
  };

  // ── Computed ─────────────────────────────────────────────────────────────────
  const netTotal   = (form.items || []).reduce((s, it) => s + ((it.qty ?? it.received_qty ?? 0) * (it.rate || 0)), 0);
  const taxTotal   = (form.taxes || []).reduce((s, tx) => {
    if (tx.charge_type === 'On Net Total') return s + ((tx.rate || 0) / 100) * netTotal;
    if (tx.charge_type === 'Actual') return s + (tx.tax_amount || 0);
    return s + ((tx.rate || 0) / 100) * netTotal;
  }, 0);
  const grandTotal = netTotal + taxTotal;

  // ── Payload ──────────────────────────────────────────────────────────────────
  const loadTaxTemplate = async (templateName: string) => {
    if (!templateName) return;
    try {
      const r = await fetch(`/api/resource/Purchase Taxes and Charges Template/${encodeURIComponent(templateName)}`, { credentials: 'include' });
      const body = await r.json();
      const tmpl = body.data;
      if (tmpl?.taxes?.length) {
        setForm(f => ({ ...f, taxes: tmpl.taxes.map((tx: any) => ({
          charge_type: tx.charge_type, account_head: tx.account_head,
          description: tx.description, rate: tx.rate,
          cost_center: tx.cost_center, account_currency: tx.account_currency,
          included_in_print_rate: tx.included_in_print_rate ?? 0,
        })) }));
      }
    } catch { /* ignore */ }
  };

  const buildPayload = (): Partial<PurchaseReceipt> => ({
    supplier: form.supplier,
    company: form.company || undefined,
    project: form.project || undefined,
    posting_date: form.posting_date,
    currency: form.currency || undefined,
    set_warehouse: form.set_warehouse || undefined,
    cost_center: form.cost_center || undefined,
    tax_category: (form as any).tax_category || undefined,
    taxes_and_charges: (form as any).taxes_and_charges || undefined,
    items: (form.items || []).filter(it => it.item_code).map((it, i) => ({
      item_code: it.item_code,
      item_name: it.item_name || it.item_code,
      description: it.description || it.item_name || it.item_code,
      received_qty: it.received_qty ?? 0,
      qty: it.qty ?? it.received_qty ?? 0,
      rejected_qty: it.rejected_qty ?? 0,
      uom: it.uom || undefined,
      stock_uom: it.stock_uom || undefined,
      conversion_factor: it.conversion_factor ?? 1,
      rate: it.rate ?? 0,
      amount: (it.qty ?? it.received_qty ?? 0) * (it.rate ?? 0),
      price_list_rate: it.price_list_rate ?? 0,
      warehouse: it.warehouse || undefined,
      rejected_warehouse: it.rejected_warehouse || undefined,
      expense_account: it.expense_account || undefined,
      cost_center: it.cost_center || undefined,
      project: it.project || form.project || undefined,
      purchase_order: it.purchase_order || undefined,
      purchase_order_item: it.purchase_order_item || undefined,
      schedule_date: it.schedule_date || undefined,
      is_free_item: it.is_free_item ?? 0,
      retain_sample: it.retain_sample ?? 0,
      sample_quantity: it.sample_quantity || undefined,
      weight_per_unit: it.weight_per_unit || undefined,
      idx: i + 1,
    })),
    taxes: (form.taxes || []).filter(tx => tx.charge_type).map((tx, i) => ({
      charge_type: tx.charge_type,
      account_head: tx.account_head || undefined,
      description: tx.description || undefined,
      included_in_print_rate: tx.included_in_print_rate ?? 0,
      cost_center: tx.cost_center || undefined,
      rate: tx.rate ?? 0,
      account_currency: tx.account_currency || DEFAULT_CURRENCY,
      idx: i + 1,
    })),
  });

  const handleSave = async () => {
    if (!form.supplier) { toast.error('Supplier is required'); return; }
    try {
      setSaving(true);
      if (isNew) {
        const created = await purchaseReceiptService.createPurchaseReceipt(buildPayload());
        toast.success('Purchase Receipt created');
        setIsEditing(false);
        navigate(`/purchase-receipts/${created.name}`);
      } else {
        const updated = await purchaseReceiptService.updatePurchaseReceipt(prName!, buildPayload());
        setDoc(updated); syncForm(updated);
        toast.success('Purchase Receipt saved');
        setIsEditing(false);
      }
    } catch (e: any) { toast.error(e.message || 'Error saving'); }
    finally { setSaving(false); }
  };

  const handleSubmit = async () => {
    if (!prName || isNew) return;
    try {
      setSubmitting(true);
      const updated = await purchaseReceiptService.submitPurchaseReceipt(prName);
      setDoc(updated); syncForm(updated);
      toast.success('Purchase Receipt submitted');
    } catch (e: any) { toast.error(e.message || 'Error submitting'); }
    finally { setSubmitting(false); }
  };

  const editable    = isNew || isEditing;
  const isSubmitted = !isNew && doc?.docstatus === 1;
  const title       = isNew ? 'New Purchase Receipt' : (form.supplier_name || prName || '');

  if (loading) return (
    <div className="flex items-center justify-center min-h-[400px]">
      <FaSpinner className="animate-spin text-green-500 text-3xl" />
    </div>
  );

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 px-6 py-6">
      <ToastContainer position="top-right" autoClose={3500} />

      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm mb-6 text-gray-500">
        <button onClick={() => navigate('/purchase-receipts')} className="hover:text-green-600">Purchase Receipts</button>
        <span>/</span>
        <span className="text-gray-700 dark:text-gray-300">{isNew ? 'New Purchase Receipt' : prName}</span>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden">

        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between gap-4 flex-wrap">
          <div className="flex items-center gap-3">
            <button onClick={() => navigate('/purchase-receipts')} className="text-gray-400 hover:text-gray-700"><FaArrowLeft /></button>
            <FaClipboardCheck className="text-green-500" />
            <div>
              <div className="flex items-center gap-2 flex-wrap">
                <h1 className="text-xl font-bold text-gray-900 dark:text-white">{title}</h1>
                {!isNew && prName && (
                  <span className="text-xs text-gray-400 font-mono">{prName}</span>
                )}
                {!isNew && (
                  <span className={`px-2 py-0.5 rounded text-xs font-semibold ${(() => { const s = doc?.status || ''; if (doc?.docstatus === 2 || s === 'Cancelled') return 'bg-red-100 text-red-700'; if (!doc || doc.docstatus === 0) return 'bg-yellow-100 text-yellow-800'; if (s === 'Completed') return 'bg-green-100 text-green-800'; if (s === 'Return Issued') return 'bg-orange-100 text-orange-800'; if (s === 'Closed') return 'bg-gray-100 text-gray-700'; return 'bg-green-100 text-green-800'; })()}`}>
                    {doc?.docstatus === 2 ? 'Cancelled' : doc?.docstatus === 0 ? 'Draft' : (doc?.status || 'Submitted')}
                  </span>
                )}
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            {!isNew && !isEditing && doc?.docstatus === 0 && (
              <button onClick={handleSubmit} disabled={submitting} className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 text-sm font-medium">
                {submitting ? <FaSpinner className="animate-spin" /> : <FaPaperPlane size={12} />} Submit
              </button>
            )}
            {!isNew && !isEditing && !isSubmitted && (
              <button onClick={() => setIsEditing(true)} className="flex items-center gap-2 px-4 py-2 border border-green-500 text-green-600 rounded-lg hover:bg-green-50 text-sm">
                <FaEdit /> Edit
              </button>
            )}
            {editable && (
              <>
                <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:opacity-50 text-sm font-medium">
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}{saving ? 'Saving…' : 'Save'}
                </button>
                {!isNew && <button onClick={() => { if (doc) syncForm(doc); setIsEditing(false); }} className="px-3 py-2 border border-gray-300 rounded-lg text-gray-600 text-sm"><FaTimes /></button>}
              </>
            )}
          </div>
        </div>

        {/* Main fields */}
        <div className="px-6 pt-5 pb-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div><FL required>Supplier</FL>
              {editable
                ? <LinkField label="Supplier" hideLabel doctype="Supplier" value={form.supplier || ''} onChange={v => { set('supplier', v); set('supplier_name', v); }} placeholder="Select supplier…" />
                : <RV>{form.supplier_name || form.supplier}</RV>}
            </div>
            <div><FL required>Posting Date</FL>
              {editable
                ? <input type="date" value={form.posting_date || ''} onChange={e => set('posting_date', e.target.value)} className={inputCls} />
                : <RV>{form.posting_date}</RV>}
            </div>
            <div><FL>Company</FL>
              {editable
                ? <LinkField label="Company" hideLabel doctype="Company" value={form.company || ''} onChange={v => set('company', v)} placeholder="Select company…" />
                : <RV>{form.company}</RV>}
            </div>
            <div><FL>Project</FL>
              {editable
                ? <LinkField label="Project" hideLabel doctype="Project" value={form.project || ''} onChange={v => set('project', v)} placeholder="Select project…" />
                : <RV>{form.project}</RV>}
            </div>
            <div><FL>Set Warehouse</FL>
              {editable
                ? <LinkField label="Warehouse" hideLabel doctype="Warehouse" value={form.set_warehouse || ''} onChange={v => set('set_warehouse', v)} placeholder="Warehouse…" />
                : <RV>{form.set_warehouse}</RV>}
            </div>
            <div><FL>Currency</FL>
              {editable
                ? <select value={form.currency || DEFAULT_CURRENCY} onChange={e => set('currency', e.target.value)} className={inputCls}>
                    <option value="SAR">SAR</option>
                    <option value="USD">USD</option>
                    <option value="EUR">EUR</option>
                  </select>
                : <RV>{form.currency}</RV>}
            </div>
          </div>
        </div>

        {/* ── Items ── */}
        <div className="border-t border-gray-100 dark:border-gray-700">
          <div className="px-6 py-3 bg-gray-50 dark:bg-gray-900/20 border-b border-gray-100 dark:border-gray-700">
            <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Items</span>
          </div>
          <div className="px-6 pb-5">
            <div className="overflow-x-auto -mx-2 mt-3">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40">
                    <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-8">No.</th>
                    <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 min-w-[180px]">Item Code <span className="text-red-400">*</span></th>
                    <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 min-w-[140px]">Item Name</th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-24">Received Qty</th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-24">Accepted Qty</th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Rate</th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Amount</th>
                    {editable && <th className="w-16 py-2 px-2" />}
                  </tr>
                </thead>
                <tbody>
                  {(form.items || []).map((it, idx) => (
                    <React.Fragment key={idx}>
                      <tr className={`border-b border-gray-100 dark:border-gray-700 align-middle ${expandedItem === idx ? 'bg-blue-50/60 dark:bg-blue-900/10' : ''}`}>
                        <td className="py-1.5 px-3 text-gray-400 text-xs">{idx + 1}</td>
                        <td className="py-1.5 px-2 min-w-[180px]">
                          {editable
                            ? <LinkField label="Item" hideLabel doctype="Item" value={it.item_code || ''} onChange={v => handleItemCode(idx, v)} placeholder="Item Code" />
                            : <span className="font-medium text-gray-800 dark:text-gray-200">{it.item_code || '-'}</span>}
                        </td>
                        <td className="py-1.5 px-2 min-w-[140px]">
                          <span className="text-gray-500 text-sm">{it.item_name || '-'}</span>
                        </td>
                        <td className="py-1.5 px-2 w-24">
                          {editable
                            ? <input type="number" min={0} step="1" value={it.received_qty ?? 0} onChange={e => updateItem(idx, 'received_qty', parseFloat(e.target.value) || 0)} className={inlineNum} />
                            : <span className="block text-right text-gray-700 dark:text-gray-300 text-sm pr-1">{(it.received_qty ?? 0).toFixed(3)}</span>}
                        </td>
                        <td className="py-1.5 px-2 w-24">
                          {editable
                            ? <input type="number" min={0} step="1" value={it.qty ?? it.received_qty ?? 0} onChange={e => updateItem(idx, 'qty', parseFloat(e.target.value) || 0)} className={inlineNum} />
                            : <span className="block text-right text-gray-700 dark:text-gray-300 text-sm pr-1">{(it.qty ?? 0).toFixed(3)}</span>}
                        </td>
                        <td className="py-1.5 px-2 w-28">
                          {editable
                            ? <input type="number" min={0} step="0.01" value={it.rate ?? 0} onChange={e => updateItem(idx, 'rate', parseFloat(e.target.value) || 0)} className={inlineNum} />
                            : <span className="block text-right text-gray-700 dark:text-gray-300 text-sm pr-1">{(it.rate ?? 0).toFixed(2)}</span>}
                        </td>
                        <td className="py-1.5 px-3 text-right font-semibold text-gray-900 dark:text-white text-sm">
                          {((it.qty ?? it.received_qty ?? 0) * (it.rate || 0)).toFixed(2)}
                        </td>
                        {editable && (
                          <td className="py-1.5 px-2">
                            <div className="flex items-center gap-1">
                              <button onClick={() => setExpandedItem(expandedItem === idx ? null : idx)}
                                className={`p-1.5 rounded text-xs ${expandedItem === idx ? 'bg-blue-600 text-white' : 'text-green-600 hover:bg-green-50'}`} title="More fields">
                                <FaPencilAlt size={11} />
                              </button>
                              <button onClick={() => removeItem(idx)} className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded"><FaTrash size={11} /></button>
                            </div>
                          </td>
                        )}
                      </tr>
                      {editable && expandedItem === idx && (
                        <PRItemRowEditor item={it} rowNo={idx + 1}
                          onChange={(k, v) => { if (k === 'item_code') handleItemCode(idx, v as string); else updateItem(idx, k, v); }}
                          onClose={() => setExpandedItem(null)} onDelete={() => removeItem(idx)} onInsertBelow={() => addItem(idx)} />
                      )}
                    </React.Fragment>
                  ))}
                  {editable && (
                    <tr><td colSpan={8} className="py-2 px-3">
                      <button onClick={() => addItem()} className="flex items-center gap-1.5 text-green-600 hover:text-green-700 text-sm font-medium"><FaPlus size={10} /> Add Row</button>
                    </td></tr>
                  )}
                </tbody>
              </table>
            </div>
            <div className="mt-3 flex justify-between text-sm border-t border-gray-100 dark:border-gray-700 pt-3">
              <span className="text-gray-500">Total Qty: <strong>{(form.items || []).reduce((s, it) => s + (it.qty ?? it.received_qty ?? 0), 0).toFixed(3)}</strong></span>
              <span className="text-gray-500">Total: <strong className="text-gray-900 dark:text-white">{form.currency || DEFAULT_CURRENCY} {netTotal.toFixed(2)}</strong></span>
            </div>
          </div>
        </div>

        {/* ── Taxes ── */}
        <div className="border-t border-gray-100 dark:border-gray-700">
          <div className="px-6 py-3 bg-gray-50 dark:bg-gray-900/20 border-b border-gray-100 dark:border-gray-700">
            <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Taxes and Charges</span>
          </div>
          <div className="px-6 pt-4 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-3">
            <div><FL>Tax Category</FL>
              {editable ? <LinkField label="Tax Category" hideLabel doctype="Tax Category" value={(form as any).tax_category || ''} onChange={v => set('tax_category' as any, v)} placeholder="Select tax category…" /> : <RV>{(form as any).tax_category}</RV>}
            </div>
            <div><FL>Purchase Taxes and Charges Template</FL>
              {editable
                ? <LinkField label="Purchase Taxes and Charges Template" hideLabel doctype="Purchase Taxes and Charges Template" value={(form as any).taxes_and_charges || ''} onChange={v => { set('taxes_and_charges' as any, v); loadTaxTemplate(v); }} placeholder="Select template…" />
                : <RV>{(form as any).taxes_and_charges}</RV>}
            </div>
          </div>
          <div className="px-6 pb-5">
            <div className="overflow-x-auto -mx-2 mt-3">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40">
                    <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-8">No.</th>
                    <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-44">Type <span className="text-red-400">*</span></th>
                    <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3">Account Head <span className="text-red-400">*</span></th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-24">Tax Rate</th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Amount</th>
                    <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Total</th>
                    {editable && <th className="w-16 py-2 px-2" />}
                  </tr>
                </thead>
                <tbody>
                  {(form.taxes || []).map((tx, idx) => {
                    const calcAmt = tx.charge_type === 'On Net Total' ? ((tx.rate || 0) / 100) * netTotal : (tx.charge_type === 'Actual' ? (tx.tax_amount || 0) : ((tx.rate || 0) / 100) * netTotal);
                    const calcRunning = netTotal + (form.taxes || []).slice(0, idx + 1).reduce((s: number, t: any) => {
                      const a = t.charge_type === 'On Net Total' ? ((t.rate || 0) / 100) * netTotal : (t.charge_type === 'Actual' ? (t.tax_amount || 0) : ((t.rate || 0) / 100) * netTotal);
                      return s + a;
                    }, 0);
                    return (
                    <React.Fragment key={idx}>
                      <tr className={`border-b border-gray-100 dark:border-gray-700 align-middle ${expandedTax === idx ? 'bg-blue-50/60 dark:bg-blue-900/10' : ''}`}>
                        <td className="py-1.5 px-3 text-gray-400 text-xs">{idx + 1}</td>
                        <td className="py-1.5 px-2 w-44">
                          {editable
                            ? <select value={tx.charge_type || ''} onChange={e => updateTax(idx, 'charge_type', e.target.value)} className={inlineTxt}>
                                <option value="">Select type…</option>
                                <option value="Actual">Actual</option>
                                <option value="On Net Total">On Net Total</option>
                                <option value="On Previous Row Amount">On Previous Row Amount</option>
                                <option value="On Previous Row Total">On Previous Row Total</option>
                                <option value="On Item Quantity">On Item Quantity</option>
                                <option value="Inter Company Transaction">Inter Company Transaction</option>
                              </select>
                            : <span className="text-gray-700 dark:text-gray-300">{tx.charge_type || '-'}</span>}
                        </td>
                        <td className="py-1.5 px-2">
                          {editable
                            ? <LinkField label="Account Head" hideLabel doctype="Account" value={tx.account_head || ''} onChange={v => updateTax(idx, 'account_head', v)} placeholder="Account Head" />
                            : <span className="text-gray-700 dark:text-gray-300">{tx.account_head || '-'}</span>}
                        </td>
                        <td className="py-1.5 px-2 w-24">
                          {editable
                            ? <input type="number" min={0} step="0.01" value={tx.rate ?? 0} onChange={e => updateTax(idx, 'rate', parseFloat(e.target.value) || 0)} className={inlineNum} />
                            : <span className="block text-right text-gray-700 dark:text-gray-300 pr-1">{tx.rate ?? 0}</span>}
                        </td>
                        <td className="py-1.5 px-3 text-right text-gray-700 dark:text-gray-300 text-sm">{calcAmt.toFixed(2)}</td>
                        <td className="py-1.5 px-3 text-right font-semibold text-gray-900 dark:text-white text-sm">{calcRunning.toFixed(2)}</td>
                        {editable && (
                          <td className="py-1.5 px-2">
                            <div className="flex items-center gap-1">
                              <button onClick={() => setExpandedTax(expandedTax === idx ? null : idx)}
                                className={`p-1.5 rounded text-xs ${expandedTax === idx ? 'bg-blue-600 text-white' : 'text-green-600 hover:bg-green-50'}`} title="More fields">
                                <FaPencilAlt size={11} />
                              </button>
                              <button onClick={() => removeTax(idx)} className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded"><FaTrash size={11} /></button>
                            </div>
                          </td>
                        )}
                      </tr>
                      {editable && expandedTax === idx && (
                        <PRTaxRowEditor tax={tx} rowNo={idx + 1} onChange={(k, v) => updateTax(idx, k, v)}
                          onClose={() => setExpandedTax(null)} onDelete={() => removeTax(idx)} onInsertBelow={() => addTax(idx)} />
                      )}
                    </React.Fragment>
                  );})}
                  {editable && (
                    <tr><td colSpan={7} className="py-2 px-3">
                      <button onClick={() => addTax()} className="flex items-center gap-1.5 text-green-600 hover:text-green-700 text-sm font-medium"><FaPlus size={10} /> Add Row</button>
                    </td></tr>
                  )}
                </tbody>
              </table>
            </div>
            {(form.taxes || []).length > 0 && (
              <div className="mt-2 flex justify-end text-sm text-gray-500 pt-2 border-t border-gray-100 dark:border-gray-700">
                Total Taxes and Charges: <strong className="ml-2 text-gray-900 dark:text-white">{form.currency || DEFAULT_CURRENCY} {taxTotal.toFixed(2)}</strong>
              </div>
            )}
          </div>
        </div>

        {/* ── Totals ── */}
        <div className="border-t border-gray-100 dark:border-gray-700 px-6 py-4">
          <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">Totals</h3>
          <div className="space-y-2 max-w-xs ml-auto">
            {[
              { label: 'Net Total',         value: (doc?.net_total ?? netTotal).toFixed(2) },
              { label: 'Total Taxes',       value: (doc?.total_taxes_and_charges ?? taxTotal).toFixed(2) },
              { label: 'Grand Total',       value: (doc?.grand_total ?? grandTotal).toFixed(2) },
              { label: 'Rounded Total',     value: (doc?.rounded_total ?? grandTotal).toFixed(2) },
            ].map(({ label, value }) => (
              <div key={label} className="flex justify-between text-sm border-b border-gray-100 dark:border-gray-700 pb-1.5 last:border-0">
                <span className="text-gray-500">{label}</span>
                <span className="font-semibold text-gray-900 dark:text-white">{form.currency || DEFAULT_CURRENCY} {value}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Meta */}
        {!isNew && doc && (
          <div className="border-t border-gray-100 dark:border-gray-700 px-6 py-4 grid grid-cols-3 gap-4 text-sm bg-gray-50 dark:bg-gray-900/20">
            <div><FL>Created By</FL><RV>{doc.owner}</RV></div>
            <div><FL>Created</FL><RV>{doc.creation ? new Date(doc.creation).toLocaleString() : '-'}</RV></div>
            <div><FL>Modified</FL><RV>{doc.modified ? new Date(doc.modified).toLocaleString() : '-'}</RV></div>
          </div>
        )}

        {!isNew && (
          <ActivityLog
            doctype="Purchase Receipt"
            docname={doc?.name || prName || ''}
            creationDate={doc?.creation}
            createdBy={doc?.owner}
            compact={false}
            initialVisible={5}
            collapsible
            startCollapsed
          />
        )}
      </div>
    </div>
  );
};

export default PurchaseReceiptDetail;
