import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes, FaPlus, FaTrash,
  FaSpinner, FaBoxes, FaPaperPlane, FaChevronDown, FaChevronRight, FaPencilAlt, FaShoppingBag,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import materialRequestService, { MaterialRequest, MaterialRequestItem } from '../services/materialRequestService';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';
import WorkflowActions from '../components/WorkflowActions';
import workflowService from '../services/workflowService';
import { DEFAULT_COMPANY } from '../constants/orgDefaults';

// ── Helpers ───────────────────────────────────────────────────────────────────
const FL: React.FC<{ children: React.ReactNode; required?: boolean }> = ({ children, required }) => (
  <label className="block text-xs 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-lg min-h-[38px] 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-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-orange-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-orange-400';
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-orange-400';
const editorInput = 'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-orange-400';
const editorNum = 'w-full px-3 py-2 text-sm text-right border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-orange-400';

// ── Collapsible section (matches Project/Task/Timesheet style) ─────────────────
const CollapsibleSection: React.FC<{
  title: string; icon?: React.ReactNode; defaultOpen?: boolean; children: React.ReactNode;
}> = ({ title, icon, defaultOpen = true, children }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
      <button type="button" onClick={() => setOpen(o => !o)}
        className="w-full flex items-center justify-between px-5 py-3.5 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors text-left">
        <div className="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-200">
          {icon}<span>{title}</span>
        </div>
        {open ? <FaChevronDown className="text-gray-400 text-xs flex-shrink-0" /> : <FaChevronRight className="text-gray-400 text-xs flex-shrink-0" />}
      </button>
      {open && (
        <div className="px-5 py-5 bg-white dark:bg-gray-800 border-t border-gray-100 dark:border-gray-700/50">
          {children}
        </div>
      )}
    </div>
  );
};

// ── Collapsible group (inside editor) ─────────────────────────────────────────
const RGroup: React.FC<{ label: string; children: React.ReactNode; defaultOpen?: boolean }> = ({ label, children, defaultOpen = false }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden mt-3">
      <button type="button" onClick={() => setOpen(o => !o)}
        className="w-full flex items-center gap-2 px-3 py-2 text-[11px] font-bold text-gray-500 uppercase tracking-wider bg-gray-50 dark:bg-gray-800/80 hover:bg-gray-100 transition-colors text-left">
        {open ? <FaChevronDown size={9} /> : <FaChevronRight size={9} />}{label}
      </button>
      {open && <div className="p-3 grid grid-cols-1 sm:grid-cols-2 gap-3 bg-white dark:bg-gray-800">{children}</div>}
    </div>
  );
};

