import React, { useEffect, useState, useCallback } from 'react';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Popover,
  Row,
  Select,
  Space,
  Spin,
  Table,
  Tag,
  Typography,
  message,
  Descriptions,
} from 'antd';
import {
  PlusOutlined,
  DollarCircleOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  FilterOutlined,
  CheckCircleOutlined,
  FormOutlined,
  LockOutlined,
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import dayjs, { Dayjs } from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';
import { CustomPattiModal } from './CustomPattiModal';

const { Text } = Typography;
const { RangePicker } = DatePicker;

const ENTITY_LABEL = 'Arrival Lot History';

interface ArrivalRecord {
  id: string;
  lotNo: string;
  billNo?: string;
  purchaseDate: string;
  arrivalDate: string;
  dateOfDespatch?: string;
  unit: string;
  quantity: string;
  bags?: string;
  weightPerBag?: string;
  remainingQuantity: string;
  remainingBags?: string;
  totalFreight: string;
  freight: string;
  extraFreight: string;
  associationFee: string;
  unloadingFee: string;
  miscellaneousFee: string;
  advanceAmount: string;
  truckNo?: string;
  agentName?: string;
  placeOfDespatch?: string;
  placeOfArrival?: string;
  status: 'ACTIVE' | 'DEPLETED' | 'CLOSED';
  vegetable?: { id: string; name: string; tamilName?: string };
  supplier?: { id: string; name: string };
  arrivalSettlement?: {
    id: string;
    settlementNo: string;
    status: string;
    netPayable: string;
    paidAmount?: string;
    balanceAmount?: string;
    paymentMode?: string;
  } | null;
  retailStocks?: {
    id: string;
    quantity: string;
    remainingQuantity: string;
    bags?: string;
    remainingBags?: string;
  }[];
  _count?: { saleItems: number };
  remarks?: string;
}

export const ArrivalLotHistory: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const [arrivals, setArrivals] = useState<ArrivalRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [totalRecords, setTotalRecords] = useState(0);
  const [_, setTotalPages] = useState(1);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // Filters
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [settlementFilter, setSettlementFilter] = useState<string | null>(null);

  // Master Data
  const [vegetables, setVegetables] = useState<{ id: string; name: string }[]>([]);
  const [suppliers, setSuppliers] = useState<{ id: string; name: string; outstandingBalance?: string | number }[]>([]);
  const [paymentModes, setPaymentModes] = useState<{ label: string; value: string }[]>([]);
  const [purchaseUnits, setPurchaseUnits] = useState<{ value: string; label: string }[]>([]);

  // Add Arrival Modal State
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [addSaving, setAddSaving] = useState(false);
  const [addForm] = Form.useForm();
  const [lotStatus, setLotStatus] = useState<{
    checking: boolean;
    isAvailable: boolean | null;
    message: string;
    vegetableName?: string | null;
    remainingQuantity?: number;
  }>({
    checking: false,
    isAvailable: null,
    message: '',
  });

  // Watchers for Add Form auto-calculations
  const addSelectedUnit = Form.useWatch('unit', addForm) || 'KG';
  const addFreightVal = Form.useWatch('freight', addForm) || 0;
  const addExtraFreightVal = Form.useWatch('extraFreight', addForm) || 0;
  const addAssociationVal = Form.useWatch('associationFee', addForm) || 0;
  const addUnloadingVal = Form.useWatch('unloadingFee', addForm) || 0;
  const addMiscVal = Form.useWatch('miscellaneousFee', addForm) || 0;
  const selectedSupplierId = Form.useWatch('supplierId', addForm);
  const selectedSupplier = suppliers.find(s => s.id === selectedSupplierId);

  const calculatedTotalFreight = (
    Number(addFreightVal || 0) +
    Number(addExtraFreightVal || 0) +
    Number(addAssociationVal || 0) +
    Number(addUnloadingVal || 0) +
    Number(addMiscVal || 0)
  ).toFixed(2);

  // Edit Modal State
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<ArrivalRecord | null>(null);
  const [editSaving, setEditSaving] = useState(false);
  const [editForm] = Form.useForm();

  // Watchers for Edit Form auto-calculations
  const editSelectedUnit = Form.useWatch('unit', editForm) || 'KG';
  const editFreightVal = Form.useWatch('freight', editForm) || 0;
  const editExtraFreightVal = Form.useWatch('extraFreight', editForm) || 0;
  const editAssociationVal = Form.useWatch('associationFee', editForm) || 0;
  const editUnloadingVal = Form.useWatch('unloadingFee', editForm) || 0;
  const editMiscVal = Form.useWatch('miscellaneousFee', editForm) || 0;
  const editSelectedSupplierId = Form.useWatch('supplierId', editForm);
  const editSelectedSupplier = suppliers.find(s => s.id === editSelectedSupplierId);

  const editCalculatedTotalFreight = (
    Number(editFreightVal || 0) +
    Number(editExtraFreightVal || 0) +
    Number(editAssociationVal || 0) +
    Number(editUnloadingVal || 0) +
    Number(editMiscVal || 0)
  ).toFixed(2);

  // View Modal State
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [viewLoading, setViewLoading] = useState(false);
  const [viewRecord, setViewRecord] = useState<any>(null);

  // Settle 4% Commission Patti Modal State
  const [settleModalVisible, setSettleModalVisible] = useState(false);
  const [settlePreviewLoading, setSettlePreviewLoading] = useState(false);
  const [settleSubmitting, setSettleSubmitting] = useState(false);
  const [selectedLotId, setSelectedLotId] = useState<string | null>(null);
  const [settlePreviewData, setSettlePreviewData] = useState<any>(null);
  const [commissionRate, setCommissionRate] = useState<number>(8.0);
  const [settleForm] = Form.useForm();

  // Custom / Modified Patti Modal State (For sharing without touching real data)
  const [customPattiVisible, setCustomPattiVisible] = useState(false);
  const [customPattiPurchaseId, setCustomPattiPurchaseId] = useState<string | null>(null);
  const [customPattiLotNo, setCustomPattiLotNo] = useState<string>('');

  const openCustomPattiModal = (purchaseId: string, lotNo?: string) => {
    setCustomPattiPurchaseId(purchaseId);
    setCustomPattiLotNo(lotNo || '');
    setCustomPattiVisible(true);
  };

  // Fetch Master Data
  const fetchMeta = async () => {
    try {
      const [metaRes, paymentRes] = await Promise.all([
        jwtAxios.get(ENDPOINTS.PURCHASE_META),
        jwtAxios.get(ENDPOINTS.PAYMENTMODES),
      ]);
      const metaResult = metaRes.data?.result || {};
      setVegetables(Array.isArray(metaResult.vegetables) ? metaResult.vegetables : []);
      setSuppliers(Array.isArray(metaResult.suppliers) ? metaResult.suppliers : []);
      setPurchaseUnits(Array.isArray(metaResult.purchaseUnits) ? metaResult.purchaseUnits : []);

      const modes = paymentRes.data?.PaymentMode || {};
      setPaymentModes(
        Object.entries(modes).map(([key, value]) => ({
          label: key,
          value: String(value),
        }))
      );
    } catch (err: any) {
      console.error('Failed to load master metadata', err);
    }
  };

  // Fetch Arrivals List
  const fetchArrivals = async (
    page: number = currentPage,
    limit: number = pageSize,
    search: string = searchText,
    dates: [Dayjs, Dayjs] | null = dateRange,
    settlementStatus: string | null | undefined = settlementFilter
  ) => {
    setLoading(true);
    try {
      const params: any = { page, limit };
      if (search) params.search = search;
      if (dates && dates[0] && dates[1]) {
        params.dateFrom = dates[0].format('YYYY-MM-DD');
        params.dateTo = dates[1].format('YYYY-MM-DD');
      }
      if (settlementStatus) {
        params.settlementStatus = settlementStatus;
      }

      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS, { params });
      setArrivals(res.data?.data || []);
      const total = res.data?.meta?.total || 0;
      setTotalRecords(total);
      setTotalPages(Math.ceil(total / limit) || 1);
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to load arrival lots history.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchArrivals(currentPage, pageSize, searchText, dateRange, settlementFilter);
    fetchMeta();

    // If navigated with action=add, automatically pop up Add Modal
    if (searchParams.get('action') === 'add') {
      openAddModal();
      navigate('/arrivals/lot-history', { replace: true });
    }
  }, []);

  const handleSearch = (val: string) => {
    setSearchText(val);
    setCurrentPage(1);
    fetchArrivals(1, pageSize, val, dateRange, settlementFilter);
  };

  const handleDateChange = (dates: any) => {
    setDateRange(dates);
    setCurrentPage(1);
    fetchArrivals(1, pageSize, searchText, dates, settlementFilter);
  };

  const handleSettlementFilterChange = (val?: string) => {
    const status = val ?? null;
    setSettlementFilter(status);
    setCurrentPage(1);
    fetchArrivals(1, pageSize, searchText, dateRange, status);
  };

  // Check Lot Reusability
  const checkLotAvailability = useCallback(async (lotNo: string, vegetableId?: string) => {
    if (!lotNo || !lotNo.trim()) {
      setLotStatus({ checking: false, isAvailable: null, message: '', vegetableName: null });
      return;
    }

    setLotStatus((prev) => ({ ...prev, checking: true }));
    try {
      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_CHECK_LOT, {
        params: { lotNo: lotNo.trim(), vegetableId },
      });
      const data = res.data?.data;
      setLotStatus({
        checking: false,
        isAvailable: data?.isAvailable,
        message: data?.message || '',
        vegetableName: data?.vegetableName || null,
        remainingQuantity: data?.remainingQuantity,
      });
    } catch (err: any) {
      setLotStatus({
        checking: false,
        isAvailable: false,
        message: err?.response?.data?.message || 'Could not verify lot status.',
        vegetableName: null,
      });
    }
  }, []);

  // Open Add Arrival Modal
  const openAddModal = () => {
    fetchMeta();
    addForm.resetFields();
    addForm.setFieldsValue({
      unit: 'KG',
      arrivalDate: dayjs(),
      dateOfDespatch: dayjs(),
      placeOfArrival: 'Amman Vegetables Stores',
      freight: 0,
      extraFreight: 0,
      associationFee: 0,
      unloadingFee: 0,
      miscellaneousFee: 0,
      advanceAmount: 0,
    });
    setLotStatus({ checking: false, isAvailable: null, message: '' });
    setAddModalVisible(true);
  };

  // Submit Add Arrival
  const handleAddSubmit = async (values: any) => {
    if (lotStatus.isAvailable === false) {
      message.error(lotStatus.message || 'Lot is currently active and must be closed before reuse.');
      return;
    }

    setAddSaving(true);
    try {
      const payload = {
        ...values,
        quantity: values.quantity ? Number(values.quantity) : 0,
        arrivalDate: values.arrivalDate ? dayjs(values.arrivalDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        dateOfDespatch: values.dateOfDespatch ? dayjs(values.dateOfDespatch).format('YYYY-MM-DD') : undefined,
        totalFreight: Number(calculatedTotalFreight),
      };

      await jwtAxios.post(ENDPOINTS.ARRIVALS, payload);
      message.success(`Arrival Lot "${values.lotNo}" saved successfully!`);
      setAddModalVisible(false);
      fetchArrivals(1, pageSize);
    } catch (err: any) {
      if (err?.response?.data?.errors) {
        const errors = err.response.data.errors;
        const formErrors = Object.keys(errors).map((key) => ({
          name: key,
          errors: Array.isArray(errors[key]) ? errors[key] : [errors[key]],
        }));
        addForm.setFields(formErrors);
        message.error('Please fix the highlighted fields.');
      } else {
        message.error(err?.response?.data?.message || 'Failed to save arrival addition.');
      }
    } finally {
      setAddSaving(false);
    }
  };

  // Open View Details Modal
  const openViewModal = async (id: string) => {
    setViewModalVisible(true);
    setViewLoading(true);
    try {
      const res = await jwtAxios.get(`${ENDPOINTS.ARRIVALS}/${id}`);
      setViewRecord(res.data?.data);
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to load arrival details.');
      setViewModalVisible(false);
    } finally {
      setViewLoading(false);
    }
  };

  // Open Edit Modal
  const openEditModal = (record: ArrivalRecord) => {
    setEditingRecord(record);
    editForm.setFieldsValue({
      vegetableId: record.vegetable?.id,
      lotNo: record.lotNo,
      billNo: record.billNo,
      unit: record.unit || 'KG',
      bags: record.bags ? Number(record.bags) : undefined,
      quantity: record.quantity ? Number(record.quantity) : undefined,
      dateOfDespatch: record.dateOfDespatch ? dayjs(record.dateOfDespatch) : undefined,
      arrivalDate: record.arrivalDate ? dayjs(record.arrivalDate) : dayjs(),
      placeOfDespatch: record.placeOfDespatch,
      placeOfArrival: record.placeOfArrival,
      truckNo: record.truckNo,
      supplierId: record.supplier?.id,
      agentName: record.agentName,
      freight: Number(record.freight || 0),
      extraFreight: Number(record.extraFreight || 0),
      associationFee: Number(record.associationFee || 0),
      unloadingFee: Number(record.unloadingFee || 0),
      miscellaneousFee: Number(record.miscellaneousFee || 0),
      advanceAmount: Number(record.advanceAmount || 0),
      remarks: record.remarks,
    });
    setEditModalVisible(true);
  };

  // Handle Edit Submit
  const handleEditSubmit = async (values: any) => {
    if (!editingRecord) return;
    setEditSaving(true);
    try {
      const payload = {
        ...values,
        quantity: values.quantity ? Number(values.quantity) : 0,
        arrivalDate: values.arrivalDate ? dayjs(values.arrivalDate).format('YYYY-MM-DD') : undefined,
        dateOfDespatch: values.dateOfDespatch ? dayjs(values.dateOfDespatch).format('YYYY-MM-DD') : undefined,
        totalFreight: Number(editCalculatedTotalFreight),
      };

      await jwtAxios.put(`${ENDPOINTS.ARRIVALS}/${editingRecord.id}`, payload);
      message.success('Arrival lot updated successfully.');
      setEditModalVisible(false);
      fetchArrivals();
    } catch (err: any) {
      if (err?.response?.data?.errors) {
        const errors = err.response.data.errors;
        const formErrors = Object.keys(errors).map((key) => ({
          name: key,
          errors: Array.isArray(errors[key]) ? errors[key] : [errors[key]],
        }));
        editForm.setFields(formErrors);
        message.error('Please fix the highlighted fields.');
      } else {
        message.error(err?.response?.data?.message || 'Failed to update arrival lot.');
      }
    } finally {
      setEditSaving(false);
    }
  };

  // Handle Delete
  const handleDelete = async (id: string) => {
    try {
      await jwtAxios.delete(`${ENDPOINTS.ARRIVALS}/${id}`);
      message.success('Arrival lot deleted successfully.');
      fetchArrivals();
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to delete arrival lot.');
    }
  };

  // Open Settle Modal directly on this page
  const openSettleModal = async (purchaseId: string) => {
    setSelectedLotId(purchaseId);
    setSettleModalVisible(true);
    setSettlePreviewLoading(true);
    try {
      const initialRate = commissionRate ?? 8.0;
      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_SETTLEMENT_PREVIEW(purchaseId), {
        params: { commissionPercent: initialRate },
      });
      let preview = res.data?.data;
      const existing = preview?.arrival?.arrivalSettlement;
      let effectiveRate = initialRate;
      if (existing?.commissionPercent != null) {
        effectiveRate = Number(existing.commissionPercent);
        if (effectiveRate !== initialRate) {
          setCommissionRate(effectiveRate);
          const res2 = await jwtAxios.get(ENDPOINTS.ARRIVALS_SETTLEMENT_PREVIEW(purchaseId), {
            params: { commissionPercent: effectiveRate },
          });
          preview = res2.data?.data;
        }
      } else {
        setCommissionRate(initialRate);
      }
      setSettlePreviewData(preview);
      const calc = preview?.calculations;
      settleForm.setFieldsValue({
        settlementDate: existing?.settlementDate ? dayjs(existing.settlementDate) : dayjs(),
        paidAmount: Math.max(0, Number(calc?.netPayable || 0)),
        paymentMode: existing?.paymentMode || paymentModes[0]?.value || 'CASH',
        remarks: existing?.remarks || undefined,
      });
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to generate settlement preview.');
      setSettleModalVisible(false);
    } finally {
      setSettlePreviewLoading(false);
    }
  };

  // Re-calculate preview when commission rate changes dynamically
  const handleCommissionChange = async (rate: number | null) => {
    const numRate = rate === null || isNaN(Number(rate)) ? 0 : Number(rate);
    setCommissionRate(numRate);

    // Instant local calculation update for snappy UI feedback
    if (settlePreviewData?.calculations) {
      const gross = Number(settlePreviewData.calculations.grossSalesTotal || 0);
      const commAmt = Math.round(((gross * numRate) / 100) * 100) / 100;
      const totalDed = Number(settlePreviewData.calculations.totalDeductions || 0);
      const adv = Number(settlePreviewData.calculations.advanceAdjusted || 0);
      const net = Math.round((gross - commAmt - totalDed - adv) * 100) / 100;

      setSettlePreviewData((prev: any) => ({
        ...prev,
        calculations: {
          ...prev?.calculations,
          commissionPercent: numRate,
          commissionAmount: commAmt,
          netPayable: net,
        },
      }));
      settleForm.setFieldsValue({
        paidAmount: Math.max(0, net),
      });
    }

    if (!selectedLotId) return;
    try {
      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_SETTLEMENT_PREVIEW(selectedLotId), {
        params: { commissionPercent: numRate },
      });
      setSettlePreviewData(res.data?.data);
      const calc = res.data?.data?.calculations;
      settleForm.setFieldsValue({
        paidAmount: Math.max(0, Number(calc?.netPayable || 0)),
      });
    } catch {
      // ignore
    }
  };

  // Submit Settlement directly from this page
  const handleCreateSettlement = async (values: any) => {
    if (!selectedLotId) return;
    setSettleSubmitting(true);
    try {
      const payload = {
        purchaseId: Number(selectedLotId),
        settlementDate: values.settlementDate ? dayjs(values.settlementDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        commissionPercent: typeof commissionRate === 'number' ? commissionRate : 8.0,
        paidAmount: Math.max(0, Number(values.paidAmount || 0)),
        paymentMode: values.paymentMode || 'CASH',
        remarks: values.remarks,
      };

      const res = await jwtAxios.post(ENDPOINTS.ARRIVALS_SETTLEMENTS, payload);
      message.success(res.data?.message || 'P.Patti Settlement generated successfully!');
      setSettleModalVisible(false);
      fetchArrivals(currentPage, pageSize, searchText, dateRange, settlementFilter);
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to create settlement.');
    } finally {
      setSettleSubmitting(false);
    }
  };

  const columns = [
    {
      title: 'Arrival Date',
      dataIndex: 'arrivalDate',
      key: 'arrivalDate',
      width: 110,
      render: (d: string) => (d ? dayjs(d).format('DD MMM YYYY') : '-'),
    },
    {
      title: 'Lot #',
      dataIndex: 'lotNo',
      key: 'lotNo',
      width: 100,
      render: (lotNo: string) => <Tag color="blue" className="font-bold">{lotNo}</Tag>,
    },
    {
      title: 'Item',
      dataIndex: ['vegetable', 'name'],
      key: 'vegetable',
      width: 140,
      render: (name: string) => <span className="font-semibold text-gray-900">{name || '-'}</span>,
    },
    {
      title: 'Supplier',
      dataIndex: ['supplier', 'name'],
      key: 'supplier',
      width: 150,
      render: (name: string, record: any) => name || record.cashSupplierName || record.agentName || 'Farmer',
    },
    {
      title: 'Total Wt (KG)',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 120,
      render: (q: string) => `${Number(q || 0).toFixed(2)} KG`,
    },
    {
      title: 'Sacks/Bags',
      dataIndex: 'bags',
      key: 'bags',
      width: 110,
      render: (b: string, record: ArrivalRecord) =>
        b ? `${b} ${record.unit}` : '-',
    },
    {
      title: 'Stock Remaining',
      key: 'remainingQuantity',
      width: 170,
      render: (_: any, record: ArrivalRecord) => {
        const wholesaleRemaining = Number(record.remainingQuantity || 0);
        const retailRemaining = record.retailStocks?.reduce((acc, curr) => acc + Number(curr.remainingQuantity || 0), 0) || 0;
        const remainingQuantity = wholesaleRemaining + retailRemaining;
        const totalQuantity = Number(record.quantity || 0);

        const wholesaleRemainingBags = Number(record.remainingBags || 0);
        const retailRemainingBags = record.retailStocks?.reduce((acc, curr) => acc + Number(curr.remainingBags || 0), 0) || 0;
        const remainingBags = wholesaleRemainingBags + retailRemainingBags;
        const totalBags = Number(record.bags || 0);

        let isDepleted = false;
        let displayRemaining = '';
        let displayTotal = '';
        let displayUnit = 'KG';
        let alertColor = 'blue';

        if (totalQuantity === 0 && totalBags > 0) {
          isDepleted = remainingBags <= 0;
          displayRemaining = remainingBags.toString();
          displayTotal = totalBags.toString();
          displayUnit = record.unit || 'BAG';
          alertColor = isDepleted ? 'green' : remainingBags <= totalBags * 0.2 ? 'orange' : 'blue';
        } else {
          isDepleted = remainingQuantity <= 0;
          displayRemaining = remainingQuantity.toFixed(2);
          displayTotal = totalQuantity.toFixed(2);
          displayUnit = 'KG';
          alertColor = isDepleted ? 'green' : remainingQuantity <= totalQuantity * 0.2 ? 'orange' : 'blue';
        }

        return (
          <div>
            <Tag color={alertColor} className="font-semibold">
              {displayRemaining} / {displayTotal} {displayUnit}
            </Tag>
            {isDepleted && (
              <Tag color="volcano" className="text-xs" title="Lot is fully depleted and can be reused">
                ♻ Depleted
              </Tag>
            )}
          </div>
        );
      },
    },
    {
      title: 'Total Freight (₹)',
      dataIndex: 'totalFreight',
      key: 'totalFreight',
      width: 130,
      render: (f: string) => `₹ ${Number(f || 0).toFixed(2)}`,
    },
    {
      title: 'Truck No',
      dataIndex: 'truckNo',
      key: 'truckNo',
      width: 130,
      render: (t: string) => t || '-',
    },
    {
      title: 'Settlement & Payment',
      key: 'settlementStatus',
      width: 170,
      render: (_: any, record: ArrivalRecord) => {
        if (record.arrivalSettlement) {
          const paid = Number(record.arrivalSettlement.paidAmount || 0);
          const bal = Number(record.arrivalSettlement.balanceAmount || 0);
          const net = Number(record.arrivalSettlement.netPayable || 0);
          const isSettled = record.arrivalSettlement.status === 'SETTLED';
          return (
            <div>
              <Popover content={
                <div>
                  <div><strong>Patti:</strong> #{record.arrivalSettlement.settlementNo}</div>
                  <div><strong>Net Payable:</strong> ₹{net.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</div>
                  <div><strong>Paid:</strong> ₹{paid.toLocaleString('en-IN', { minimumFractionDigits: 2 })} ({record.arrivalSettlement.paymentMode || 'CASH'})</div>
                  {bal > 0 && <div><strong>Balance:</strong> ₹{bal.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</div>}
                </div>
              }>
                <Tag color={isSettled ? 'success' : 'warning'} className="font-bold cursor-pointer">
                  {record.arrivalSettlement.status}
                </Tag>
              </Popover>
              {paid > 0 && (
                <div style={{ fontSize: 11, color: '#389e0d', fontWeight: 600, marginTop: 2 }}>
                  Paid: ₹{paid.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                </div>
              )}
              {bal > 0 && (
                <div style={{ fontSize: 11, color: '#cf1322', marginTop: 1 }}>
                  Bal: ₹{bal.toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                </div>
              )}
            </div>
          );
        }
        return <Tag color="processing">UNSETTLED</Tag>;
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right' as const,
      width: 140,
      render: (_: any, record: ArrivalRecord) => {
        const wholesaleRemaining = Number(record.remainingQuantity || 0);
        const retailRemaining = record.retailStocks?.reduce((acc, curr) => acc + Number(curr.remainingQuantity || 0), 0) || 0;
        let remaining = wholesaleRemaining + retailRemaining;

        const totalQuantity = Number(record.quantity || 0);
        const totalBags = Number(record.bags || 0);
        let displayUnit = 'KG';

        if (totalQuantity === 0 && totalBags > 0) {
          const wholesaleRemainingBags = Number(record.remainingBags || 0);
          const retailRemainingBags = record.retailStocks?.reduce((acc, curr) => acc + Number(curr.remainingBags || 0), 0) || 0;
          remaining = wholesaleRemainingBags + retailRemainingBags;
          displayUnit = record.unit || 'BAG';
        }

        return (
          <Space size="small">
            <Popover content="View Details">
              <Button
                type="link"
                icon={<EyeOutlined />}
                onClick={() => openViewModal(record.id)}
              />
            </Popover>

            <Popover
              content={
                remaining > 0 && !record.arrivalSettlement
                  ? 'Cannot settle: Sales are not fully completed (items remaining)'
                  : !record.arrivalSettlement
                    ? 'Settle Commission Patti'
                    : remaining > 0
                      ? `Update Patti (${record.arrivalSettlement.settlementNo}) - ${displayUnit === 'KG' ? remaining.toFixed(1) : remaining} ${displayUnit} Remaining`
                      : `Settled (${record.arrivalSettlement.settlementNo}) - Click to View (Locked)`
              }
            >
              <Button
                type="link"
                disabled={remaining > 0 && !record.arrivalSettlement}
                icon={
                  !record.arrivalSettlement ? (
                    <DollarCircleOutlined style={{ color: remaining > 0 ? '#ccc' : '#0F5132', fontSize: 16 }} />
                  ) : remaining > 0 ? (
                    <DollarCircleOutlined style={{ color: '#0284c7', fontSize: 16 }} />
                  ) : (
                    <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 16 }} />
                  )
                }
                onClick={() => openSettleModal(record.id)}
              />
            </Popover>

            <Popover content="Custom / Modified Patti (For Sending to Others)">
              <Button
                type="link"
                icon={<FormOutlined style={{ color: '#722ed1', fontSize: 16 }} />}
                onClick={() => openCustomPattiModal(record.id, record.lotNo)}
              />
            </Popover>

            {!record.arrivalSettlement && (
              <>
                <Popover content="Edit">
                  <Button
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => openEditModal(record)}
                  />
                </Popover>

                <Popover content="Delete">
                  <Popconfirm
                    title="Delete Arrival Lot"
                    description="Are you sure you want to delete this arrival lot?"
                    okText="Delete"
                    cancelText="Cancel"
                    okButtonProps={{ danger: true }}
                    onConfirm={() => handleDelete(record.id)}
                  >
                    <Button danger type="link" icon={<DeleteOutlined />} />
                  </Popconfirm>
                </Popover>
              </>
            )}
          </Space>
        );
      },
    },
  ];

  const salesBreakdownColumns = [
    {
      title: 'Date',
      dataIndex: 'invoiceDate',
      key: 'date',
      width: 110,
      render: (d: string, item: any) => {
        const val = d || item.sale?.invoiceDate;
        return val ? dayjs(val).format('DD/MM/YYYY') : '-';
      },
    },
    {
      title: 'Invoice #',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      width: 150,
      render: (no: string, item: any) => (
        <span className="font-semibold text-blue-700">
          {no || item.sale?.invoiceNo || '-'}
        </span>
      ),
    },
    {
      title: 'Channel',
      dataIndex: 'channel',
      key: 'channel',
      width: 110,
      render: (channel: string) => (
        <Tag color={channel === 'RETAIL' ? 'orange' : 'blue'} className="font-semibold">
          {channel === 'RETAIL' ? 'Retail' : 'Wholesale'}
        </Tag>
      ),
    },
    {
      title: 'Buyer',
      key: 'buyer',
      render: (_: any, item: any) =>
        item.buyerName || item.sale?.customer?.name || item.sale?.walkInName || (item.channel === 'RETAIL' ? 'Retail Walk-in' : 'Buyer'),
    },
    {
      title: 'Quantity (KG)',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 120,
      render: (q: any) => `${Number(q || 0).toFixed(2)} KG`,
    },
    {
      title: 'Rate / KG',
      dataIndex: 'sellingRate',
      key: 'rate',
      width: 110,
      render: (r: any) => `₹ ${Number(r || 0).toFixed(2)}`,
    },
    {
      title: 'Total (₹)',
      dataIndex: 'total',
      key: 'total',
      width: 120,
      render: (t: any) => <strong>₹ {Number(t || 0).toFixed(2)}</strong>,
    },
  ];

  return (
    <div>
      <Spin spinning={loading}>
        <AppContainer
          title={ENTITY_LABEL}
          headerAction={
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={openAddModal}
                className="bg-green-600"
              >
                Add Arrival
              </Button>
              <Button
                icon={<DollarCircleOutlined />}
                onClick={() => navigate('/arrivals/settlements')}
              >
                Patti Settlements
              </Button>
            </Space>
          }
        >
          {/* Toolbar Section */}
          <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
            <Space wrap>
              <Select
                placeholder={
                  <>
                    <FilterOutlined /> Status
                  </>
                }
                allowClear
                style={{ width: 160 }}
                value={settlementFilter}
                onChange={handleSettlementFilterChange}
                options={[
                  { label: 'UNSETTLED', value: 'UNSETTLED' },
                  { label: 'SETTLED', value: 'SETTLED' },
                ]}
              />

              <RangePicker
                format="DD/MM/YYYY"
                value={dateRange}
                onChange={handleDateChange}
                style={{ width: 240 }}
              />

              <Input.Search
                placeholder="Search Lot, Item, Supplier, Truck..."
                value={searchText}
                onChange={(e) => {
                  const val = e.target.value;
                  setSearchText(val);
                  if (!val) {
                    handleSearch('');
                  }
                }}
                onSearch={handleSearch}
                allowClear
                style={{ width: 260 }}
              />
            </Space>

            <div>
              <Tag color="cyan">
                {totalRecords} {ENTITY_LABEL.toLowerCase()}
              </Tag>
            </div>
          </div>

          {/* Table Section */}
          <Table
            rowKey="id"
            columns={columns}
            dataSource={arrivals}
            loading={loading}
            scroll={{ x: 'max-content', y: 400 }}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: totalRecords,
              showSizeChanger: true,
              showTotal: (total) => `Total ${total} arrival lots`,
            }}
            onChange={(pageInfo) => {
              setCurrentPage(pageInfo.current!);
              setPageSize(pageInfo.pageSize!);
              fetchArrivals(pageInfo.current!, pageInfo.pageSize!, searchText, dateRange, settlementFilter);
            }}
          />
        </AppContainer>

        {/* ADD ARRIVAL MODAL */}
        <Modal
          title={
            <div className="flex items-center justify-between pr-6 border-b pb-3">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-700 font-bold">
                  +
                </div>
                <div>
                  <h3 className="text-base font-bold text-gray-900 leading-tight m-0">
                    Add Commission Arrival Consignment
                  </h3>
                  <span className="text-xs text-gray-500 font-normal">
                    Record inward stock lot with logistics and freight charges
                  </span>
                </div>
              </div>
            </div>
          }
          open={addModalVisible}
          onCancel={() => setAddModalVisible(false)}
          footer={null}
          width={860}
          centered
          destroyOnHidden
          styles={{
            body: {
              maxHeight: 'calc(85vh - 90px)',
              overflowY: 'auto',
              padding: '16px 20px',
            },
          }}
        >
          <Form
            form={addForm}
            layout="vertical"
            onFinish={handleAddSubmit}
            initialValues={{
              unit: 'KG',
              arrivalDate: dayjs(),
              dateOfDespatch: dayjs(),
              placeOfArrival: 'Amman Vegetables Stores',
              freight: 0,
              extraFreight: 0,
              associationFee: 0,
              unloadingFee: 0,
              miscellaneousFee: 0,
              advanceAmount: 0,
            }}
          >
            {/* 1. ITEM & LOT IDENTIFICATION */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                1. Item & Lot Identification
              </span>
              <Row gutter={16}>
                <Col xs={24} sm={10}>
                  <Form.Item
                    name="vegetableId"
                    label="Vegetable Item"
                    rules={[{ required: true, message: 'Please select a vegetable!' }]}
                  >
                    <Select
                      showSearch
                      placeholder="Select vegetable"
                      optionFilterProp="children"
                      onChange={(vegId) => {
                        const currentLot = addForm.getFieldValue('lotNo');
                        if (currentLot) {
                          checkLotAvailability(currentLot, vegId);
                        }
                        const veg = vegetables.find((v) => String(v.id) === String(vegId));
                        const vegName = (veg?.name || '').toLowerCase();
                        if (vegName.includes('banana') || vegName.includes('வாழை')) {
                          addForm.setFieldsValue({ unit: 'THAAR' });
                        } else if (vegName.includes('coconut') || vegName.includes('தேங்காய்')) {
                          addForm.setFieldsValue({ unit: 'KG' });
                        } else if (vegName.includes('cabbage') || vegName.includes('முட்டைக்கோஸ்')) {
                          addForm.setFieldsValue({ unit: 'BAG' });
                        }
                      }}
                    >
                      {vegetables.map((v) => (
                        <Select.Option key={v.id} value={v.id}>
                          {v.name}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={8}>
                  <Form.Item
                    name="lotNo"
                    label="Lot Number (e.g. 1, 2, 3)"
                    rules={[{ required: true, message: 'Please enter lot number!' }]}
                    extra={
                      lotStatus.checking ? (
                        <span className="text-xs text-gray-500">Checking availability...</span>
                      ) : lotStatus.isAvailable === true ? (
                        <span className="text-xs text-emerald-600 font-semibold">✓ {lotStatus.message || 'Lot available for entry'}</span>
                      ) : lotStatus.isAvailable === false ? (
                        <span className="text-xs text-red-600 font-semibold">
                          ⚠ {lotStatus.message || (
                            lotStatus.vegetableName
                              ? `Lot active for ${lotStatus.vegetableName}. The lot must be closed before reuse.`
                              : 'Lot is currently active and must be closed before reuse.'
                          )}
                        </span>
                      ) : undefined
                    }
                  >
                    <Input
                      placeholder="e.g. 1"
                      onChange={(e) => {
                        const lot = e.target.value;
                        const vegId = addForm.getFieldValue('vegetableId');
                        checkLotAvailability(lot, vegId);
                      }}
                    />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={6}>
                  <Form.Item name="billNo" label="Consignment / Bill #">
                    <Input placeholder="Optional Bill #" />
                  </Form.Item>
                </Col>
              </Row>
            </div>

            {/* 2. SACKS & WEIGHT DETAILS */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                2. Weight & Packaging Details
              </span>
              <Row gutter={16}>
                <Col xs={12} sm={8}>
                  <Form.Item name="unit" label="Unit" rules={[{ required: true }]}>
                    <Select>
                      {purchaseUnits.map((u) => (
                        <Select.Option key={u.value} value={u.value}>
                          {u.label}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                {addSelectedUnit !== 'KG' && (
                  <Col xs={12} sm={8}>
                    <Form.Item
                      name="bags"
                      label={`Number of ${addSelectedUnit === 'BOX' ? 'Boxes' : (addSelectedUnit === 'THAAR' ? 'Thaar' : (addSelectedUnit === 'PIECES' ? 'Pieces' : 'Bags'))}`}
                      rules={[{ required: true, message: `Enter number of ${addSelectedUnit === 'BOX' ? 'boxes' : (addSelectedUnit === 'THAAR' ? 'thaar' : (addSelectedUnit === 'PIECES' ? 'pieces' : 'bags'))}` }]}
                    >
                      <InputNumber min={1} className="w-full" placeholder="e.g. 20" />
                    </Form.Item>
                  </Col>
                )}

                <Col xs={12} sm={8}>
                  <Form.Item
                    name="quantity"
                    label={<span className="font-bold text-emerald-800">Total Wt (KG) {addSelectedUnit !== 'KG' ? '(Optional)' : ''}</span>}
                    rules={[{ required: addSelectedUnit === 'KG', message: 'Total weight in KG is required for KG unit' }]}
                  >
                    <InputNumber
                      min={0.0}
                      step={0.1}
                      className="w-full font-bold text-base text-emerald-950"
                      placeholder="e.g. 1000"
                    />
                  </Form.Item>
                </Col>
              </Row>
            </div>

            {/* 3. DESPATCH & LOGISTICS INFO */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                3. Despatch & Logistics Information
              </span>
              <Row gutter={16}>
                <Col xs={24} sm={8}>
                  <Form.Item name="dateOfDespatch" label="Date of Despatch">
                    <DatePicker
                      className="w-full"
                      format="DD/MM/YYYY"
                      disabledDate={(current) => {
                        const arrivalDate = addForm.getFieldValue('arrivalDate');
                        return arrivalDate ? current && current.isAfter(arrivalDate, 'day') : false;
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="arrivalDate" label="Date of Arrival" rules={[{ required: true }]}>
                    <DatePicker className="w-full" format="DD/MM/YYYY" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="truckNo" label="Truck / Vehicle #">
                    <Input placeholder="e.g. TN-58-AB-1234" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item
                    name="supplierId"
                    label="Supplier"
                    rules={[
                      {
                        required: true,
                        message: "Please select a supplier",
                      },
                    ]}
                    extra={
                      selectedSupplier && selectedSupplier.outstandingBalance !== undefined && selectedSupplier.outstandingBalance !== null ? (
                        <div className={`text-xs mt-1 font-medium ${Number(selectedSupplier.outstandingBalance) > 0 ? 'text-red-500' : 'text-green-600'}`}>
                          Outstanding Balance: ₹{Number(selectedSupplier.outstandingBalance).toFixed(2)}
                        </div>
                      ) : null
                    }
                  >
                    <Select
                      showSearch
                      allowClear
                      placeholder="Select Supplier"
                      optionFilterProp="children"
                    >
                      {suppliers.map((s) => (
                        <Select.Option key={s.id} value={s.id}>
                          {s.name}
                        </Select.Option>
                      ))}
                    </Select>

                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="agentName" label="Or Agent Name (Free Text)">
                    <Input placeholder="Agent / Farmer Name" />
                  </Form.Item>
                </Col>
                {/* <Col xs={24} sm={8}>
                  <Form.Item name="advanceAmount" label="Advance Paid Upfront (₹)">
                    <InputNumber min={0} className="w-full" placeholder="₹ 0.00" />
                  </Form.Item>
                </Col> */}
                <Col xs={24} sm={12}>
                  <Form.Item name="placeOfDespatch" label="Place of Despatch">
                    <Input placeholder="e.g. Ottanchathiram" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item name="placeOfArrival" label="Place of Arrival">
                    <Input placeholder="e.g. Amman Stores" />
                  </Form.Item>
                </Col>
              </Row>
            </div>

            {/* 4. FREIGHT & LANDING CHARGES */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                4. Freight & Inward Landing Expenses
              </span>
              <Row gutter={16}>
                <Col xs={12} sm={8}>
                  <Form.Item name="freight" label="Freight (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="extraFreight" label="Extra Freight (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="associationFee" label="Association Fee (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="unloadingFee" label="Unloading / Coolie (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="miscellaneousFee" label="Misc Fee (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <div className="bg-emerald-100 p-3 rounded-lg border border-emerald-300 text-center">
                    <span className="text-xs font-semibold text-emerald-800 uppercase block">
                      Total Inward Freight
                    </span>
                    <span className="text-lg font-bold text-emerald-950 block mt-0.5">
                      ₹ {calculatedTotalFreight}
                    </span>
                  </div>
                </Col>
              </Row>
            </div>

            {/* 5. REMARKS */}
            <Form.Item name="remarks" label="Arrival Remarks" className="mb-4">
              <Input.TextArea rows={2} placeholder="Optional notes, truck condition, quality notes" />
            </Form.Item>

            {/* FOOTER ACTIONS */}
            <div className="flex justify-end gap-2 pt-3 border-t">
              <Button onClick={() => setAddModalVisible(false)}>Cancel</Button>
              <Button
                type="primary"
                htmlType="submit"
                icon={<PlusOutlined />}
                loading={addSaving}
                className="bg-emerald-600 hover:bg-emerald-500 font-semibold px-5"
                disabled={lotStatus.isAvailable === false}
              >
                Save Arrival Lot
              </Button>
            </div>
          </Form>
        </Modal>

        {/* VIEW DETAILS MODAL */}
        <Modal
          title={
            <div className="flex items-center justify-between pr-6 border-b pb-3">
              <span className="font-bold text-base text-gray-900">
                Lot {viewRecord?.lotNo} - {viewRecord?.vegetable?.name}
              </span>
              <Tag color={viewRecord?.status === 'ACTIVE' ? 'green' : 'red'}>
                {viewRecord?.status}
              </Tag>
            </div>
          }
          open={viewModalVisible}
          onCancel={() => setViewModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setViewModalVisible(false)}>
              Close
            </Button>
          ]}
          width={880}
          centered
          destroyOnHidden
        >
          {viewLoading ? (
            <div className="py-12 text-center">
              <Spin size="large" />
            </div>
          ) : viewRecord ? (
            <div className="space-y-4 pt-2">
              <Descriptions bordered size="small" column={{ xs: 1, sm: 2, md: 3 }}>
                <Descriptions.Item label="Vegetable Item">
                  <strong>{viewRecord.vegetable?.name}</strong> {viewRecord.vegetable?.tamilName ? `(${viewRecord.vegetable?.tamilName})` : ''}
                </Descriptions.Item>
                <Descriptions.Item label="Lot Number">
                  <Tag color="geekblue" className="font-bold">Lot {viewRecord.lotNo}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Supplier / Agent">
                  {viewRecord.supplier?.name || viewRecord.cashSupplierName || viewRecord.agentName || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Arrival Date">
                  {viewRecord.arrivalDate ? dayjs(viewRecord.arrivalDate).format('DD MMM YYYY') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Total Weight Inward">
                  {Number(viewRecord.quantity) === 0 && Number(viewRecord.bags) > 0
                    ? '-'
                    : `${Number(viewRecord.quantity).toFixed(2)} KG`}
                </Descriptions.Item>
                <Descriptions.Item label="Sacks / Bags">
                  {viewRecord.bags ? `${viewRecord.bags} ${viewRecord.unit || 'BAG'}` : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Stock Remaining">
                  {(() => {
                    const totalQty = Number(viewRecord.quantity || 0);
                    const totalBags = Number(viewRecord.bags || 0);

                    const wholesaleRemainingQty = Number(viewRecord.remainingQuantity || 0);
                    const retailRemainingQty = viewRecord.retailStocks?.reduce((acc: number, curr: any) => acc + Number(curr.remainingQuantity || 0), 0) || 0;
                    const remainingQty = wholesaleRemainingQty + retailRemainingQty;

                    const wholesaleRemainingBags = Number(viewRecord.remainingBags || 0);
                    const retailRemainingBags = viewRecord.retailStocks?.reduce((acc: number, curr: any) => acc + Number(curr.remainingBags || 0), 0) || 0;
                    const remainingBags = wholesaleRemainingBags + retailRemainingBags;

                    if (totalQty === 0 && totalBags > 0) {
                      return (
                        <Tag color={remainingBags <= 0 ? 'green' : 'orange'}>
                          {remainingBags} / {totalBags} {viewRecord.unit || 'BAG'}
                        </Tag>
                      );
                    }
                    return (
                      <Tag color={remainingQty <= 0 ? 'green' : 'orange'}>
                        {remainingQty.toFixed(2)} / {totalQty.toFixed(2)} KG
                      </Tag>
                    );
                  })()}
                </Descriptions.Item>
                <Descriptions.Item label="Truck Number">
                  {viewRecord.truckNo || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Place of Despatch">
                  {viewRecord.placeOfDespatch || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Total Freight Deduction">
                  ₹ {Number(viewRecord.totalFreight || 0).toFixed(2)}
                </Descriptions.Item>
                {/* <Descriptions.Item label="Advance Paid">
                  ₹ {Number(viewRecord.advanceAmount || 0).toFixed(2)}
                </Descriptions.Item> */}
                <Descriptions.Item label="Settlement Status">
                  {viewRecord.arrivalSettlement ? (
                    <Tag color="success">Patti #{viewRecord.arrivalSettlement.settlementNo}</Tag>
                  ) : (
                    <Tag color="warning">UNSETTLED</Tag>
                  )}
                </Descriptions.Item>
              </Descriptions>

              {/* SALES REALIZATION LIST */}
              <div>
                <Text strong className="text-sm block mb-2 text-gray-700">
                  Sales Realization Line Items ({viewRecord.saleItems?.length || 0} Bills)
                </Text>
                <Table
                  size="small"
                  columns={salesBreakdownColumns}
                  dataSource={viewRecord.saleItems || []}
                  rowKey="id"
                  scroll={{ y: 200, x: 'max-content' }}
                  pagination={
                    (viewRecord.saleItems?.length || 0) > 5
                      ? { pageSize: 5, size: 'small', showTotal: (tot) => `Total ${tot} bills` }
                      : false
                  }
                />
              </div>
            </div>
          ) : null}
        </Modal>

        {/* EDIT MODAL */}
        <Modal
          title={
            <div className="flex items-center justify-between pr-6 border-b pb-3">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 font-bold">
                  <EditOutlined />
                </div>
                <div>
                  <h3 className="text-base font-bold text-gray-900 leading-tight m-0">
                    Edit Commission Arrival Consignment
                  </h3>
                  <span className="text-xs text-gray-500 font-normal">
                    Update inward stock lot with logistics and freight charges
                  </span>
                </div>
              </div>
            </div>
          }
          open={editModalVisible}
          onCancel={() => setEditModalVisible(false)}
          footer={null}
          width={860}
          centered
          destroyOnHidden
          styles={{
            body: {
              maxHeight: 'calc(85vh - 90px)',
              overflowY: 'auto',
              padding: '16px 20px',
            },
          }}
        >
          <Form
            form={editForm}
            layout="vertical"
            onFinish={handleEditSubmit}
          >
            {/* 1. ITEM & LOT IDENTIFICATION */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                1. Item & Lot Identification
              </span>
              <Row gutter={16}>
                <Col xs={24} sm={10}>
                  <Form.Item
                    name="vegetableId"
                    label="Vegetable Item"
                    rules={[{ required: true, message: 'Please select a vegetable!' }]}
                  >
                    <Select
                      showSearch
                      disabled
                      placeholder="Select vegetable"
                      optionFilterProp="children"
                    >
                      {vegetables.map((v) => (
                        <Select.Option key={v.id} value={v.id}>
                          {v.name}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                <Col xs={24} sm={8}>
                  <Form.Item
                    name="lotNo"
                    label="Lot Number (e.g. 1, 2, 3)"
                    rules={[{ required: true, message: 'Please enter lot number!' }]}
                  >
                    <Input disabled placeholder="e.g. 1" />
                  </Form.Item>
                </Col>

                <Col xs={24} sm={6}>
                  <Form.Item name="billNo" label="Consignment / Bill #">
                    <Input placeholder="Optional Bill #" />
                  </Form.Item>
                </Col>
              </Row>
            </div>

            {/* 2. SACKS & WEIGHT DETAILS */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                2. Weight & Packaging Details
              </span>
              <Row gutter={16}>
                <Col xs={12} sm={8}>
                  <Form.Item name="unit" label="Unit" rules={[{ required: true }]}>
                    <Select disabled>
                      {purchaseUnits.map((u) => (
                        <Select.Option key={u.value} value={u.value}>
                          {u.label}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>

                {editSelectedUnit !== 'KG' && (
                  <Col xs={12} sm={8}>
                    <Form.Item
                      name="bags"
                      label={`Number of ${editSelectedUnit === 'BOX' ? 'Boxes' : (editSelectedUnit === 'THAAR' ? 'Thaar' : (editSelectedUnit === 'PIECES' ? 'Pieces' : 'Bags'))}`}
                      rules={[{ required: true, message: `Enter number of ${editSelectedUnit === 'BOX' ? 'boxes' : (editSelectedUnit === 'THAAR' ? 'thaar' : (editSelectedUnit === 'PIECES' ? 'pieces' : 'bags'))}` }]}
                    >
                      <InputNumber min={1} className="w-full" placeholder="e.g. 20" />
                    </Form.Item>
                  </Col>
                )}

                <Col xs={12} sm={8}>
                  <Form.Item
                    name="quantity"
                    label={<span className="font-bold text-blue-800">Total Wt (KG) {editSelectedUnit !== 'KG' ? '(Optional)' : ''}</span>}
                    rules={[{ required: editSelectedUnit === 'KG', message: 'Total weight in KG is required for KG unit' }]}
                  >
                    <InputNumber
                      min={0.0}
                      step={0.1}
                      className="w-full font-bold text-base text-blue-950"
                      placeholder="e.g. 1000"
                    />
                  </Form.Item>
                </Col>
              </Row>
            </div>

            {/* 3. DESPATCH & LOGISTICS INFO */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                3. Despatch & Logistics Information
              </span>
              <Row gutter={16}>
                <Col xs={24} sm={8}>
                  <Form.Item name="dateOfDespatch" label="Date of Despatch">
                    <DatePicker
                      className="w-full"
                      format="DD/MM/YYYY"
                      disabledDate={(current) => {
                        const arrivalDate = editForm.getFieldValue('arrivalDate');
                        return arrivalDate ? current && current.isAfter(arrivalDate, 'day') : false;
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="arrivalDate" label="Date of Arrival" rules={[{ required: true }]}>
                    <DatePicker className="w-full" format="DD/MM/YYYY" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="truckNo" label="Truck / Vehicle #">
                    <Input placeholder="e.g. TN-58-AB-1234" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item
                    name="supplierId"
                    label="Supplier"
                    rules={[
                      {
                        required: true,
                        message: "Please select a supplier",
                      },
                    ]}
                    extra={
                      editSelectedSupplier && editSelectedSupplier.outstandingBalance !== undefined && editSelectedSupplier.outstandingBalance !== null ? (
                        <div className={`text-xs mt-1 font-medium ${Number(editSelectedSupplier.outstandingBalance) > 0 ? 'text-red-500' : 'text-green-600'}`}>
                          Outstanding Balance: ₹{Number(editSelectedSupplier.outstandingBalance).toFixed(2)}
                        </div>
                      ) : null
                    }
                  >
                    <Select
                      disabled
                      showSearch
                      allowClear
                      placeholder="Select Supplier"
                      optionFilterProp="children"
                    >
                      {suppliers.map((s) => (
                        <Select.Option key={s.id} value={s.id}>
                          {s.name}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <Form.Item name="agentName" label="Or Agent Name (Free Text)">
                    <Input placeholder="Agent / Farmer Name" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item name="placeOfDespatch" label="Place of Despatch">
                    <Input placeholder="e.g. Ottanchathiram" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item name="placeOfArrival" label="Place of Arrival">
                    <Input placeholder="e.g. Amman Stores" />
                  </Form.Item>
                </Col>
              </Row>
            </div>

            {/* 4. FREIGHT & LANDING CHARGES */}
            <div className="bg-gray-50/80 border border-gray-200 rounded-xl p-4 mb-4 shadow-sm">
              <span className="text-xs font-bold text-gray-600 uppercase tracking-wider block mb-3">
                4. Freight & Inward Landing Expenses
              </span>
              <Row gutter={16}>
                <Col xs={12} sm={8}>
                  <Form.Item name="freight" label="Freight (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="extraFreight" label="Extra Freight (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="associationFee" label="Association Fee (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="unloadingFee" label="Unloading / Coolie (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={12} sm={8}>
                  <Form.Item name="miscellaneousFee" label="Misc Fee (₹)">
                    <InputNumber min={0} className="w-full" placeholder="0.00" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={8}>
                  <div className="bg-blue-100 p-3 rounded-lg border border-blue-300 text-center">
                    <span className="text-xs font-semibold text-blue-800 uppercase block">
                      Total Inward Freight
                    </span>
                    <span className="text-lg font-bold text-blue-950 block mt-0.5">
                      ₹ {editCalculatedTotalFreight}
                    </span>
                  </div>
                </Col>
              </Row>
            </div>

            {/* 5. REMARKS */}
            <Form.Item name="remarks" label="Arrival Remarks" className="mb-4">
              <Input.TextArea rows={2} placeholder="Optional notes, truck condition, quality notes" />
            </Form.Item>

            {/* FOOTER ACTIONS */}
            <div className="flex justify-end gap-2 pt-3 border-t">
              <Button onClick={() => setEditModalVisible(false)}>Cancel</Button>
              <Button
                type="primary"
                htmlType="submit"
                icon={<EditOutlined />}
                loading={editSaving}
                className="bg-blue-600 hover:bg-blue-500 font-semibold px-5"
              >
                Update Arrival Lot
              </Button>
            </div>
          </Form>
        </Modal>

        {/* SETTLE 4% COMMISSION PATTI MODAL */}
        <Modal
          title={
            <div className="flex items-center justify-between pr-6 border-b pb-3">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-700 font-bold text-base">
                  ₹
                </div>
                <div>
                  <h3 className="text-base font-bold text-gray-900 leading-tight m-0">
                    Generate Commission Patti Settlement
                  </h3>
                  <span className="text-xs text-gray-500 font-normal">
                    Real-time sales realization, deductions & commission calculation
                  </span>
                </div>
              </div>
              {settlePreviewData?.arrival?.lotNo && (
                <Tag color="geekblue" className="text-sm font-bold px-3 py-1 rounded-full m-0">
                  Lot {settlePreviewData.arrival.lotNo}
                </Tag>
              )}
            </div>
          }
          open={settleModalVisible}
          onCancel={() => setSettleModalVisible(false)}
          footer={null}
          width={920}
          centered
          destroyOnHidden
          styles={{
            body: {
              maxHeight: 'calc(85vh - 90px)',
              overflowY: 'auto',
              padding: '16px 20px',
            },
          }}
        >
          {settlePreviewLoading ? (
            <div className="py-16 text-center">
              <Spin size="large" />
              <div className="mt-3 text-gray-600 font-medium">Calculating real-time sales & expenses...</div>
            </div>
          ) : settlePreviewData ? (
            <Form form={settleForm} layout="vertical" onFinish={handleCreateSettlement}>
              {/* LOT OVERVIEW STATS */}
              <div className="bg-linear-gradient-to-r from-emerald-50/80 to-teal-50/50 border border-emerald-200/80 rounded-xl p-4 mb-4 shadow-sm">
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  <div>
                    <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Vegetable Item</span>
                    <span className="text-base font-bold text-gray-900 block mt-0.5">
                      {settlePreviewData.arrival?.vegetable?.name || '—'}
                    </span>
                    {(settlePreviewData.arrival?.supplier?.name || settlePreviewData.arrival?.cashSupplierName || settlePreviewData.arrival?.agentName) && (
                      <span className="text-xs text-emerald-800 font-medium truncate block mt-0.5">
                        {settlePreviewData.arrival?.supplier?.name || settlePreviewData.arrival?.cashSupplierName || settlePreviewData.arrival?.agentName}
                      </span>
                    )}
                  </div>
                  <div>
                    <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Inward Quantity</span>
                    <span className="text-base font-bold text-gray-900 block mt-0.5">
                      {Number(settlePreviewData.calculations?.totalWeightReceived || 0).toFixed(2)} KG
                    </span>
                    {settlePreviewData.arrival?.bags && Number(settlePreviewData.arrival.bags) > 0 && (
                      <span className="text-xs text-gray-500 block">({Number(settlePreviewData.arrival.bags)} Bags)</span>
                    )}
                  </div>
                  <div>
                    <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Total Sold</span>
                    <span className="text-base font-bold text-emerald-700 block mt-0.5">
                      {Number(settlePreviewData.calculations?.totalWeightSold || 0).toFixed(2)} KG
                    </span>
                    {Number(settlePreviewData.calculations?.retailWeightSold || 0) > 0 ? (
                      <span className="text-[11px] text-gray-500 block">
                        WS: {Number(settlePreviewData.calculations?.wholesaleWeightSold || 0).toFixed(1)} KG | Ret: {Number(settlePreviewData.calculations?.retailWeightSold || 0).toFixed(1)} KG
                      </span>
                    ) : (
                      <span className="text-xs text-gray-500 block">100% Wholesale</span>
                    )}
                  </div>
                  <div>
                    <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Remaining Stock</span>
                    <div className="mt-1">
                      <Tag
                        color={Number(settlePreviewData.calculations?.remainingQuantity || 0) <= 0 ? 'green' : 'orange'}
                        className="font-bold text-xs px-2 py-0.5"
                      >
                        {Number(settlePreviewData.calculations?.remainingQuantity || 0).toFixed(2)} KG
                        {Number(settlePreviewData.calculations?.remainingQuantity || 0) <= 0 ? ' (Depleted)' : ' Active'}
                      </Tag>
                    </div>
                  </div>
                </div>
              </div>

              {/* SALES REALIZATION LINE ITEMS TABLE */}
              <div className="mb-4 bg-white border border-gray-200 rounded-xl p-3.5 shadow-sm">
                <div className="flex items-center justify-between mb-2.5">
                  <div className="flex items-center gap-2">
                    <span className="font-bold text-sm text-gray-800">Sales Realization Line Items</span>
                    <Tag color="cyan" className="rounded-full px-2 text-xs font-semibold">
                      {settlePreviewData.salesSummary?.saleItems?.length || 0} Invoices
                    </Tag>
                  </div>
                  <span className="text-xs text-gray-600">
                    Gross Realized: <strong className="text-emerald-800 text-sm">₹ {Number(settlePreviewData.calculations?.grossSalesTotal || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</strong>
                  </span>
                </div>
                <Table
                  size="small"
                  columns={salesBreakdownColumns}
                  dataSource={settlePreviewData.salesSummary?.saleItems || []}
                  rowKey="id"
                  scroll={{ y: 180, x: 'max-content' }}
                  pagination={
                    (settlePreviewData.salesSummary?.saleItems?.length || 0) > 5
                      ? { pageSize: 5, size: 'small', showTotal: (tot) => `Total ${tot} bills` }
                      : false
                  }
                />
              </div>

              {/* DEDUCTIONS & COMMISSION CALCULATION BOX */}
              <Card size="small" className="bg-gray-50/80 mb-4 border border-gray-200 rounded-xl shadow-sm">
                <Row gutter={16}>
                  <Col xs={24} md={12}>
                    <div className="space-y-2 text-sm pr-2">
                      <div className="flex justify-between py-1 border-b border-gray-200/60 font-semibold text-gray-800">
                        <span>Gross Sales Total:</span>
                        <span>₹ {Number(settlePreviewData.calculations?.grossSalesTotal || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
                      </div>
                      <div className="flex justify-between items-center text-red-600">
                        <span className="flex items-center gap-1.5 font-medium">
                          Commission (
                          <InputNumber
                            size="small"
                            min={0}
                            max={100}
                            step={0.5}
                            value={commissionRate}
                            disabled={Boolean(settlePreviewData?.arrival?.arrivalSettlement)}
                            style={{ width: 62 }}
                            className="font-semibold text-center"
                            onChange={(val) => handleCommissionChange(val !== null && val !== undefined ? Number(val) : 0)}
                          />
                          %):
                          {settlePreviewData?.arrival?.arrivalSettlement && (
                            <Tag color="default" className="text-[10px] px-1 py-0 m-0 leading-tight">
                              Locked
                            </Tag>
                          )}
                        </span>
                        <span className="font-semibold">- ₹ {Number(settlePreviewData.calculations?.commissionAmount || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Freight:</span>
                        <span>- ₹ {Number(settlePreviewData.calculations?.freightDeducted || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Unloading / Coolie:</span>
                        <span>- ₹ {Number(settlePreviewData.calculations?.unloadingDeducted || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Association Fee:</span>
                        <span>- ₹ {Number(settlePreviewData.calculations?.associationDeducted || 0).toFixed(2)}</span>
                      </div>
                      {Number(settlePreviewData.calculations?.extraFreightDeducted || 0) > 0 && (
                        <div className="flex justify-between text-red-600">
                          <span>Extra Freight:</span>
                          <span>- ₹ {Number(settlePreviewData.calculations?.extraFreightDeducted || 0).toFixed(2)}</span>
                        </div>
                      )}
                      {Number(settlePreviewData.calculations?.miscDeducted || 0) > 0 && (
                        <div className="flex justify-between text-red-600">
                          <span>Misc Fee:</span>
                          <span>- ₹ {Number(settlePreviewData.calculations?.miscDeducted || 0).toFixed(2)}</span>
                        </div>
                      )}
                      {Number(settlePreviewData.calculations?.advanceAdjusted || 0) > 0 && (
                        <div className="flex justify-between text-red-600">
                          <span>Advance Paid Upfront:</span>
                          <span>- ₹ {Number(settlePreviewData.calculations?.advanceAdjusted || 0).toFixed(2)}</span>
                        </div>
                      )}
                      <div className="flex justify-between pt-1 border-t border-gray-200 font-semibold text-gray-700 text-xs">
                        <span>Total Deductions:</span>
                        <span>- ₹ {Number(settlePreviewData.calculations?.totalDeductions || 0).toFixed(2)}</span>
                      </div>
                    </div>
                  </Col>

                  <Col xs={24} md={12} className="mt-3 md:mt-0 md:border-l md:pl-4 flex flex-col justify-center">
                    <div className="bg-linear-to-br from-emerald-100 to-teal-50 p-5 rounded-xl text-center border border-emerald-300 shadow-sm">
                      <Text type="secondary" className="text-xs uppercase font-bold text-emerald-800 tracking-wider">
                        Net Amount Payable
                      </Text>
                      <div className="text-3xl font-extrabold text-emerald-950 mt-1.5 tracking-tight">
                        ₹ {Number(settlePreviewData.calculations?.netPayable || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                      </div>
                    </div>
                  </Col>
                </Row>
              </Card>

              {/* PAYMENT HANDOVER FIELDS */}
              <div className="bg-white border border-gray-200 rounded-xl p-3.5 mb-4 shadow-sm">
                <Row gutter={16}>
                  <Col xs={24} sm={8}>
                    <Form.Item name="settlementDate" label="Settlement Date" rules={[{ required: true }]}>
                      <DatePicker className="w-full" format="DD/MM/YYYY" disabled={Boolean(settlePreviewData?.arrival?.arrivalSettlement)} />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={8}>
                    <Form.Item name="paidAmount" label="Handover Amount Paid (₹)" rules={[{ required: true }]}>
                      <InputNumber className="w-full font-bold text-base text-emerald-900" disabled={true} />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={8}>
                    <Form.Item name="paymentMode" label="Payment Mode" rules={[{ required: true, message: 'Please select payment mode' }]}>
                      <Select placeholder="Select payment mode" options={paymentModes} disabled={Boolean(settlePreviewData?.arrival?.arrivalSettlement)} />
                    </Form.Item>
                  </Col>
                </Row>

                <Form.Item name="remarks" label="Settlement Remarks" className="mb-0">
                  <Input.TextArea rows={2} placeholder="Optional notes or transaction reference numbers" disabled={Boolean(settlePreviewData?.arrival?.arrivalSettlement)} />
                </Form.Item>
              </div>

              {/* FOOTER ACTIONS */}
              <div className="flex items-center justify-between pt-2 border-t">
                {settlePreviewData?.arrival?.arrivalSettlement ? (
                  <div className="text-xs text-amber-700 bg-amber-50 px-2.5 py-1 rounded border border-amber-200 flex items-center gap-1.5 font-medium">
                    <LockOutlined /> Patti Settlement Confirmed & Locked (View Only)
                  </div>
                ) : (
                  <div />
                )}
                <div className="flex items-center gap-2">
                  <Button onClick={() => setSettleModalVisible(false)}>
                    {settlePreviewData?.arrival?.arrivalSettlement ? 'Close' : 'Cancel'}
                  </Button>
                  {!settlePreviewData?.arrival?.arrivalSettlement && (
                    <Button
                      type="primary"
                      htmlType="submit"
                      icon={<CheckCircleOutlined />}
                      loading={settleSubmitting}
                      className="bg-emerald-600 hover:bg-emerald-500 font-semibold px-5"
                    >
                      Confirm & Generate P.Patti
                    </Button>
                  )}
                </div>
              </div>
            </Form>
          ) : null}
        </Modal>

        {/* CUSTOM / MODIFIED PATTI MODAL */}
        <CustomPattiModal
          open={customPattiVisible}
          onClose={() => setCustomPattiVisible(false)}
          purchaseId={customPattiPurchaseId}
          lotNo={customPattiLotNo}
          onSuccess={() => fetchArrivals(currentPage, pageSize)}
        />
      </Spin>
    </div>
  );
};

export default ArrivalLotHistory;
