import React, { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { FaMoneyBillWave, FaArrowLeft, FaSave, FaCheck, FaPlus, FaTrash } from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { paymentEntryService, PaymentEntry, PaymentEntryReference } from '../services/paymentEntryService';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';
import { DEFAULT_COMPANY, DEFAULT_CURRENCY } 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 }) => (
  <p className="text-sm text-gray-800 dark:text-gray-200 min-h-[20px] py-0.5">{children || <span className="text-gray-400 italic">—</span>}</p>
);

const inputCls = 'w-full border border-gray-200 dark:border-gray-600 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100';
const numCls   = inputCls + ' text-right';

const statusBadge = (pe: Partial<PaymentEntry>) => {
  const ds = pe.docstatus ?? 0;
  if (ds === 2) return <span className="px-2 py-1 rounded-full text-xs font-bold bg-red-100 text-red-700">Cancelled</span>;
  if (ds === 1) {
    const s = pe.status || 'Submitted';
    if (s === 'Paid') return <span className="px-2 py-1 rounded-full text-xs font-bold bg-green-100 text-green-700">Paid</span>;
    return <span className="px-2 py-1 rounded-full text-xs font-bold bg-blue-100 text-blue-700">{s}</span>;
  }
  return <span className="px-2 py-1 rounded-full text-xs font-bold bg-yellow-100 text-yellow-700">Draft</span>;
};

const Section: React.FC<{ title: string; children: React.ReactNode }> = ({ title, children }) => (
  <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
    <div className="px-4 py-2.5 border-b border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40">
      <h3 className="text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider">{title}</h3>
    </div>
    <div className="p-4">{children}</div>
  </div>
);

const emptyRef = (): Partial<PaymentEntryReference> => ({
  reference_doctype: 'Sales Invoice',
  reference_name: '',
  total_amount: 0,
  outstanding_amount: 0,
  allocated_amount: 0,
  exchange_rate: 1,
});

/** Default cash/bank account for Receive payments (company-specific; change if your COA differs). */
const DEFAULT_ACCOUNT_PAID_TO = 'Cash - SA';