// ── Create Dropdown ───────────────────────────────────────────────────────────
const CreateDropdown: React.FC<{ items: { label: string; icon: React.ReactNode; onClick: () => void }[] }> = ({ items }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const h = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)}
        className="flex items-center gap-1.5 px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 text-sm font-medium shadow-sm">
        Create <FaChevronDown size={10} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>
      {open && (
        <div className="absolute right-0 mt-1 w-52 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl z-50 py-1.5">
          <div className="px-3 py-1.5 text-[10px] font-bold text-gray-400 uppercase tracking-wider border-b border-gray-100 dark:border-gray-700 mb-1">Create from this request</div>
          {items.map(({ label, icon, onClick }) => (
            <button key={label} onClick={() => { onClick(); setOpen(false); }}
              className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-amber-50 dark:hover:bg-amber-900/20 hover:text-amber-700 transition-colors text-left">
              <span className="text-gray-400">{icon}</span>{label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

// ── MR Item Row Editor ────────────────────────────────────────────────────────
const MRItemRowEditor: React.FC<{
  item: Partial<MaterialRequestItem>;
  rowNo: number;
  onChange: (k: string, v: any) => void;
  onClose: () => void;
  onDelete: () => void;
  onInsertBelow: () => void;
}> = ({ item, rowNo, onChange, onClose, onDelete, onInsertBelow }) => {
  const set = (k: string, v: any) => onChange(k, v);
  return (
    <tr>
      <td colSpan={7} className="p-0">
        <div className="bg-amber-50/60 dark:bg-amber-900/10 border-b border-amber-200 dark:border-amber-800 px-4 py-3">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs font-bold text-amber-700 dark:text-amber-300 uppercase tracking-wider">Editing Row #{rowNo}</span>
            <div className="flex gap-1">
              <button onClick={onInsertBelow} className="px-2 py-1 text-[11px] bg-amber-600 text-white rounded hover:bg-amber-700">Insert Below</button>
              <button onClick={onDelete} className="px-2 py-1 text-[11px] bg-red-500 text-white rounded hover:bg-red-600">Delete</button>
              <button onClick={onClose} className="px-2 py-1 text-[11px] bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300">ESC</button>
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div><FL required>Item Code</FL><LinkField label="Item Code" hideLabel doctype="Item" value={item.item_code || ''} onChange={v => set('item_code', v)} /></div>
            {/* schedule_date is the correct Frappe fieldname for "Required By" on MR items */}
            <div><FL required>Required By</FL><input type="date" value={(item as any).schedule_date || ''} onChange={e => set('schedule_date', e.target.value)} className={editorInput} /></div>
            <div><FL>Item Name</FL><input value={item.item_name || ''} onChange={e => set('item_name', e.target.value)} className={editorInput} /></div>
          </div>

          <RGroup label="Description">
            <div className="sm:col-span-2">
              <FL>Description</FL>
              <textarea value={item.description || ''} onChange={e => set('description', e.target.value)} rows={2} className={editorInput + ' resize-none'} />
            </div>
          </RGroup>

          <RGroup label="Quantity and Warehouse" defaultOpen>
            <div><FL required>Quantity</FL><input type="number" min={0} step="1" value={item.qty ?? 1} onChange={e => set('qty', parseFloat(e.target.value) || 0)} className={editorNum} /></div>
            <div><FL required>UOM</FL><LinkField label="UOM" hideLabel doctype="UOM" value={item.uom || ''} onChange={v => set('uom', v)} /></div>
            <div><FL>Stock UOM</FL><LinkField label="Stock UOM" hideLabel doctype="UOM" value={item.stock_uom || ''} onChange={v => set('stock_uom', v)} /></div>
            <div><FL>UOM Conversion Factor</FL><input type="number" min={0} step="0.0001" value={(item as any).conversion_factor ?? 1} onChange={e => set('conversion_factor', parseFloat(e.target.value) || 1)} className={editorNum} /></div>
            <div><FL>Target Warehouse</FL><LinkField label="Target Warehouse" hideLabel doctype="Warehouse" value={(item as any).warehouse || ''} onChange={v => set('warehouse', v)} /></div>
          </RGroup>

          <RGroup label="Rate">
            <div><FL>Rate</FL><input type="number" min={0} step="0.01" value={(item as any).rate ?? 0} onChange={e => set('rate', parseFloat(e.target.value) || 0)} className={editorNum} /></div>
          </RGroup>

          <RGroup label="Accounting Details">
            <div className="sm:col-span-2"><FL>Expense Account</FL><LinkField label="Expense Account" hideLabel doctype="Account" value={(item as any).expense_account || ''} onChange={v => set('expense_account', v)} /></div>
          </RGroup>

          <RGroup label="Manufacturing">
            <div><FL>BOM No</FL><LinkField label="BOM No" hideLabel doctype="BOM" value={(item as any).bom_no || ''} onChange={v => set('bom_no', v)} /></div>
          </RGroup>

          <RGroup label="Accounting Dimensions">
            <div><FL>Cost Center</FL><LinkField label="Cost Center" hideLabel doctype="Cost Center" value={(item as any).cost_center || ''} onChange={v => set('cost_center', v)} /></div>
            <div><FL>Project</FL><LinkField label="Project" hideLabel doctype="Project" value={(item as any).project || ''} onChange={v => set('project', v)} /></div>
          </RGroup>
        </div>
      </td>
    </tr>
  );
};

// ── Empty helper ──────────────────────────────────────────────────────────────
const emptyItem = (today: string): Partial<MaterialRequestItem> => ({
  item_code: '', item_name: '', qty: 1, uom: '', schedule_date: today,
});

// ── Component ─────────────────────────────────────────────────────────────────
const MaterialRequestDetail: React.FC = () => {
  const { mrName } = useParams<{ mrName: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const isNew = mrName === 'new';

  const contextProject  = searchParams.get('project')  || '';
  const contextCustomer = searchParams.get('customer') || '';
  const contextCompany  = searchParams.get('company')  || DEFAULT_COMPANY;

  const [doc, setDoc]             = useState<MaterialRequest | 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);
  /** Workflow "Only Allow Edit For" — false until loaded for existing docs */
  const [wfCanEdit, setWfCanEdit] = useState(true);
  /** Whether Material Request has an active workflow in ERPNext (hide duplicate Submit) */
  const [mrHasWorkflow, setMrHasWorkflow] = useState<boolean | null>(null);

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

  const [form, setForm] = useState<Partial<MaterialRequest>>({
    material_request_type: 'Purchase',
    company: contextCompany, project: contextProject, customer: contextCustomer,
    transaction_date: today, schedule_date: today,
    items: [emptyItem(today)],
  });

  const syncForm = useCallback((d: MaterialRequest) => {
    const items = (d.items || []).map((it: any) => ({
      ...it,
      schedule_date: it.schedule_date || it.required_by || '',
    }));
    setForm({
      material_request_type: d.material_request_type || 'Purchase',
      company: (d as any).company || DEFAULT_COMPANY, project: (d as any).project || '', customer: (d as any).customer || '',
      transaction_date: d.transaction_date || today,
      schedule_date: (d as any).schedule_date || today,
      items,
    });
  }, [today]);

  const fetchDoc = useCallback(() => {
    if (isNew || !mrName) return;
    setLoading(true);
    materialRequestService.getMaterialRequest(mrName)
      .then(d => { setDoc(d); syncForm(d); })
      .catch(e => toast.error(e.message))
      .finally(() => setLoading(false));
  }, [isNew, mrName, syncForm]);

  useEffect(() => { fetchDoc(); }, [fetchDoc]);

  useEffect(() => {
    workflowService.getWorkflowInfo('Material Request').then(w => setMrHasWorkflow(!!w)).catch(() => setMrHasWorkflow(false));
  }, []);

  const onWorkflowMeta = useCallback((m: { canEdit: boolean }) => {
    setWfCanEdit(m.canEdit);
  }, []);

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

  const updateItem = (idx: number, k: string, v: any) =>
    setForm(f => {
      const items = [...(f.items || [])];
      items[idx] = { ...items[idx], [k]: v };
      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,
          stock_uom: d.stock_uom || '', uom: d.purchase_uom || d.stock_uom || '',
          description: d.description || '',
        };
        return { ...f, items };
      });
    } catch { /* ignore */ }
  };

  const addItem = (after?: number) => {
    setForm(f => {
      const items = [...(f.items || [])];
      const pos = after !== undefined ? after + 1 : items.length;
      items.splice(pos, 0, emptyItem(today));
      return { ...f, items };
    });
  };
  const removeItem = (idx: number) => {
    setForm(f => { const items = [...(f.items || [])]; items.splice(idx, 1); return { ...f, items }; });
    setExpandedItem(null);
  };

  const buildPayload = (): Partial<MaterialRequest> => {
    // Compute doc-level schedule_date from the earliest item schedule_date or today
    const itemDates = (form.items || [])
      .map((it: any) => it.schedule_date || it.required_by || '')
      .filter(Boolean)
      .sort();
    const docScheduleDate = itemDates[0] || (form as any).schedule_date || today;

    return {
      material_request_type: form.material_request_type || 'Purchase',
      company: (form as any).company || undefined,
      project: (form as any).project || undefined,
      customer: (form as any).customer || undefined,
      transaction_date: form.transaction_date,
      schedule_date: docScheduleDate, // required doc-level field
      items: (form.items || []).filter(it => it.item_code).map((it: any, i) => ({
        ...(it.name ? { name: it.name } : {}),
        item_code:         it.item_code,
        item_name:         it.item_name || it.item_code,
        description:       it.description || undefined,
        qty:               it.qty ?? 1,
        uom:               it.uom || undefined,
        stock_uom:         it.stock_uom || undefined,
        conversion_factor: it.conversion_factor ?? 1,
        schedule_date:     it.schedule_date || it.required_by || docScheduleDate,
        warehouse:         it.warehouse || undefined,
        rate:              it.rate ?? 0,
        expense_account:   it.expense_account || undefined,
        cost_center:       it.cost_center || (form as any).cost_center || undefined,
        project:           it.project || (form as any).project || undefined,
        idx:               i + 1,
      })),
    };
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      if (isNew) {
        const created = await materialRequestService.createMaterialRequest(buildPayload());
        toast.success('Material Request created');
        setIsEditing(false);
        navigate(`/material-requests/${created.name}`);
      } else {
        await materialRequestService.updateMaterialRequest(mrName!, buildPayload());
        toast.success('Material Request saved');
        setIsEditing(false);
        fetchDoc(); // refetch to preserve all fields (company, project, etc.)
      }
    } catch (e: any) { toast.error(e.message || 'Error saving'); }
    finally { setSaving(false); }
  };

  const handleSubmit = async () => {
    if (!mrName || isNew) return;
    try {
      setSubmitting(true);
      const updated = await materialRequestService.submitMaterialRequest(mrName);
      setDoc(updated); syncForm(updated);
      toast.success('Material Request submitted');
    } catch (e: any) { toast.error(e.message || 'Error submitting'); }
    finally { setSubmitting(false); }
  };

  const createPO = () => {
    const p = new URLSearchParams();
    p.set('mr', mrName!);
    if ((form as any).company) p.set('company', String((form as any).company));
    if ((form as any).project) p.set('project', String((form as any).project));
    navigate(`/purchase-orders/new?${p.toString()}`);
  };

  const workflowState = (doc as unknown as { workflow_state?: string })?.workflow_state || '';
  const workflowDocData = useMemo(
    () => (doc ? ({ ...doc } as Record<string, unknown>) : undefined),
    [doc],
  );

  const editable = isNew || (isEditing && wfCanEdit);
  const isSubmitted = !isNew && doc?.docstatus === 1;
  const showManualSubmit = !isNew && doc?.docstatus === 0 && mrHasWorkflow === false;

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

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

      {/* ── Sticky Header ─────────────────────────────────────────────────── */}
      <div className="sticky top-0 z-10 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="px-6 py-4">
          {/* Breadcrumb */}
          <div className="flex items-center gap-1.5 text-xs text-gray-400 mb-2.5">
            <button onClick={() => navigate('/projects')} className="hover:text-orange-500 transition-colors">Project Management</button>
            <span>/</span>
            <button onClick={() => navigate('/material-requests')} className="hover:text-orange-500 transition-colors">Material Requests</button>
            <span>/</span>
            <span className="text-gray-600 dark:text-gray-300 font-medium">{isNew ? 'New Material Request' : mrName}</span>
          </div>

          {/* Title + Actions */}
          <div className="flex items-center justify-between gap-4 flex-wrap">
            <div className="flex items-center gap-3">
              <button onClick={() => navigate('/material-requests')} className="p-1.5 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                <FaArrowLeft size={14} />
              </button>
              <FaBoxes className="text-orange-500 text-xl" />
              <div>
                <h1 className="text-lg font-bold text-gray-900 dark:text-white">
                  {isNew ? 'New Material Request' : mrName}
                </h1>
                {!isNew && (
                  <div className="flex flex-wrap items-center gap-2 mt-0.5">
                    <span className={`inline-block 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 === 'Transferred' || s === 'Issued') return 'bg-green-100 text-green-800';
                      if (s === 'Partially Ordered' || s === 'Ordered') return 'bg-blue-100 text-blue-800';
                      if (s === 'Pending') return 'bg-orange-100 text-orange-800';
                      if (s === 'Stopped' || 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>
                    {workflowState ? (
                      <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-violet-100 text-violet-800 dark:bg-violet-900/40 dark:text-violet-200 border border-violet-200 dark:border-violet-700">
                        {workflowState}
                      </span>
                    ) : null}
                  </div>
                )}
              </div>
            </div>

            <div className="flex items-center gap-2 flex-wrap">
              {isSubmitted && (
                <CreateDropdown items={[
                  { label: 'Purchase Order', icon: <FaShoppingBag size={13} />, onClick: createPO },
                ]} />
              )}
              {showManualSubmit && !isEditing && (
                <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 shadow-sm">
                  {submitting ? <FaSpinner className="animate-spin" size={12} /> : <FaPaperPlane size={12} />} Submit
                </button>
              )}
              {!isNew && !isEditing && !isSubmitted && wfCanEdit && (
                <button onClick={() => setIsEditing(true)}
                  className="flex items-center gap-2 px-4 py-2 border border-orange-500 text-orange-600 rounded-lg hover:bg-orange-50 text-sm font-medium">
                  <FaEdit size={12} /> Edit
                </button>
              )}
              {editable && (
                <>
                  <button onClick={handleSave} disabled={saving}
                    className="flex items-center gap-2 px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 disabled:opacity-50 text-sm font-medium shadow-sm">
                    {saving ? <FaSpinner className="animate-spin" size={12} /> : <FaSave size={12} />}
                    {saving ? 'Saving…' : 'Save'}
                  </button>
                  {!isNew && (
                    <button onClick={() => { if (doc) syncForm(doc); setIsEditing(false); }}
                      className="p-2 border border-gray-300 rounded-lg text-gray-500 hover:bg-gray-100 text-sm">
                      <FaTimes size={12} />
                    </button>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* ── Page Content: main + right sidebar (matches Work Order layout) ─ */}
      <div className="px-6 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 items-start">
          <div className={`space-y-3 ${!isNew ? 'lg:col-span-3' : 'lg:col-span-4'}`}>
        {/* Details Card */}
        <CollapsibleSection title="Details" icon={<FaBoxes size={12} className="text-orange-500" />}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-4">
            <div>
              <FL required>Purpose (Type)</FL>
              {editable
                ? <select value={form.material_request_type || 'Purchase'} onChange={e => set('material_request_type', e.target.value)} className={inputCls}>
                    <option value="Purchase">Purchase</option>
                    <option value="Material Transfer">Material Transfer</option>
                    <option value="Manufacture">Manufacture</option>
                    <option value="Customer Provided">Customer Provided</option>
                    <option value="Material Issue">Material Issue</option>
                  </select>
                : <RV>{form.material_request_type}</RV>}
            </div>
            <div>
              <FL required>Transaction Date</FL>
              {editable
                ? <input type="date" value={form.transaction_date || ''} onChange={e => set('transaction_date', e.target.value)} className={inputCls} />
                : <RV>{form.transaction_date}</RV>}
            </div>
            <div>
              <FL>Company</FL>
              {editable
                ? <LinkField label="Company" hideLabel doctype="Company" value={(form as any).company || ''} onChange={v => set('company' as any, v)} placeholder="Select company…" />
                : <RV>{(form as any).company}</RV>}
            </div>
            <div>
              <FL>Project</FL>
              {editable
                ? <LinkField label="Project" hideLabel doctype="Project" value={(form as any).project || ''} onChange={v => set('project' as any, v)} placeholder="Select project…" />
                : <RV>{(form as any).project}</RV>}
            </div>
          </div>
        </CollapsibleSection>

        {/* Items Card */}
        <CollapsibleSection title="Items" icon={<FaBoxes size={12} className="text-amber-500" />}>
          <div className="overflow-x-auto -mx-2">
            <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 w-28">UOM <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">Qty <span className="text-red-400">*</span></th>
                  <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-32">Required By</th>
                  <th className="text-left text-[10px] font-semibold text-gray-500 uppercase py-2 px-3 w-36">Target Warehouse</th>
                  {editable && <th className="w-16 py-2 px-2" />}
                </tr>
              </thead>
              <tbody>
                {(form.items || []).map((it: any, idx) => (
                  <React.Fragment key={idx}>
                    <tr className={`border-b border-gray-100 dark:border-gray-700 align-middle ${expandedItem === idx ? 'bg-amber-50/60 dark:bg-amber-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="Select item…" />
                          : <span className="font-medium text-gray-800 dark:text-gray-200">{it.item_code || '-'}</span>}
                      </td>
                      <td className="py-1.5 px-2 w-28">
                        {editable
                          ? <LinkField label="UOM" hideLabel doctype="UOM" value={it.uom || ''} onChange={v => updateItem(idx, 'uom', v)} placeholder="UOM" />
                          : <span className="text-gray-500 text-sm">{it.uom || '-'}</span>}
                      </td>
                      <td className="py-1.5 px-2 w-24">
                        {editable
                          ? <input type="number" min={0} step="1" value={it.qty ?? 1} onChange={e => updateItem(idx, 'qty', parseFloat(e.target.value) || 0)} className={inlineNum} />
                          : <span className="block text-right text-sm pr-1">{it.qty ?? 0}</span>}
                      </td>
                      <td className="py-1.5 px-2 w-32">
                        {editable
                          ? <input type="date" value={it.schedule_date || it.required_by || ''} onChange={e => updateItem(idx, 'schedule_date', e.target.value)} className={inlineTxt} />
                          : <span className="text-gray-500 text-sm">{it.schedule_date || it.required_by || '-'}</span>}
                      </td>
                      <td className="py-1.5 px-2 w-36">
                        {editable
                          ? <LinkField label="Warehouse" hideLabel doctype="Warehouse" value={it.warehouse || ''} onChange={v => updateItem(idx, 'warehouse', v)} placeholder="Warehouse" />
                          : <span className="text-gray-500 text-sm truncate max-w-[120px] block">{it.warehouse || '-'}</span>}
                      </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-amber-600 text-white' : 'text-amber-600 hover:bg-amber-50'}`}>
                              <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 && (
                      <MRItemRowEditor
                        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={7} className="py-2 px-3">
                    <button onClick={() => addItem()} className="flex items-center gap-1.5 text-orange-600 hover:text-orange-700 text-sm font-medium">
                      <FaPlus size={10} /> Add Row
                    </button>
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>
        </CollapsibleSection>
          </div>

          {!isNew && mrName && (
            <aside className="lg:col-span-1 space-y-6 lg:sticky lg:top-28 lg:self-start">
              <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-5 border border-gray-200 dark:border-gray-700">
                <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                  Workflow Actions
                </h2>
                <WorkflowActions
                  doctype="Material Request"
                  docname={mrName}
                  workflowState={workflowState}
                  docData={workflowDocData as Record<string, any>}
                  documentLabel="Material Request"
                  onStateChange={fetchDoc}
                  onWorkflowMeta={onWorkflowMeta}
                  className="space-y-4"
                />
              </div>

              <ActivityLog
                doctype="Material Request"
                docname={mrName || ''}
                creationDate={doc?.creation}
                createdBy={doc?.owner}
                compact
                initialVisible={5}
                collapsible
                startCollapsed
              />
            </aside>
          )}
        </div>
      </div>
    </div>
  );
};

export default MaterialRequestDetail;
