import React, { useEffect, useState, useCallback } from 'react';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  Form,
  Input,
  InputNumber,
  Modal,
  Popover,
  Row,
  Select,
  Space,
  Spin,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import {
  PrinterOutlined,
  PlusOutlined,
  HistoryOutlined,
  CheckCircleOutlined,
  EyeOutlined,
  FormOutlined,
  LockOutlined,
} from '@ant-design/icons';
import { useSearchParams, useNavigate } 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 = 'Patti Settlements';

interface SettlementRecord {
  id: string;
  settlementNo: string;
  settlementDate: string;
  totalWeightSold: string;
  grossSalesTotal: string;
  commissionPercent: string;
  commissionAmount: string;
  freightDeducted?: string;
  extraFreightDeducted?: string;
  unloadingDeducted?: string;
  associationDeducted?: string;
  miscDeducted?: string;
  totalDeductions: string;
  advanceAdjusted: string;
  netPayable: string;
  paidAmount: string;
  balanceAmount: string;
  status: 'UNSETTLED' | 'PARTIALLY_SETTLED' | 'SETTLED';
  paymentMode?: string;
  remarks?: string;
  purchase?: {
    id: string;
    lotNo: string;
    quantity: string;
    bags?: string;
    arrivalDate: string;
    truckNo?: string;
    agentName?: string;
    vegetable?: { name: string; tamilName?: string };
    supplier?: { name: string; mobileNo?: string };
    cashSupplierName?: string;
  };
}

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

  const [settlements, setSettlements] = useState<SettlementRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: Number(import.meta.env.VITE_PAGE_SIZE) || 10,
    total: 0,
    totalPages: 0,
  });

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

  // Settlement Generator Modal State
  const [modalVisible, setModalVisible] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [selectedPurchaseId, setSelectedPurchaseId] = useState<string | null>(null);
  const [previewData, setPreviewData] = useState<any>(null);
  const [commissionRate, setCommissionRate] = useState<number>(8.0);
  const [paymentModes, setPaymentModes] = useState<{ label: string; value: string }[]>([]);

  // View Details Modal State
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [viewRecord, setViewRecord] = useState<SettlementRecord | null>(null);

  // Custom / Modified Patti Modal State
  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);
  };

  const [settleForm] = Form.useForm();

  // Status color mapper
  const statusColor = (status: string) => {
    switch (status) {
      case 'SETTLED':
        return 'green';
      case 'PARTIALLY_SETTLED':
        return 'orange';
      case 'UNSETTLED':
        return 'red';
      default:
        return 'default';
    }
  };

  // Fetch Settlements List
  const fetchSettlements = useCallback(
    async (
      page = pagination.current,
      limit = pagination.pageSize,
      search = searchText,
      dates = dateRange,
      status = statusFilter
    ) => {
      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 (status) {
          params.status = status;
        }

        const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_SETTLEMENTS, { params });
        const records = res.data?.data || [];
        const meta = res.data?.meta || {};
        const total = meta.total ?? 0;

        setSettlements(records);
        setPagination((prev) => ({
          ...prev,
          current: meta.page ?? page,
          pageSize: meta.limit ?? limit,
          total: total,
          totalPages: meta.totalPages ?? Math.ceil(total / limit),
        }));
      } catch (err: any) {
        message.error(err?.response?.data?.message || 'Failed to load settlements.');
        setSettlements([]);
      } finally {
        setLoading(false);
      }
    },
    [pagination.current, pagination.pageSize, searchText, dateRange, statusFilter]
  );

  const fetchPaymentModes = async () => {
    try {
      const res = await jwtAxios.get(ENDPOINTS.PAYMENTMODES);
      const modes = res.data?.PaymentMode || {};
      setPaymentModes(
        Object.entries(modes).map(([key, value]) => ({
          label: key,
          value: String(value),
        }))
      );
    } catch (err: any) {
      console.error('Failed to fetch payment modes', err);
    }
  };

  useEffect(() => {
    fetchSettlements(1, pagination.pageSize, '');
    fetchPaymentModes();
  }, []);

  const handleSearch = (val: string) => {
    setSearchText(val);
    fetchSettlements(1, pagination.pageSize, val, dateRange, statusFilter);
  };

  const handleDateChange = (dates: any) => {
    setDateRange(dates);
    fetchSettlements(1, pagination.pageSize, searchText, dates, statusFilter);
  };


  // Close Settle Modal and ensure URL is clean
  const closeSettleModal = () => {
    setModalVisible(false);
    setSelectedPurchaseId(null);
    setPreviewData(null);
    if (searchParams.get('purchaseId')) {
      navigate('/arrivals/settlements', { replace: true });
    }
  };

  // Open Settle Modal and fetch preview
  const openSettleModal = async (purchaseId: string) => {
    setSelectedPurchaseId(purchaseId);
    setModalVisible(true);
    setPreviewLoading(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);
      }
      setPreviewData(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.');
      closeSettleModal();
    } finally {
      setPreviewLoading(false);
    }
  };

  // If purchaseId came in query params, open modal ONCE and immediately clear URL
  useEffect(() => {
    const pId = searchParams.get('purchaseId');
    if (pId) {
      openSettleModal(pId);
      navigate('/arrivals/settlements', { replace: true });
    }
  }, []);

  // 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 (previewData?.calculations) {
      const gross = Number(previewData.calculations.grossSalesTotal || 0);
      const commAmt = Math.round(((gross * numRate) / 100) * 100) / 100;
      const totalDed = Number(previewData.calculations.totalDeductions || 0);
      const adv = Number(previewData.calculations.advanceAdjusted || 0);
      const net = Math.round((gross - commAmt - totalDed - adv) * 100) / 100;

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

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

  // Submit Settlement
  const handleCreateSettlement = async (values: any) => {
    if (!selectedPurchaseId) return;
    setSubmitting(true);
    try {
      const payload = {
        purchaseId: Number(selectedPurchaseId),
        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!');
      closeSettleModal();
      fetchSettlements(1, pagination.pageSize);
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to create settlement.');
    } finally {
      setSubmitting(false);
    }
  };

  // Download PDF
  const downloadPdf = async (id: string, settlementNo: string) => {
    try {
      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_SETTLEMENT_PDF(id), {
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `Patti-${settlementNo}.pdf`);
      document.body.appendChild(link);
      link.click();
      link.remove();
    } catch (err: any) {
      message.error('Failed to download Patti PDF.');
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: 'Patti No',
      dataIndex: 'settlementNo',
      key: 'settlementNo',
      width: 150,
      render: (no: string) => <Tag color="blue" className="font-semibold">{no}</Tag>,
    },
    {
      title: 'Date',
      dataIndex: 'settlementDate',
      key: 'settlementDate',
      width: 120,
      render: (d: string) => (d ? dayjs(d).format('DD MMM YYYY') : '-'),
    },
    {
      title: 'Item & Lot',
      key: 'itemLot',
      width: 180,
      render: (_: any, r: SettlementRecord) => (
        <div>
          <span className="font-semibold text-gray-800">{r.purchase?.vegetable?.name || '-'}</span>
          <Tag color="cyan" className="ml-1.5 font-bold">Lot {r.purchase?.lotNo}</Tag>
        </div>
      ),
    },
    {
      title: 'Supplier',
      key: 'supplier',
      width: 160,
      render: (_: any, r: SettlementRecord) =>
        r.purchase?.supplier?.name || r.purchase?.cashSupplierName || r.purchase?.agentName || '-',
    },
    {
      title: 'Sold Qty',
      dataIndex: 'totalWeightSold',
      key: 'totalWeightSold',
      width: 120,
      render: (v: string) => `${Number(v || 0).toFixed(2)} KG`,
    },
    {
      title: 'Gross Sales (₹)',
      dataIndex: 'grossSalesTotal',
      key: 'grossSalesTotal',
      width: 130,
      render: (v: string) => Number(v || 0).toFixed(2),
    },
    {
      title: 'Commission (₹)',
      key: 'commission',
      width: 150,
      render: (_: any, r: SettlementRecord) => (
        <span className="text-emerald-700 font-semibold">
          {Number(r.commissionAmount || 0).toFixed(2)}
          <span className="text-xs text-gray-400 font-normal ml-1">({r.commissionPercent}%)</span>
        </span>
      ),
    },
    {
      title: 'Deductions (₹)',
      dataIndex: 'totalDeductions',
      key: 'totalDeductions',
      width: 130,
      render: (v: string) => Number(v || 0).toFixed(2),
    },
    {
      title: 'Net Payable (₹)',
      dataIndex: 'netPayable',
      key: 'netPayable',
      width: 200,
      render: (v: string) => (
        <span className="font-bold text-emerald-900">
          {Number(v || 0).toFixed(2)}
        </span>
      ),
    },
    {
      title: 'Paid (₹)',
      dataIndex: 'paidAmount',
      key: 'paidAmount',
      width: 120,
      render: (v: string) => Number(v || 0).toFixed(2),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      render: (status: string) => <Tag color={statusColor(status)}>{status}</Tag>,
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right' as const,
      width: 110,
      render: (_: any, r: SettlementRecord) => (
        <Space size="small">
          <Popover content="View Details">
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={() => {
                setViewRecord(r);
                setViewModalVisible(true);
              }}
            />
          </Popover>
          <Popover content="Print Patti Slip PDF">
            <Button
              type="link"
              icon={<PrinterOutlined style={{ color: '#0F5132' }} />}
              onClick={() => downloadPdf(r.id, r.settlementNo)}
            />
          </Popover>
          <Popover content="Custom / Modified Patti (For Sending to Others)">
            <Button
              type="link"
              icon={<FormOutlined style={{ color: '#722ed1', fontSize: 16 }} />}
              onClick={() => openCustomPattiModal(r.purchase?.id || '', r.purchase?.lotNo)}
            />
          </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
                icon={<HistoryOutlined />}
                onClick={() => navigate('/arrivals/lot-history')}
              >
                Arrival Lot History
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => navigate('/arrivals/lot-history?action=add')}
                className="bg-green-600"
              >
                Add Arrival
              </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={statusFilter}
                onChange={handleStatusFilterChange}
                onClear={() => handleStatusFilterChange(undefined)}
                options={[
                  { label: 'Settled', value: 'SETTLED' },
                  { label: 'Partially Settled', value: 'PARTIALLY_SETTLED' },
                  { label: 'Unsettled', value: 'UNSETTLED' },
                ]}
              /> */}

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

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

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

          {/* Table Section */}
          <Table
            rowKey="id"
            columns={columns}
            dataSource={settlements}
            loading={loading}
            scroll={{ x: 'max-content', y: 400 }}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showTotal: (total) => `Total ${total} items`,
              onChange: (page, pSize) => {
                fetchSettlements(page, pSize, searchText, dateRange, statusFilter);
              },
            }}
          />
        </AppContainer>

        {/* 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">
                Patti Settlement Details - {viewRecord?.settlementNo}
              </span>
              {viewRecord?.status && (
                <Tag color={statusColor(viewRecord.status)} className="font-semibold">
                  {viewRecord.status}
                </Tag>
              )}
            </div>
          }
          open={viewModalVisible}
          onCancel={() => setViewModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setViewModalVisible(false)}>
              Close
            </Button>,
            <Button
              key="print"
              type="primary"
              icon={<PrinterOutlined />}
              className="bg-emerald-600"
              onClick={() => viewRecord && downloadPdf(viewRecord.id, viewRecord.settlementNo)}
            >
              Print Patti PDF
            </Button>,
          ]}
          width={800}
          centered
          destroyOnHidden
        >
          {viewRecord && (
            <div className="space-y-4 pt-2">
              <Descriptions bordered size="small" column={{ xs: 1, sm: 2, md: 3 }}>
                <Descriptions.Item label="Patti No">
                  <Tag color="blue" className="font-bold">{viewRecord.settlementNo}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Settlement Date">
                  {viewRecord.settlementDate ? dayjs(viewRecord.settlementDate).format('DD MMM YYYY') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Item & Lot">
                  <strong>{viewRecord.purchase?.vegetable?.name}</strong> (Lot {viewRecord.purchase?.lotNo})
                </Descriptions.Item>
                <Descriptions.Item label="Supplier">
                  {viewRecord.purchase?.supplier?.name || viewRecord.purchase?.cashSupplierName || viewRecord.purchase?.agentName || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Total Sold Qty">
                  <strong>{Number(viewRecord.totalWeightSold || 0).toFixed(2)} KG</strong>
                </Descriptions.Item>
                <Descriptions.Item label="Gross Sales Total">
                  <strong>₹ {Number(viewRecord.grossSalesTotal || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</strong>
                </Descriptions.Item>
                <Descriptions.Item label="Commission">
                  <span className="text-red-600 font-semibold">
                    - ₹ {Number(viewRecord.commissionAmount || 0).toFixed(2)} ({viewRecord.commissionPercent}%)
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Freight">
                  <span className="text-red-600 font-semibold">
                    - ₹ {Number(viewRecord.freightDeducted || 0).toFixed(2)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Extra Freight">
                  <span className="text-red-600 font-semibold">
                    - ₹ {Number(viewRecord.extraFreightDeducted || 0).toFixed(2)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Unloading / Coolie">
                  <span className="text-red-600 font-semibold">
                    - ₹ {Number(viewRecord.unloadingDeducted || 0).toFixed(2)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Association Fee">
                  <span className="text-red-600 font-semibold">
                    - ₹ {Number(viewRecord.associationDeducted || 0).toFixed(2)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Other Charges">
                  <span className="text-red-600 font-semibold">
                    - ₹ {Number(viewRecord.miscDeducted || 0).toFixed(2)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Total Deductions">
                  <span className="text-red-600 font-bold">
                    - ₹ {Number(viewRecord.totalDeductions || 0).toFixed(2)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Net Payable">
                  <span className="text-emerald-800 font-bold text-base">
                    ₹ {Number(viewRecord.netPayable || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Paid Amount">
                  <span className="font-bold">
                    ₹ {Number(viewRecord.paidAmount || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Balance Amount">
                  <span className="font-semibold text-orange-600">
                    ₹ {Number(viewRecord.balanceAmount || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="Payment Mode">
                  <Tag color="cyan">{viewRecord.paymentMode || 'CASH'}</Tag>
                </Descriptions.Item>
                {viewRecord.remarks && (
                  <Descriptions.Item label="Remarks" span={3}>
                    {viewRecord.remarks}
                  </Descriptions.Item>
                )}
              </Descriptions>
            </div>
          )}
        </Modal>

        {/* GENERATE SETTLEMENT 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>
              {previewData?.arrival?.lotNo && (
                <Tag color="geekblue" className="text-sm font-bold px-3 py-1 rounded-full m-0">
                  Lot {previewData.arrival.lotNo}
                </Tag>
              )}
            </div>
          }
          open={modalVisible}
          onCancel={closeSettleModal}
          footer={null}
          width={920}
          centered
          destroyOnHidden
          styles={{
            body: {
              maxHeight: 'calc(85vh - 90px)',
              overflowY: 'auto',
              padding: '16px 20px',
            },
          }}
        >
          {previewLoading ? (
            <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>
          ) : previewData ? (
            <Form form={settleForm} layout="vertical" onFinish={handleCreateSettlement}>
              {/* LOT OVERVIEW STATS */}
              <div className="bg-linear-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">
                      {previewData.arrival?.vegetable?.name || '—'}
                    </span>
                    {(previewData.arrival?.supplier?.name || previewData.arrival?.cashSupplierName || previewData.arrival?.agentName) && (
                      <span className="text-xs text-emerald-800 font-medium truncate block mt-0.5">
                        {previewData.arrival?.supplier?.name || previewData.arrival?.cashSupplierName || previewData.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(previewData.calculations?.totalWeightReceived || 0).toFixed(2)} KG
                    </span>
                    {previewData.arrival?.bags && Number(previewData.arrival.bags) > 0 && (
                      <span className="text-xs text-gray-500 block">({Number(previewData.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(previewData.calculations?.totalWeightSold || 0).toFixed(2)} KG
                    </span>
                    {Number(previewData.calculations?.retailWeightSold || 0) > 0 ? (
                      <span className="text-[11px] text-gray-500 block">
                        WS: {Number(previewData.calculations?.wholesaleWeightSold || 0).toFixed(1)} KG | Ret: {Number(previewData.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(previewData.calculations?.remainingQuantity || 0) <= 0 ? 'green' : 'orange'}
                        className="font-bold text-xs px-2 py-0.5"
                      >
                        {Number(previewData.calculations?.remainingQuantity || 0).toFixed(2)} KG
                        {Number(previewData.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">
                      {previewData.salesSummary?.saleItems?.length || 0} Invoices
                    </Tag>
                  </div>
                  <span className="text-xs text-gray-600">
                    Gross Realized: <strong className="text-emerald-800 text-sm">₹ {Number(previewData.calculations?.grossSalesTotal || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</strong>
                  </span>
                </div>
                <Table
                  size="small"
                  columns={salesBreakdownColumns}
                  dataSource={previewData.salesSummary?.saleItems || []}
                  rowKey="id"
                  scroll={{ y: 180, x: 'max-content' }}
                  pagination={
                    (previewData.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(previewData.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">
                          Commission (
                          <InputNumber
                            size="small"
                            min={0}
                            max={100}
                            step={0.5}
                            value={commissionRate}
                            disabled={Boolean(previewData?.arrival?.arrivalSettlement)}
                            style={{ width: 62 }}
                            className="font-semibold text-center"
                            onChange={(val) => handleCommissionChange(val !== null && val !== undefined ? Number(val) : 0)}
                          />
                          %):
                          {previewData?.arrival?.arrivalSettlement && (
                            <Tag color="default" className="text-[10px] px-1 py-0 m-0 leading-tight">
                              Locked
                            </Tag>
                          )}
                        </span>
                        <span className="font-semibold">- ₹ {Number(previewData.calculations?.commissionAmount || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Freight:</span>
                        <span>- ₹ {Number(previewData.calculations?.freightDeducted || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Extra Freight:</span>
                        <span>- ₹ {Number(previewData.calculations?.extraFreightDeducted || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Unloading / Coolie:</span>
                        <span>- ₹ {Number(previewData.calculations?.unloadingDeducted || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Association Fee:</span>
                        <span>- ₹ {Number(previewData.calculations?.associationDeducted || 0).toFixed(2)}</span>
                      </div>
                      <div className="flex justify-between text-red-600">
                        <span>Misc Fee:</span>
                        <span>- ₹ {Number(previewData.calculations?.miscDeducted || 0).toFixed(2)}</span>
                      </div>
                      {Number(previewData.calculations?.advanceAdjusted || 0) > 0 && (
                        <div className="flex justify-between text-red-600">
                          <span>Advance Paid Upfront:</span>
                          <span>- ₹ {Number(previewData.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(previewData.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(previewData.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(previewData?.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(previewData?.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(previewData?.arrival?.arrivalSettlement)} />
                </Form.Item>
              </div>

              {/* FOOTER ACTIONS */}
              <div className="flex items-center justify-between pt-2 border-t">
                {previewData?.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={closeSettleModal}>
                    {previewData?.arrival?.arrivalSettlement ? 'Close' : 'Cancel'}
                  </Button>
                  {!previewData?.arrival?.arrivalSettlement && (
                    <Button
                      type="primary"
                      htmlType="submit"
                      icon={<CheckCircleOutlined />}
                      loading={submitting}
                      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={() => fetchSettlements(pagination.current, pagination.pageSize)}
        />
      </Spin>
    </div>
  );
};

export default ArrivalSettlements;