export default function PaymentEntryDetail() {
  const { peName } = useParams<{ peName: string }>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const isNew = peName === 'new';

  const contextSI       = searchParams.get('si')       || '';
  const contextCustomer = searchParams.get('customer') || '';
  const contextCompany  = searchParams.get('company')  || DEFAULT_COMPANY;
  const contextProject  = searchParams.get('project')  || '';
  const contextAmount   = parseFloat(searchParams.get('amount') || '0');
  const contextCurrency = searchParams.get('currency') || DEFAULT_CURRENCY;

  const [doc, setDoc]           = useState<PaymentEntry | null>(null);
  const [loading, setLoading]   = useState(!isNew);
  const [saving, setSaving]     = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [isEditing, setIsEditing]   = useState(isNew);

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

  const [form, setForm] = useState<Partial<PaymentEntry>>({
    payment_type: 'Receive',
    posting_date: today,
    company: contextCompany,
    party_type: 'Customer',
    party: contextCustomer || '',
    party_name: contextCustomer || '',
    mode_of_payment: 'Cash',
    paid_to: DEFAULT_ACCOUNT_PAID_TO,
    reference_date: today,
    reference_no: '',
    paid_amount: contextAmount || 0,
    received_amount: contextAmount || 0,
    source_exchange_rate: 1,
    target_exchange_rate: 1,
    project: contextProject || '',
    references: contextSI ? [{
      reference_doctype: 'Sales Invoice',
      reference_name: contextSI,
      total_amount: contextAmount,
      outstanding_amount: contextAmount,
      allocated_amount: contextAmount,
      exchange_rate: 1,
    }] : [],
  });

  const syncForm = useCallback((d: PaymentEntry) => {
    setForm({
      payment_type: d.payment_type || 'Receive',
      posting_date: d.posting_date || today,
      company: d.company || DEFAULT_COMPANY,
      party_type: d.party_type || 'Customer',
      party: d.party || '',
      party_name: d.party_name || '',
      mode_of_payment: d.mode_of_payment || '',
      paid_from: d.paid_from || '',
      paid_to: d.paid_to || '',
      paid_from_account_currency: d.paid_from_account_currency || '',
      paid_to_account_currency: d.paid_to_account_currency || '',
      paid_amount: d.paid_amount || 0,
      received_amount: d.received_amount || 0,
      source_exchange_rate: d.source_exchange_rate || 1,
      target_exchange_rate: d.target_exchange_rate || 1,
      total_allocated_amount: d.total_allocated_amount || 0,
      unallocated_amount: d.unallocated_amount || 0,
      difference_amount: d.difference_amount || 0,
      project: d.project || '',
      cost_center: d.cost_center || '',
      remarks: d.remarks || '',
      reference_no: (d as any).reference_no || '',
      reference_date: (d as any).reference_date || '',
      references: d.references || [],
    } as any);
  }, [today]);

  // Pre-fill from SI
  useEffect(() => {
    if (!isNew || !contextSI) return;
    fetch(`/api/resource/Sales Invoice/${encodeURIComponent(contextSI)}`, { credentials: 'include' })
      .then(r => r.json()).then(b => {
        const si = b.data;
        if (!si) return;
        const outstanding = si.outstanding_amount || si.grand_total || 0;
        setForm(f => ({
          ...f,
          party: si.customer || f.party,
          party_name: si.customer_name || si.customer || f.party_name,
          company: si.company || f.company,
          project: si.project || f.project,
          paid_from: si.debit_to || '',
          paid_from_account_currency: si.currency || contextCurrency || '',
          paid_to_account_currency: si.currency || contextCurrency || '',
          paid_amount: outstanding,
          received_amount: outstanding,
          references: [{
            reference_doctype: 'Sales Invoice',
            reference_name: contextSI,
            total_amount: si.grand_total || 0,
            outstanding_amount: outstanding,
            allocated_amount: outstanding,
            exchange_rate: 1,
          }],
          remarks: `Amount ${si.currency || ''} ${outstanding} received from ${si.customer_name || si.customer}\nAmount ${si.currency || ''} ${outstanding} against Sales Invoice ${contextSI}`,
        } as any));
      }).catch(() => {});
  }, [isNew, contextSI]);

  useEffect(() => {
    if (isNew) return;
    setLoading(true);
    paymentEntryService.getPaymentEntry(peName!)
      .then(d => { setDoc(d); syncForm(d); })
      .catch(e => toast.error(e.message))
      .finally(() => setLoading(false));
  }, [peName, isNew, syncForm]);

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

  // References helpers
  const updateRef = (idx: number, k: string, v: any) => {
    setForm(f => {
      const refs = [...(f.references || [])];
      refs[idx] = { ...refs[idx], [k]: v };
      // auto-set allocated = outstanding if not changed
      if (k === 'outstanding_amount') refs[idx].allocated_amount = v;
      return { ...f, references: refs };
    });
  };

  const addRef = () => setForm(f => ({ ...f, references: [...(f.references || []), emptyRef()] }));
  const removeRef = (idx: number) => setForm(f => ({ ...f, references: (f.references || []).filter((_, i) => i !== idx) }));

  // Auto-update paid_amount from allocated refs
  const totalAllocated = (form.references || []).reduce((s, r) => s + (r.allocated_amount || 0), 0);

  // Fetch reference outstanding amount when ref name is set
  const fetchRefDetails = async (idx: number, refDoctype: string, refName: string) => {
    if (!refDoctype || !refName) return;
    try {
      const r = await fetch(`/api/resource/${encodeURIComponent(refDoctype)}/${encodeURIComponent(refName)}`, { credentials: 'include' });
      const b = await r.json();
      const d = b.data;
      if (!d) return;
      setForm(f => {
        const refs = [...(f.references || [])];
        refs[idx] = {
          ...refs[idx],
          total_amount: d.grand_total || d.outstanding_amount || 0,
          outstanding_amount: d.outstanding_amount || d.grand_total || 0,
          allocated_amount: d.outstanding_amount || d.grand_total || 0,
        };
        return { ...f, references: refs, paid_amount: d.outstanding_amount || d.grand_total || 0, received_amount: d.outstanding_amount || d.grand_total || 0 };
      });
    } catch { /* ignore */ }
  };

  const buildPayload = (): Partial<PaymentEntry> => ({
    payment_type: form.payment_type || 'Receive',
    posting_date: form.posting_date,
    company: (form as any).company || undefined,
    party_type: form.party_type || 'Customer',
    party: form.party,
    party_name: form.party_name || form.party,
    mode_of_payment: (form as any).mode_of_payment || undefined,
    paid_from: (form as any).paid_from || undefined,
    paid_to: (form as any).paid_to || undefined,
    paid_from_account_currency: (form as any).paid_from_account_currency || undefined,
    paid_to_account_currency: (form as any).paid_to_account_currency || undefined,
    paid_amount: form.paid_amount || totalAllocated,
    received_amount: form.received_amount || totalAllocated,
    source_exchange_rate: (form as any).source_exchange_rate || 1,
    target_exchange_rate: (form as any).target_exchange_rate || 1,
    project: (form as any).project || undefined,
    cost_center: (form as any).cost_center || undefined,
    remarks: (form as any).remarks || undefined,
    reference_no: (form as any).reference_no || undefined,
    reference_date: (form as any).reference_date || undefined,
    references: (form.references || []).filter(r => r.reference_name).map((r, i) => ({
      reference_doctype: r.reference_doctype || 'Sales Invoice',
      reference_name: r.reference_name,
      total_amount: r.total_amount || 0,
      outstanding_amount: r.outstanding_amount || 0,
      allocated_amount: r.allocated_amount || 0,
      exchange_rate: r.exchange_rate || 1,
      idx: i + 1,
    })),
  });

  const handleSave = async () => {
    if (!form.party) { toast.error('Party is required'); return; }
    try {
      setSaving(true);
      if (isNew) {
        const created = await paymentEntryService.createPaymentEntry(buildPayload());
        toast.success('Payment Entry created');
        setIsEditing(false);
        navigate(`/payment-entries/${created.name}`);
      } else {
        const updated = await paymentEntryService.updatePaymentEntry(peName!, buildPayload());
        setDoc(updated); syncForm(updated);
        toast.success('Payment Entry saved');
        setIsEditing(false);
      }
    } catch (e: any) { toast.error(e.message || 'Error saving'); }
    finally { setSaving(false); }
  };

  const handleSubmit = async () => {
    if (!peName || isNew) return;
    try {
      setSubmitting(true);
      const updated = await paymentEntryService.submitPaymentEntry(peName);
      setDoc(updated); syncForm(updated);
      toast.success('Payment Entry submitted');
    } catch (e: any) { toast.error(e.message || 'Error submitting'); }
    finally { setSubmitting(false); }
  };

  const editable = isEditing && (doc?.docstatus ?? 0) < 1;
  const isSubmitted = (doc?.docstatus ?? 0) === 1;

  if (loading) return (
    <div className="flex items-center justify-center h-64">
      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600" />
    </div>
  );

  return (
    <><ToastContainer position="top-right" autoClose={3000} />
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 px-6 py-6 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <button onClick={() => navigate('/payment-entries')} className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            <FaArrowLeft size={14} />
          </button>
          <div className="w-9 h-9 rounded-xl bg-teal-600 flex items-center justify-center shadow-sm">
            <FaMoneyBillWave className="text-white" size={15} />
          </div>
          <div>
            <div className="flex items-center gap-2 flex-wrap">
              <h1 className="text-lg font-bold text-gray-900 dark:text-white">
                {isNew ? 'New Payment Entry' : (doc?.party_name || doc?.party || peName)}
              </h1>
              {!isNew && statusBadge(doc || {})}
            </div>
            {!isNew && <p className="text-xs text-gray-400">{peName}</p>}
          </div>
        </div>
        <div className="flex items-center gap-2">
          {editable && (
            <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 px-4 py-2 bg-teal-600 hover:bg-teal-700 text-white text-sm font-semibold rounded-lg shadow disabled:opacity-50 transition-colors">
              <FaSave size={13} />{saving ? 'Saving…' : 'Save'}
            </button>
          )}
          {!isNew && !isEditing && !isSubmitted && (
            <button onClick={() => setIsEditing(true)} className="flex items-center gap-2 px-4 py-2 border border-teal-500 text-teal-600 hover:bg-teal-50 text-sm font-semibold rounded-lg transition-colors">
              Edit
            </button>
          )}
          {!isNew && !isSubmitted && !isEditing && (
            <button onClick={handleSubmit} disabled={submitting} className="flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded-lg shadow disabled:opacity-50 transition-colors">
              <FaCheck size={12} />{submitting ? 'Submitting…' : 'Submit'}
            </button>
          )}
        </div>
      </div>

      {/* Payment Type & Date */}
      <Section title="Payment Details">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <FL required>Payment Type</FL>
            {editable
              ? <select value={(form as any).payment_type || 'Receive'} onChange={e => set('payment_type', e.target.value)} className={inputCls}>
                  <option value="Receive">Receive</option>
                  <option value="Pay">Pay</option>
                  <option value="Internal Transfer">Internal Transfer</option>
                </select>
              : <RV>{(form as any).payment_type}</RV>}
          </div>
          <div>
            <FL required>Posting Date</FL>
            {editable
              ? <input type="date" value={(form as any).posting_date || ''} onChange={e => set('posting_date', e.target.value)} className={inputCls} />
              : <RV>{(form as any).posting_date}</RV>}
          </div>
          <div>
            <FL>Mode of Payment</FL>
            {editable
              ? <LinkField label="Mode of Payment" hideLabel doctype="Mode of Payment" value={(form as any).mode_of_payment || ''} onChange={v => set('mode_of_payment', v)} placeholder="Cash, Bank…" />
              : <RV>{(form as any).mode_of_payment}</RV>}
          </div>
          <div>
            <FL>Company</FL>
            {editable
              ? <LinkField label="Company" hideLabel doctype="Company" value={(form as any).company || ''} onChange={v => set('company', v)} placeholder="Company…" />
              : <RV>{(form as any).company}</RV>}
          </div>
        </div>
      </Section>

      {/* Party */}
      <Section title="Payment From / To">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <FL>Party Type</FL>
            {editable
              ? <select value={(form as any).party_type || 'Customer'} onChange={e => set('party_type', e.target.value)} className={inputCls}>
                  <option value="Customer">Customer</option>
                  <option value="Supplier">Supplier</option>
                  <option value="Employee">Employee</option>
                </select>
              : <RV>{(form as any).party_type}</RV>}
          </div>
          <div>
            <FL required>Party</FL>
            {editable
              ? <LinkField label="Party" hideLabel doctype={(form as any).party_type || 'Customer'} value={(form as any).party || ''} onChange={v => { set('party', v); set('party_name', v); }} placeholder="Select party…" />
              : <RV>{(form as any).party_name || (form as any).party}</RV>}
          </div>
          <div>
            <FL>Project</FL>
            {editable
              ? <LinkField label="Project" hideLabel doctype="Project" value={(form as any).project || ''} onChange={v => set('project', v)} placeholder="Project…" />
              : <RV>{(form as any).project}</RV>}
          </div>
          <div>
            <FL>Cost Center</FL>
            {editable
              ? <LinkField label="Cost Center" hideLabel doctype="Cost Center" value={(form as any).cost_center || ''} onChange={v => set('cost_center', v)} placeholder="Cost center…" />
              : <RV>{(form as any).cost_center}</RV>}
          </div>
        </div>
      </Section>

      {/* Accounts */}
      <Section title="Accounts">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <FL>Account Paid From</FL>
            {editable
              ? <LinkField label="Account Paid From" hideLabel doctype="Account" value={(form as any).paid_from || ''} onChange={v => set('paid_from', v)} placeholder="Debtors account…" />
              : <RV>{(form as any).paid_from}</RV>}
          </div>
          <div>
            <FL>Account Paid To</FL>
            {editable
              ? <LinkField label="Account Paid To" hideLabel doctype="Account" value={(form as any).paid_to || ''} onChange={v => set('paid_to', v)} placeholder="Cash / Bank account…" />
              : <RV>{(form as any).paid_to}</RV>}
          </div>
          <div>
            <FL required>Paid Amount</FL>
            {editable
              ? <input type="number" min={0} step="0.01" value={(form as any).paid_amount ?? 0} onChange={e => { const v = parseFloat(e.target.value) || 0; set('paid_amount', v); set('received_amount', v); }} className={numCls} />
              : <RV>{((form as any).paid_amount || 0).toFixed(2)}</RV>}
          </div>
          <div>
            <FL>Received Amount</FL>
            {editable
              ? <input type="number" min={0} step="0.01" value={(form as any).received_amount ?? 0} onChange={e => set('received_amount', parseFloat(e.target.value) || 0)} className={numCls} />
              : <RV>{((form as any).received_amount || 0).toFixed(2)}</RV>}
          </div>
        </div>
      </Section>

      {/* Transaction ID — ERPNext: reference_no, reference_date */}
      <Section title="Transaction ID">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <FL>Cheque / Reference No</FL>
            {editable
              ? <input type="text" value={(form as any).reference_no || ''} onChange={e => set('reference_no', e.target.value)} className={inputCls} placeholder="Reference number…" />
              : <RV>{(form as any).reference_no}</RV>}
          </div>
          <div>
            <FL>Cheque / Reference Date</FL>
            {editable
              ? <input type="date" value={(form as any).reference_date || ''} onChange={e => set('reference_date', e.target.value)} className={inputCls} />
              : <RV>{(form as any).reference_date}</RV>}
          </div>
        </div>
      </Section>

      {/* References */}
      <Section title="Payment References">
        <div className="overflow-x-auto">
          <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">Type</th>
                <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3">Reference</th>
                <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Total Amount</th>
                <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Outstanding</th>
                <th className="text-right text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-28">Allocated</th>
                {editable && <th className="w-10 py-2 px-2" />}
              </tr>
            </thead>
            <tbody>
              {(form.references || []).map((ref, idx) => (
                <tr key={idx} className="border-b border-gray-100 dark:border-gray-700 align-middle">
                  <td className="py-2 px-3 text-gray-400 text-xs">{idx + 1}</td>
                  <td className="py-2 px-3 w-40">
                    {editable
                      ? <select value={ref.reference_doctype || ''} onChange={e => updateRef(idx, 'reference_doctype', e.target.value)} className="w-full border border-gray-200 rounded px-2 py-1 text-xs bg-white dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100">
                          <option value="Sales Invoice">Sales Invoice</option>
                          <option value="Purchase Invoice">Purchase Invoice</option>
                          <option value="Sales Order">Sales Order</option>
                          <option value="Purchase Order">Purchase Order</option>
                          <option value="Journal Entry">Journal Entry</option>
                        </select>
                      : <span className="text-gray-700 dark:text-gray-300 text-xs">{ref.reference_doctype}</span>}
                  </td>
                  <td className="py-2 px-3 min-w-[180px]">
                    {editable
                      ? <LinkField label="Reference" hideLabel
                          doctype={ref.reference_doctype || 'Sales Invoice'}
                          value={ref.reference_name || ''}
                          onChange={v => { updateRef(idx, 'reference_name', v); if (v) fetchRefDetails(idx, ref.reference_doctype || 'Sales Invoice', v); }}
                          placeholder="Select document…"
                        />
                      : <span className="text-teal-600 font-medium text-xs">{ref.reference_name || '-'}</span>}
                  </td>
                  <td className="py-2 px-3 text-right text-gray-700 dark:text-gray-300 text-xs">
                    {editable
                      ? <input type="number" min={0} step="0.01" value={ref.total_amount ?? 0} onChange={e => updateRef(idx, 'total_amount', parseFloat(e.target.value) || 0)} className="w-full border border-gray-200 rounded px-2 py-1 text-xs text-right bg-white dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100" />
                      : (ref.total_amount || 0).toFixed(2)}
                  </td>
                  <td className="py-2 px-3 text-right text-gray-700 dark:text-gray-300 text-xs">
                    {(ref.outstanding_amount || 0).toFixed(2)}
                  </td>
                  <td className="py-2 px-3 text-right font-semibold text-gray-900 dark:text-white text-xs">
                    {editable
                      ? <input type="number" min={0} step="0.01" value={ref.allocated_amount ?? 0} onChange={e => updateRef(idx, 'allocated_amount', parseFloat(e.target.value) || 0)} className="w-full border border-gray-200 rounded px-2 py-1 text-xs text-right bg-white dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100" />
                      : (ref.allocated_amount || 0).toFixed(2)}
                  </td>
                  {editable && (
                    <td className="py-2 px-2">
                      <button onClick={() => removeRef(idx)} className="p-1 text-red-400 hover:text-red-600 rounded"><FaTrash size={11} /></button>
                    </td>
                  )}
                </tr>
              ))}
              {editable && (
                <tr>
                  <td colSpan={7} className="py-2 px-3">
                    <button onClick={addRef} className="flex items-center gap-1.5 text-teal-600 hover:text-teal-700 text-sm font-medium">
                      <FaPlus size={10} /> Add Row
                    </button>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="flex justify-end mt-3 pt-3 border-t border-gray-100 dark:border-gray-700 gap-6 text-sm">
          <span className="text-gray-500">Total Allocated: <strong className="text-gray-900 dark:text-white">{totalAllocated.toFixed(2)}</strong></span>
          <span className="text-gray-500">Unallocated: <strong className="text-gray-900 dark:text-white">{Math.max(0, ((form as any).paid_amount || 0) - totalAllocated).toFixed(2)}</strong></span>
        </div>
      </Section>

      {/* Remarks */}
      <Section title="Remarks">
        <div>
          {editable
            ? <textarea rows={3} value={(form as any).remarks || ''} onChange={e => set('remarks', e.target.value)} className={inputCls} placeholder="Remarks…" />
            : <RV>{(form as any).remarks}</RV>}
        </div>
      </Section>

      {/* Totals */}
      {!isNew && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
            {[
              { label: 'Paid Amount',       value: ((form as any).paid_amount || 0).toFixed(2) },
              { label: 'Total Allocated',   value: totalAllocated.toFixed(2) },
              { label: 'Unallocated',       value: Math.max(0, ((form as any).paid_amount || 0) - totalAllocated).toFixed(2) },
            ].map(({ label, value }) => (
              <div key={label} className="text-center">
                <p className="text-[10px] font-semibold text-gray-500 uppercase mb-1">{label}</p>
                <span className="font-semibold text-gray-900 dark:text-white">{value}</span>
              </div>
            ))}
          </div>
        </div>
      )}

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