import { useEffect, useState } from 'react';
import { useInvoiceLanguages } from '../../hooks/useInvoiceLanguages';
import {
    Button,
    Col,
    DatePicker,
    Form,
    Input,
    InputNumber,
    Modal,
    Row,
    Select,
    Space,
    Table,
    Tag,
    message,
    Popover,
    Descriptions,
    Spin,
    Tooltip,
    Upload,
    Image,
    type UploadFile,
    // Switch,
} from 'antd';
import {
    PlusOutlined,
    EyeOutlined,
    DeleteOutlined,
    WarningOutlined,
    PrinterOutlined,
    DownloadOutlined,
    EditOutlined,
    WhatsAppOutlined,
    ShoppingCartOutlined,
    DollarOutlined,
    WalletOutlined,
    RiseOutlined,
} from '@ant-design/icons';
import { AddSaleReturnModal } from './AddSaleReturnModal';
import dayjs, { Dayjs } from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import SummaryCard from '../../components/SummaryCard';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';

const ENTITY_LABEL = 'Credit Bills';
const ENTITY_ENDPOINT = ENDPOINTS.SALES;
const ENDPOINT_SALES_WHATSAPP_MESSAGE = ENDPOINTS.SALES_WHATSAPP_MESSAGE;

interface NamedOption {
    id: string;
    name: string;
    outstandingBalance?: string;
}

interface SaleMeta {
    customers: NamedOption[];
    vegetables: NamedOption[];
}

interface AvailableLot {
    id: string;
    lotNo: string;
    batchIndex?: number;
    batchLabel?: string;
    remainingQuantity: string;
    remainingBags: string;
    weightPerBag: string | null;
    costPerUnit: string;
    unit: string;
    rateType: string;
    vegetable: { id: string; name: string; isFlexible?: boolean };
    supplier: { name: string };
}

const { RangePicker } = DatePicker;

export const Sales = () => {
    const [form] = Form.useForm();
    const [open, setOpen] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
    const [data, setData] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [meta, setMeta] = useState<SaleMeta>({ customers: [], vegetables: [] });
    const [availableLots, setAvailableLots] = useState<Record<string, AvailableLot[]>>({});
    const [allAvailableLots, setAllAvailableLots] = useState<AvailableLot[]>([]);
    // costPerUnit per row index for warning display
    const [rowCostPerUnit, setRowCostPerUnit] = useState<Record<number, number>>({});
    // sellingRate per row for live warning check
    const [rowSellingRate, setRowSellingRate] = useState<Record<number, number>>({});
    const [rowSaleUnit, setRowSaleUnit] = useState<Record<number, string>>({});
    const [rowLot, setRowLot] = useState<Record<number, AvailableLot | undefined>>({});
    const [editingId, setEditingId] = useState<string | number | null>(null);

    const [viewOpen, setViewOpen] = useState(false);
    const [viewRecord, setViewRecord] = useState<any>(null);
    const [viewLoading, setViewLoading] = useState(false);

    // Returns state
    const [returnModalOpen, setReturnModalOpen] = useState(false);
    const [selectedItemToReturn, setSelectedItemToReturn] = useState<any>(null);

    // Print Options state
    const [printModalOpen, setPrintModalOpen] = useState(false);
    const [printInvoiceId, setPrintInvoiceId] = useState<string | number | null>(null);
    const [printLang, setPrintLang] = useState('en');
    const [pdfName, setPdfName] = useState('');

    // Image Upload states
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await new Promise((resolve) => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj as any);
                reader.onload = () => resolve(reader.result as string);
            });
        }
        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || (file.url ? file.url.substring(file.url.lastIndexOf('/') + 1) : 'Image Preview'));
    };

    const { languages: invoiceLanguages } = useInvoiceLanguages();
    // const [printSign, setPrintSign] = useState(false); // TEMP: Digital signature disabled — change to true to re-enable

    const [summary, setSummary] = useState({
        totalGrandTotal: 0,
        totalReceivedAmount: 0,
        totalBalanceAmount: 0,
    });
    const [selectedCustomer, setSelectedCustomer] = useState<string | undefined>(undefined);

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: Number(import.meta.env.VITE_PAGE_SIZE) || 10,
        total: 0,
        totalPages: 0,
    });

    const fetchMeta = async () => {
        try {
            const res = await jwtAxios.get(ENDPOINTS.SALES_META);
            setMeta(res.data?.result || { customers: [], vegetables: [] });
        } catch (err: any) {
            message.error(err.response?.data?.message || 'Failed to fetch meta');
        }
    };

    const fetchAvailableLots = async (vegetableId: string, fieldKey: number) => {
        try {
            const res = await jwtAxios.get(`${ENDPOINTS.SALES_AVAILABLE_LOTS}?vegetableId=${vegetableId}`);
            setAvailableLots((prev) => ({
                ...prev,
                [fieldKey]: res.data?.result || [],
            }));
        } catch (err: any) {
            message.error('Failed to fetch available lots');
        }
    };

    const fetchAllAvailableLots = async () => {
        try {
            const res = await jwtAxios.get(ENDPOINTS.SALES_AVAILABLE_LOTS);
            setAllAvailableLots(res.data?.result || []);
        } catch (err: any) {
            // silent catch
        }
    };

    const fetchData = async (
        page: number = pagination.current,
        limit: number = pagination.pageSize,
        search: string = searchText,
        range: [Dayjs, Dayjs] | null = dateRange,
        customer: string | undefined = selectedCustomer
    ) => {
        setLoading(true);
        try {
            let url = `${ENTITY_ENDPOINT}?page=${page}&limit=${limit}&saleType=CREDIT`;
            if (search) {
                url += `&search=${encodeURIComponent(search)}`;
            }
            if (customer) {
                url += `&customerId=${customer}`;
            }
            if (range) {
                url += `&dateFrom=${range[0].format('YYYY-MM-DD')}&dateTo=${range[1].format('YYYY-MM-DD')}`;
            }
            const res = await jwtAxios.get(url);
            // message.success(res?.data?.message);
            const records = res.data?.result?.data || [];
            const metaInfo = res.data?.result?.meta || {};

            setData(records.map((item: any) => ({ key: item.id, ...item })));
            setPagination((prev) => ({
                ...prev,
                current: metaInfo.page ?? page,
                pageSize: metaInfo.limit ?? limit,
                total: metaInfo.total ?? prev.total,
                totalPages: metaInfo.totalPages ?? prev.totalPages,
            }));

            if (metaInfo.summary) {
                setSummary({
                    totalGrandTotal: Number(metaInfo.summary.totalGrandTotal || 0),
                    totalReceivedAmount: Number(metaInfo.summary.totalReceivedAmount || 0),
                    totalBalanceAmount: Number(metaInfo.summary.totalBalanceAmount || 0),
                });
            }
        } catch (err: any) {
            message.error(err.response?.data?.message || 'Failed to fetch data');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchMeta();
        fetchAllAvailableLots();
        fetchData(1, pagination.pageSize, '');
    }, []);

    const handleSearch = (value: string) => {
        fetchData(1, pagination.pageSize, value, dateRange, selectedCustomer);
    };

    const handleDateRangeChange = (values: any) => {
        const range = values ? (values as [Dayjs, Dayjs]) : null;
        setDateRange(range);
        fetchData(1, pagination.pageSize, searchText, range, selectedCustomer);
    };

    const handleCustomerChange = (val: any) => {
        setSelectedCustomer(val);
        fetchData(1, pagination.pageSize, searchText, dateRange, val);
    };

    const handleAdd = () => {
        fetchMeta();
        fetchAllAvailableLots();
        form.resetFields();
        form.setFieldsValue({
            invoiceDate: dayjs(),
            discount: 0,
            freightCharge: 0,
            cashAmount: 0,
            upiAmount: 0,
            bankAmount: 0,
            items: [{}],
        });
        setRowSaleUnit({});
        setRowLot({});
        setRowCostPerUnit({});
        setRowSellingRate({});
        setEditingId(null);
        setFileList([]);
        setOpen(true);
    };

    const handleEdit = async (id: string) => {
        setLoading(true);
        fetchMeta();
        fetchAllAvailableLots();
        try {
            const res = await jwtAxios.get(`${ENTITY_ENDPOINT}/${id}`);
            const record = res.data?.result;

            if (record.saleReturns && record.saleReturns.length > 0) {
                message.error("Cannot edit a sale that already has returns.");
                return;
            }

            form.resetFields();

            const newRowLot: Record<number, AvailableLot | undefined> = {};
            const newRowSaleUnit: Record<number, string> = {};
            const newRowCostPerUnit: Record<number, number> = {};
            const newRowSellingRate: Record<number, number> = {};

            const items = (record.items || []).map((item: any, index: number) => {
                const mappedLot = {
                    ...item.purchase,
                    id: item.purchase?.id,
                    vegetable: item.purchase?.vegetable,
                } as AvailableLot;

                newRowLot[index] = mappedLot;
                newRowSaleUnit[index] = item.saleUnit;
                newRowCostPerUnit[index] = Number(item.costPerUnit);
                newRowSellingRate[index] = Number(item.sellingRate);

                setAllAvailableLots(prev => {
                    if (!prev.find(p => p.id === mappedLot.id)) {
                        return [...prev, mappedLot];
                    }
                    return prev;
                });

                return {
                    id: item.id,
                    vegetableId: item.purchase?.vegetableId,
                    purchaseId: item.purchase?.id,
                    saleUnit: item.saleUnit,
                    bags: (item.saleUnit === 'PIECES' || item.saleUnit === 'THAAR') ? undefined : (item.bags ? Number(item.bags) : undefined),
                    quantity: Number(item.quantity || (item.saleUnit === 'THAAR' ? item.bags : 0) || 0),
                    sellingRate: Number(item.sellingRate),
                    isNew: false,
                };
            });

            setRowLot(newRowLot);
            setRowSaleUnit(newRowSaleUnit);
            setRowCostPerUnit(newRowCostPerUnit);
            setRowSellingRate(newRowSellingRate);

            form.setFieldsValue({
                customerId: record.customerId,
                walkInName: record.walkInName,
                walkInMobile: record.walkInMobile,
                invoiceDate: dayjs(record.invoiceDate),
                discount: Number(record.discount || 0),
                freightCharge: Number(record.freightCharge || 0),
                cashAmount: Number(record.cashAmount || 0),
                upiAmount: Number(record.upiAmount || 0),
                bankAmount: Number(record.bankAmount || 0),
                subTotal: Number(record.subTotal || 0),
                grandTotal: Number(record.grandTotal || 0),
                _subTotalDisplay: Number(record.subTotal || 0).toFixed(2),
                _grandTotalDisplay: Number(record.grandTotal || 0).toFixed(2),
                items,
            });

            let existingImgs: string[] = [];
            if (record.images) {
                try {
                    existingImgs = typeof record.images === 'string' ? JSON.parse(record.images) : record.images;
                } catch {
                    existingImgs = [];
                }
            }
            const baseUrl = (import.meta.env.VITE_API_BASE_URL || '').replace(/\/$/, '');
            const mappedFiles: UploadFile[] = (existingImgs || []).map((fileName: string, idx: number) => ({
                uid: `-${idx}`,
                name: fileName,
                status: 'done',
                url: `${baseUrl}/uploads/sales/${fileName}`,
                response: { path: fileName },
            }));
            setFileList(mappedFiles);

            setEditingId(record.id);
            setOpen(true);
        } catch (err: any) {
            message.error('Failed to load sale details');
        } finally {
            setLoading(false);
        }
    };

    const handleWhatsapp = async (saleId: string) => {
        setLoading(true);
        try {
            await jwtAxios.post(ENDPOINT_SALES_WHATSAPP_MESSAGE(saleId));
            message.success('WhatsApp message sent successfully');
            fetchData(pagination.current, pagination.pageSize, searchText, dateRange);
        } catch (err: any) {
            message.error(err?.response?.data?.message || 'Failed to send WhatsApp message');
        } finally {
            setLoading(false);
        }
    }

    const handleView = async (id: string) => {
        setViewLoading(true);
        setViewOpen(true);
        try {
            const res = await jwtAxios.get(`${ENTITY_ENDPOINT}/${id}`);
            setViewRecord(res.data?.result);
        } catch (err: any) {
            message.error('Failed to load details');
            setViewOpen(false);
        } finally {
            setViewLoading(false);
        }
    };

    const handlePrintInvoice = (saleId: number | string) => {
        setPrintInvoiceId(saleId);
        setPrintModalOpen(true);
    };

    const executePrintInvoice = async () => {
        if (!printInvoiceId) return;
        setLoading(true);
        try {
            // const response = await jwtAxios.get(
            //     `${ENTITY_ENDPOINT}/${printInvoiceId}/invoice?lang=${printLang}&printSign=${printSign}`,
            //     {
            //         responseType: "blob",
            //     }
            // );
            const response = await jwtAxios.get(
                `${ENTITY_ENDPOINT}/${printInvoiceId}/invoice?lang=${printLang}`,
                {
                    responseType: "blob",
                }
            );

            const blob = new Blob([response.data], {
                type: "application/pdf",
            });

            const url = window.URL.createObjectURL(blob);

            // Get filename from Content-Disposition
            const disposition = response.headers["content-disposition"];
            console.log(disposition);
            let fileName = `invoice-${printInvoiceId}.pdf`;
            if (pdfName && pdfName.trim() !== "") {
                fileName = pdfName.trim().endsWith(".pdf") ? pdfName.trim() : `${pdfName.trim()}.pdf`;
            } else if (disposition) {
                console.log("Content-Disposition:", disposition);
                const match = disposition.match(/filename="?(.+)"?/i);
                if (match?.[1]) {
                    fileName = match[1];
                }
            }
            const link = document.createElement("a");
            link.href = url;
            link.download = fileName;

            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            window.URL.revokeObjectURL(url);

            message.success("Invoice downloaded successfully");
            setPrintModalOpen(false);
            setPdfName("");
        } catch (error: any) {
            message.error("Unable to generate invoice.");
        } finally {
            setLoading(false);
        }
    };

    const handleExport = async () => {
        if (!data || data.length === 0) {
            message.warning('No data available to export');
            return;
        }
        setLoading(true);
        try {
            const params = new URLSearchParams();
            params.set('saleType', 'CREDIT');
            if (searchText) params.set('search', searchText);
            if (selectedCustomer) params.set('customerId', selectedCustomer);
            if (dateRange) {
                params.set('dateFrom', dateRange[0].format('YYYY-MM-DD'));
                params.set('dateTo', dateRange[1].format('YYYY-MM-DD'));
            }

            const url = `${ENDPOINTS.SALES_EXPORT}${params.toString() ? '?' + params.toString() : ''}`;
            const response = await jwtAxios.get(url, { responseType: 'blob' });

            const disposition = response.headers['content-disposition'];
            let fileName = `credit-bills-${dayjs().format('YYYY-MM-DD')}.xlsx`;
            if (disposition) {
                const match = disposition.match(/filename\*?=(?:UTF-8'')?"?([^"\n;]+)"?/i);
                if (match?.[1]) fileName = decodeURIComponent(match[1]);
            }

            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            });
            const objectUrl = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = objectUrl;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(objectUrl);

            message.success('Sales exported successfully');
        } catch {
            message.error('Failed to export sales. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    const handleExportPdf = async () => {
        if (!data || data.length === 0) {
            message.warning('No data available to export');
            return;
        }
        setLoading(true);
        try {
            const params = new URLSearchParams();
            params.set('saleType', 'CREDIT');
            if (searchText) params.set('search', searchText);
            if (selectedCustomer) params.set('customerId', selectedCustomer);
            if (dateRange) {
                params.set('dateFrom', dateRange[0].format('YYYY-MM-DD'));
                params.set('dateTo', dateRange[1].format('YYYY-MM-DD'));
            }

            const url = `${ENDPOINTS.SALES_EXPORT_PDF}${params.toString() ? '?' + params.toString() : ''}`;
            const response = await jwtAxios.get(url, { responseType: 'blob' });

            const disposition = response.headers['content-disposition'];
            let fileName = `wholesale-sales-${dayjs().format('YYYY-MM-DD')}.pdf`;
            if (disposition) {
                const match = disposition.match(/filename="?([^"\n;]+)"?/i);
                if (match?.[1]) fileName = match[1];
            }

            const blob = new Blob([response.data], { type: 'application/pdf' });
            const objectUrl = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = objectUrl;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(objectUrl);

            message.success('PDF exported successfully');
        } catch (err: any) {
            let errorMessage = 'Failed to export PDF. Please try again.';

            // If responseType is 'blob', Axios wraps the JSON error in a Blob
            if (err.response?.data instanceof Blob) {
                try {
                    const text = await err.response.data.text();
                    const json = JSON.parse(text);
                    errorMessage = json.message || errorMessage;
                } catch (parseError) {
                    // fallback to default error message if parsing fails
                }
            } else if (err.response?.data?.message) {
                errorMessage = err.response.data.message;
            } else if (err.message) {
                errorMessage = err.message;
            }

            message.error(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    const computeSubTotal = (items: any[]) => {
        let subTotal = 0;
        (items || []).forEach((item: any) => {
            if (item.saleUnit === 'BOX' || item.saleUnit === 'BAG') {
                const bags = Number(item.bags) || 0;
                const rate = Number(item.sellingRate) || 0;
                subTotal += bags * rate;
            } else {
                const qty = Number(item.quantity) || 0;
                const rate = Number(item.sellingRate) || 0;
                subTotal += qty * rate;
            }
        });
        return Number(subTotal.toFixed(2));
    };

    const calculateTotals = () => {
        const items = form.getFieldValue('items') || [];
        const subTotal = computeSubTotal(items);
        const discount = Number(form.getFieldValue('discount')) || 0;
        const freightCharge = Number(form.getFieldValue('freightCharge')) || 0;
        const grandTotal = Number((subTotal - discount + freightCharge).toFixed(2));

        form.setFieldsValue({
            subTotal,
            grandTotal,
            _subTotalDisplay: subTotal.toFixed(2),
            _grandTotalDisplay: grandTotal.toFixed(2),
        });
    };

    const handleSubmit = async (values: any) => {
        setLoading(true);
        try {
            const subTotal = computeSubTotal(values.items);
            const discount = Number(values.discount) || 0;
            const freightCharge = Number(values.freightCharge) || 0;
            const grandTotal = Number((subTotal - discount + freightCharge).toFixed(2));

            const isCashBill = values.walkInName && !values.customerId;
            const cashAmount = isCashBill ? grandTotal : (Number(values.cashAmount) || 0);
            const upiAmount = isCashBill ? 0 : (Number(values.upiAmount) || 0);
            const bankAmount = isCashBill ? 0 : (Number(values.bankAmount) || 0);
            const receivedAmount = isCashBill ? grandTotal : Number((cashAmount + upiAmount + bankAmount).toFixed(2));

            const payload = {
                ...values,
                subTotal,
                grandTotal,
                cashAmount,
                upiAmount,
                bankAmount,
                receivedAmount,
                invoiceDate: values.invoiceDate.format('YYYY-MM-DD'),
            };

            const formData = new FormData();
            Object.keys(payload).forEach((key) => {
                if (key === 'items') {
                    formData.append('items', JSON.stringify(payload.items));
                } else if (payload[key] !== undefined && payload[key] !== null) {
                    formData.append(key, String(payload[key]));
                }
            });

            const existingImages: string[] = [];
            fileList.forEach((file) => {
                if (file.originFileObj) {
                    formData.append('images', file.originFileObj);
                } else if (file.name) {
                    existingImages.push(file.name);
                }
            });
            formData.append('existingImages', JSON.stringify(existingImages));

            if (editingId) {
                await jwtAxios.put(`${ENTITY_ENDPOINT}/${editingId}`, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
                message.success('Sale updated successfully');
            } else {
                await jwtAxios.post(ENTITY_ENDPOINT, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
                message.success('Sale created successfully');
            }

            setEditingId(null);
            setFileList([]);
            setOpen(false);
            fetchData(pagination.current, pagination.pageSize, searchText, dateRange);
        } catch (err: any) {
            if (err.response?.status === 422 && err.response?.data?.errors) {
                const fieldErrors = err.response.data.errors;
                const formErrors: { name: string | (string | number)[]; errors: string[] }[] = [];

                Object.keys(fieldErrors).forEach((fieldName) => {
                    const rawErrors = fieldErrors[fieldName];
                    const errorMsgs = Array.isArray(rawErrors) ? rawErrors : [rawErrors];

                    let namePath: string | (string | number)[] = fieldName;
                    if (fieldName.includes('.')) {
                        namePath = fieldName.split('.').map((p) => (!isNaN(Number(p)) ? Number(p) : p));
                    }

                    formErrors.push({
                        name: namePath,
                        errors: errorMsgs,
                    });
                });

                form.setFields(formErrors);
                const msg = err.response?.data?.message || 'Please fix the validation errors in the form.';
                message.error(msg);
            } else {
                const msg = err.response?.data?.message || 'Failed to create sale';
                message.error(msg);
            }
        } finally {
            setLoading(false);
        }
    };

    const columns = [
        {
            title: "ID",
            dataIndex: "id",
        },
        { title: 'Invoice No', dataIndex: 'invoiceNo' },
        {
            title: 'Date',
            dataIndex: 'invoiceDate',
            render: (date: string) => dayjs(date).format('DD/MM/YYYY'),
        },
        {
            title: 'Customer',
            dataIndex: 'customer',
            render: (customer: any, record: any) => customer?.name || (record.walkInName ? `${record.walkInName} (Walk-in)` : '-'),
        },
        {
            title: 'Sub Total',
            dataIndex: 'subTotal',
            render: (val: string) => Number(val).toFixed(2),
        },
        {
            title: 'Grand Total',
            dataIndex: 'grandTotal',
            render: (val: string) => Number(val).toFixed(2),
        },
        {
            title: 'Images',
            key: 'images',
            align: 'center' as const,
            render: (_: any, record: any) => {
                let imgs: string[] = [];
                if (record.images) {
                    try {
                        imgs = typeof record.images === 'string' ? JSON.parse(record.images) : record.images;
                        if (!Array.isArray(imgs)) imgs = [];
                    } catch {
                        imgs = [];
                    }
                }
                if (!imgs || imgs.length === 0) {
                    return <span className="text-gray-400">-</span>;
                }
                const baseUrl = (import.meta.env.VITE_API_BASE_URL || '').replace(/\/$/, '');
                const fullUrls = imgs.map((fileName: string) => `${baseUrl}/uploads/sales/${fileName}`);

                return (
                    <Image.PreviewGroup>
                        <div style={{ display: 'inline-flex', alignItems: 'center', padding: '4px 0' }}>
                            {fullUrls.map((url: string, index: number) => (
                                <div
                                    key={index}
                                    style={{
                                        marginLeft: index === 0 ? 0 : -10,
                                        zIndex: index + 1,
                                        display: 'inline-flex',
                                        transition: 'transform 0.2s ease',
                                    }}
                                    className="hover:scale-115 hover:z-50"
                                >
                                    <Image
                                        src={url}
                                        width={30}
                                        height={30}
                                        wrapperStyle={{
                                            borderRadius: '50%',
                                            overflow: 'hidden',
                                            display: 'inline-flex',
                                            border: '2px solid #ffffff',
                                            boxShadow: '0 2px 5px rgba(0, 0, 0, 0.15)',
                                            cursor: 'pointer',
                                        }}
                                        style={{
                                            width: 30,
                                            height: 30,
                                            objectFit: 'cover',
                                            borderRadius: '50%',
                                        }}
                                    />
                                </div>
                            ))}
                        </div>
                    </Image.PreviewGroup>
                );
            },
        },
        {
            title: 'Actions',
            render: (_: any, record: any) => (
                <Space>
                    <Popover content="View Details">
                        <Button type="link" icon={<EyeOutlined />} onClick={() => handleView(record.id)} />
                    </Popover>
                    <Popover content="Edit Credit Bill">
                        <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record.id)} />
                    </Popover>
                    <Popover content="Print Invoice">
                        <Button type="link" className="text-red-500!" icon={<PrinterOutlined />} onClick={() => handlePrintInvoice(record.id)} />
                    </Popover>
                    <Popover
                        content={
                            record.isWhatsappMessageSent
                                ? "Invoice already sent"
                                : "Share Invoice via WhatsApp"
                        }
                    >
                        <Button
                            disabled={record.isWhatsappMessageSent ?? false}
                            type="link"
                            className={
                                record.isWhatsappMessageSent
                                    ? "text-gray-400! opacity-60! cursor-not-allowed!"
                                    : "text-green-500!"
                            }
                            icon={<WhatsAppOutlined />}
                            onClick={() => handleWhatsapp(record.id)}
                        />
                    </Popover>
                </Space>
            ),
        },
    ];

    return (
        <div>
            <AppContainer
                title={`${ENTITY_LABEL}`}
                headerAction={
                    <Space>
                        <Button
                            icon={<DownloadOutlined />}
                            style={{ color: '#52c41a', borderColor: '#52c41a' }}
                            onClick={handleExport}
                            loading={loading}
                        >
                            Export
                        </Button>
                        <Button
                            icon={<DownloadOutlined />}
                            style={{ color: '#cf1322', borderColor: '#cf1322' }}
                            onClick={handleExportPdf}
                            loading={loading}
                        >
                            Export PDF
                        </Button>
                        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                            Add Credit Bill
                        </Button>
                    </Space>
                }
            >
                {/* Summary KPI Cards */}
                <Row gutter={[16, 16]} className="mb-4">
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Credit Invoiced"
                            value={summary.totalGrandTotal}
                            icon={<ShoppingCartOutlined />}
                            color="#1677ff"
                        />
                    </Col>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Amount Collected"
                            value={summary.totalReceivedAmount}
                            icon={<DollarOutlined />}
                            color="#52c41a"
                        />
                    </Col>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Outstanding Balance"
                            value={summary.totalBalanceAmount}
                            icon={<WalletOutlined />}
                            color="#f5222d"
                        />
                    </Col>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Credit Bills"
                            value={pagination.total}
                            icon={<RiseOutlined />}
                            color="#722ed1"
                            showCurrency={false}
                        />
                    </Col>
                </Row>

                <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
                    <Space wrap>
                        <RangePicker value={dateRange as any} onChange={handleDateRangeChange} />
                        <Select
                            placeholder="Filter by Customer"
                            allowClear
                            showSearch
                            value={selectedCustomer}
                            onChange={handleCustomerChange}
                            optionFilterProp="label"
                            filterOption={(input, option) =>
                                String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                            }
                            style={{ width: 220 }}
                            options={meta.customers.map((c) => ({
                                label: `${c.name} (Bal: ₹${c.outstandingBalance})`,
                                value: c.id,
                            }))}
                        />
                        <Input.Search
                            placeholder="Search..."
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            onSearch={handleSearch}
                            allowClear
                            style={{ width: 200 }}
                        />
                    </Space>
                </div>
                <Table
                    columns={columns}
                    dataSource={data}
                    loading={loading}
                    rowKey="id"
                    pagination={{
                        ...pagination,
                        onChange: (page, pageSize) => fetchData(page, pageSize),
                    }}
                />
                <div className="text-center mt-2">
                    <Tag color="cyan">
                        Page {pagination.current} of {pagination.totalPages}
                    </Tag>
                </div>

                {/* CREATE/EDIT SALE MODAL */}
                <Modal
                    title={editingId ? `Edit Credit Bill #${editingId}` : "Create Credit Bill"}
                    open={open}
                    onCancel={() => setOpen(false)}
                    width={1200}
                    styles={{ body: { maxHeight: '70vh', overflowY: 'auto', overflowX: 'hidden' } }}
                    onOk={() => {
                        if (editingId) {
                            form.submit();
                        } else {
                            Modal.confirm({
                                title: "Confirm Credit Bill",
                                content: "Once submitted, sales cannot be edited (only cancelled). Are you sure?",
                                onOk: () => form.submit(),
                            });
                        }
                    }}
                    okText={editingId ? "Update Sale" : "Submit Sale"}
                >
                    <Form form={form} layout="vertical" onFinish={handleSubmit} onValuesChange={calculateTotals}>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item noStyle shouldUpdate>
                                    {() => {
                                        const isCashBill = form.getFieldValue('walkInName') && !form.getFieldValue('customerId');
                                        return isCashBill ? (
                                            <Form.Item name="walkInName" label="Customer (Cash)">
                                                <Input disabled />
                                            </Form.Item>
                                        ) : (
                                            <Form.Item name="customerId" label="Customer" rules={[{ required: true, message: 'Please select a customer' }]}>
                                                <Select
                                                    showSearch
                                                    optionFilterProp="label"
                                                    filterOption={(input, option) =>
                                                        String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                                    }
                                                    placeholder="Select customer"
                                                    options={meta.customers.map(c => ({ label: `${c.name} (Bal: ₹${c.outstandingBalance})`, value: c.id }))}
                                                // disabled={!!editingId}
                                                />
                                            </Form.Item>
                                        );
                                    }}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="invoiceDate" label="Invoice Date" rules={[{ required: true, message: 'Please select a date' }]}>
                                    <DatePicker style={{ width: '100%' }} />
                                </Form.Item>
                            </Col>
                        </Row>

                        <div style={{ border: '1px solid #d9d9d9', padding: 16, marginBottom: 16, borderRadius: 8 }}>
                            <h4>Sale Items</h4>
                            <Form.List name="items">
                                {(fields, { add, remove }) => (
                                    <>
                                        {fields.map(({ key, name, ...restField }) => {
                                            const isFlexibleLot = !!rowLot[name]?.vegetable?.isFlexible || rowLot[name]?.unit === 'THAAR' || rowSaleUnit[name] === 'PIECES';
                                            const costPerUnit = rowCostPerUnit[name];
                                            let unitCost = costPerUnit;
                                            if (rowSaleUnit[name] && rowSaleUnit[name] !== 'KG' && Number(rowLot[name]?.weightPerBag) > 0 && costPerUnit !== undefined) {
                                                unitCost = costPerUnit * Number(rowLot[name]!.weightPerBag);
                                            }
                                            const sellingRate = rowSellingRate[name];
                                            const isBelowCost = !isFlexibleLot && unitCost !== undefined && sellingRate !== undefined && sellingRate < unitCost;

                                            return (
                                                <div key={key} className="bg-gray-50 border border-gray-200 rounded-lg py-3 px-4 mb-3">
                                                    <Row gutter={12} className="items-start mb-4">
                                                        <Col span={5}>
                                                            <Form.Item
                                                                {...restField}
                                                                label="Vegetable"
                                                                name={[name, 'vegetableId']}
                                                                rules={[{ required: true, message: 'Select vegetable' }]}
                                                            >
                                                                <Select
                                                                    placeholder="Select vegetable"
                                                                    showSearch
                                                                    allowClear
                                                                    disabled={!!editingId && !form.getFieldValue(['items', name, 'isNew'])}
                                                                    optionFilterProp="label"
                                                                    filterOption={(input, option) =>
                                                                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                                                    }
                                                                    options={meta.vegetables.map(v => ({
                                                                        label: v.name,
                                                                        value: v.id
                                                                    }))}
                                                                    onChange={(val) => {
                                                                        if (val) {
                                                                            fetchAvailableLots(val, name);
                                                                            form.setFieldValue(['items', name, 'purchaseId'], undefined);
                                                                        } else {
                                                                            setAvailableLots((prev) => ({ ...prev, [name]: [] }));
                                                                            form.setFieldValue(['items', name, 'vegetableId'], undefined);
                                                                            form.setFieldValue(['items', name, 'purchaseId'], undefined);
                                                                            setRowLot((prev) => ({ ...prev, [name]: undefined }));
                                                                        }

                                                                        // Clear cost reference when vegetable changes
                                                                        setRowCostPerUnit(prev => {
                                                                            const n = { ...prev };
                                                                            delete n[name];
                                                                            return n;
                                                                        });
                                                                    }}
                                                                />
                                                            </Form.Item>
                                                        </Col>
                                                        <Col span={12}>
                                                            <Form.Item
                                                                {...restField}
                                                                label="Lot"

                                                                name={[name, 'purchaseId']}
                                                                rules={[{ required: true, message: 'Select lot' }]}
                                                            >
                                                                {(() => {
                                                                    const rowVegId = form.getFieldValue(['items', name, 'vegetableId']);
                                                                    const getVegId = (l: any) => l.vegetable?.id ?? l.vegetableId ?? l.vegetable_id;

                                                                    const vegLots = (availableLots[name] && availableLots[name].length > 0)
                                                                        ? availableLots[name]
                                                                        : allAvailableLots.filter((l) => rowVegId && String(getVegId(l)) === String(rowVegId));

                                                                    let optionsPool = rowVegId ? vegLots : allAvailableLots;

                                                                    // Ensure the currently selected lot is always in the options pool (crucial for Edit mode)
                                                                    if (rowLot[name] && !optionsPool.find((l) => String(l.id) === String(rowLot[name]!.id))) {
                                                                        optionsPool = [...optionsPool, rowLot[name]!];
                                                                    }

                                                                    return (
                                                                        <Select
                                                                            placeholder="Select or enter lot no"
                                                                            showSearch
                                                                            allowClear
                                                                            disabled={!!editingId && !form.getFieldValue(['items', name, 'isNew'])}
                                                                            optionFilterProp="label"
                                                                            filterOption={(input, option) => {
                                                                                const searchText = input.toLowerCase();
                                                                                const label = String(option?.label || '').toLowerCase();
                                                                                const lotNo = String(option?.lotNo || '').toLowerCase();
                                                                                const vegName = String(option?.vegName || '').toLowerCase();
                                                                                return label.includes(searchText) || lotNo.includes(searchText) || vegName.includes(searchText);
                                                                            }}
                                                                            onSearch={(value) => {
                                                                                if (!value || !value.trim()) return;
                                                                                const trimmed = value.trim().toLowerCase();
                                                                                const exists = allAvailableLots.some(
                                                                                    (l) =>
                                                                                        l.lotNo.toLowerCase().includes(trimmed) ||
                                                                                        (l.batchLabel && l.batchLabel.toLowerCase().includes(trimmed)) ||
                                                                                        (l.vegetable?.name && l.vegetable.name.toLowerCase().includes(trimmed))
                                                                                );
                                                                                if (!exists) {
                                                                                    message.warning(`Lot number "${value.trim()}" is not available or out of stock.`);
                                                                                }
                                                                            }}
                                                                            options={optionsPool.map((lot) => ({
                                                                                label: `${lot.batchLabel || lot.lotNo} ${lot.vegetable?.name ? `(${lot.vegetable.name})` : ''} (Avail: ${Number(lot.remainingQuantity) > 0 ? lot.remainingQuantity + ' KG' : ''}${Number(lot.remainingBags) > 0 ? (Number(lot.remainingQuantity) > 0 ? ' / ' : '') + lot.remainingBags + ' ' + lot.unit : ''} - Cost: ₹${Number(lot.costPerUnit).toFixed(2)})`,
                                                                                value: lot.id,
                                                                                lotNo: lot.lotNo,
                                                                                vegName: lot.vegetable?.name || '',
                                                                            }))}
                                                                            onChange={(lotId) => {
                                                                                if (!lotId) {
                                                                                    form.setFieldValue(['items', name, 'purchaseId'], undefined);
                                                                                    form.setFieldValue(['items', name, 'vegetableId'], undefined);
                                                                                    setRowCostPerUnit((prev) => { const n = { ...prev }; delete n[name]; return n; });
                                                                                    setRowLot((prev) => ({ ...prev, [name]: undefined }));
                                                                                    return;
                                                                                }
                                                                                const lot = optionsPool.find((l) => l.id === lotId) || allAvailableLots.find((l) => l.id === lotId);
                                                                                if (lot) {
                                                                                    const currentVegId = form.getFieldValue(['items', name, 'vegetableId']);
                                                                                    const lotVegId = getVegId(lot);
                                                                                    if (lotVegId && String(currentVegId) !== String(lotVegId)) {
                                                                                        form.setFieldValue(['items', name, 'vegetableId'], lotVegId);
                                                                                        fetchAvailableLots(lotVegId, name);
                                                                                    }
                                                                                    setRowCostPerUnit((prev) => ({ ...prev, [name]: Number(lot.costPerUnit) }));
                                                                                    setRowLot((prev) => ({ ...prev, [name]: lot }));
                                                                                    const isLotFlexible = !!lot.vegetable?.isFlexible || lot.unit === 'THAAR';
                                                                                    const defaultUnit: string = isLotFlexible
                                                                                        ? (lot.unit === 'THAAR' ? 'THAAR' : (lot.unit === 'KG' ? 'PIECES' : (lot.unit || 'PIECES')))
                                                                                        : (lot.rateType === 'UNIT' ? (lot.unit || 'KG') : (Number(lot.remainingQuantity) > 0 ? 'KG' : (lot.unit || 'KG')));
                                                                                    setRowSaleUnit((prev) => ({ ...prev, [name]: defaultUnit }));
                                                                                    form.setFieldValue(['items', name, 'saleUnit'], defaultUnit);
                                                                                    form.setFieldValue(['items', name, 'bags'], undefined);
                                                                                }
                                                                            }}
                                                                        />
                                                                    );
                                                                })()}
                                                            </Form.Item>
                                                        </Col>
                                                        <Col span={6}>
                                                            <Form.Item
                                                                {...restField}
                                                                label="Sell By"
                                                                name={[name, 'saleUnit']}
                                                                initialValue="KG"
                                                                rules={[{ required: true, message: 'Required' }]}
                                                            >
                                                                {(() => {
                                                                    const currentPurchaseId = form.getFieldValue(['items', name, 'purchaseId']);
                                                                    const selectedLot = rowLot[name] || (currentPurchaseId ? allAvailableLots.find((l: any) => l.id === currentPurchaseId) : undefined);
                                                                    const isLotFlexible = !!selectedLot?.vegetable?.isFlexible || selectedLot?.unit === 'THAAR';
                                                                    return (
                                                                        <Select
                                                                            options={
                                                                                isLotFlexible
                                                                                    ? [
                                                                                        { label: 'PIECES', value: 'PIECES' },
                                                                                        ...(selectedLot?.unit === 'THAAR'
                                                                                            ? [{ label: 'THAAR', value: 'THAAR' }]
                                                                                            : selectedLot?.unit === 'BAG'
                                                                                                ? [{ label: 'BAG', value: 'BAG' }, { label: 'KG', value: 'KG' }]
                                                                                                : selectedLot?.unit === 'BOX'
                                                                                                    ? [{ label: 'BOX', value: 'BOX' }, { label: 'KG', value: 'KG' }]
                                                                                                    : [{ label: 'KG', value: 'KG' }]),
                                                                                    ]
                                                                                    : selectedLot?.rateType === 'UNIT'
                                                                                        ? [{ label: selectedLot.unit, value: selectedLot.unit }]
                                                                                        : selectedLot?.rateType === 'KG'
                                                                                            ? [{ label: 'KG', value: 'KG' }]
                                                                                            : [
                                                                                                ...(Number(selectedLot?.remainingQuantity) > 0 ? [{ label: 'KG', value: 'KG' }] : []),
                                                                                                ...(selectedLot?.unit !== 'KG' && Number(selectedLot?.remainingBags) > 0
                                                                                                    ? [{ label: selectedLot!.unit, value: selectedLot!.unit }]
                                                                                                    : []),
                                                                                            ]
                                                                            }
                                                                            disabled={(!!editingId && !form.getFieldValue(['items', name, 'isNew'])) || (isLotFlexible ? false : !!selectedLot?.rateType)}
                                                                            onChange={(val) => {
                                                                                setRowSaleUnit(prev => ({ ...prev, [name]: val }));
                                                                                if (val === 'KG') {
                                                                                    if (selectedLot?.unit === 'KG') {
                                                                                        form.setFieldValue(['items', name, 'bags'], undefined);
                                                                                    }
                                                                                } else if (val === 'PIECES') {
                                                                                    form.setFieldValue(['items', name, 'bags'], undefined);
                                                                                } else {
                                                                                    form.setFieldValue(['items', name, 'quantity'], undefined);
                                                                                }
                                                                            }}
                                                                        />
                                                                    );
                                                                })()}
                                                            </Form.Item>
                                                        </Col>
                                                    </Row>
                                                    <Row gutter={12} className="items-start">
                                                        <Col span={6}>
                                                            <Form.Item label={rowSaleUnit[name] === 'PIECES' ? "Cost / Piece" : (rowSaleUnit[name] && rowSaleUnit[name] !== 'KG' ? `Cost / ${rowSaleUnit[name] === 'THAAR' ? 'Thaar' : (rowLot[name]?.unit || rowSaleUnit[name])}` : "Cost / Kg")}>
                                                                <Input
                                                                    readOnly
                                                                    value={
                                                                        rowSaleUnit[name] === 'PIECES'
                                                                            ? '-'
                                                                            : (costPerUnit !== undefined
                                                                                ? `₹${(
                                                                                    rowSaleUnit[name] && rowSaleUnit[name] !== 'KG' && Number(rowLot[name]?.weightPerBag) > 0
                                                                                        ? costPerUnit * Number(rowLot[name]!.weightPerBag)
                                                                                        : costPerUnit
                                                                                ).toFixed(2)}`
                                                                                : '-')
                                                                    }
                                                                    className="font-bold bg-gray-100 text-gray-600 cursor-default border-gray-300"
                                                                />
                                                            </Form.Item>
                                                        </Col>
                                                        <Col span={6}>
                                                            {(rowSaleUnit[name] === 'PIECES' || rowSaleUnit[name] === 'THAAR') ? (
                                                                <Form.Item
                                                                    {...restField}
                                                                    label={rowSaleUnit[name] === 'THAAR' ? 'Thaar Count' : 'Pieces Count'}
                                                                    name={[name, 'quantity']}
                                                                    rules={[{ required: true, message: 'Required' }]}
                                                                >
                                                                    <InputNumber placeholder={rowSaleUnit[name] === 'THAAR' ? 'Thaar Count' : 'Pieces'} min={1} step={1} className="w-full" />
                                                                </Form.Item>
                                                            ) : (rowSaleUnit[name] && rowSaleUnit[name] !== 'KG') ? (
                                                                <Form.Item
                                                                    {...restField}
                                                                    label={rowLot[name]?.unit || rowSaleUnit[name] || 'Bags'}
                                                                    name={[name, 'bags']}
                                                                    rules={[{ required: true, message: 'Required' }]}
                                                                >
                                                                    <InputNumber placeholder={rowLot[name]?.unit || rowSaleUnit[name] || 'Bags'} min={1} step={1} className="w-full" />
                                                                </Form.Item>
                                                            ) : (
                                                                <div className="flex gap-1">
                                                                    {(rowLot[name]?.unit === 'BAG' || rowLot[name]?.unit === 'BOX') && (
                                                                        <Form.Item
                                                                            {...restField}
                                                                            label="Bags"
                                                                            name={[name, 'bags']}
                                                                            rules={[{ required: true, message: 'Req' }]}
                                                                            className="flex-1"
                                                                        >
                                                                            <InputNumber placeholder="Bags" min={1} step={1} className="w-full" />
                                                                        </Form.Item>
                                                                    )}
                                                                    <Form.Item
                                                                        {...restField}
                                                                        label="Qty (Kg)"
                                                                        name={[name, 'quantity']}
                                                                        rules={[{ required: true, message: 'Req' }]}
                                                                        className="flex-1"
                                                                    >
                                                                        <InputNumber placeholder="Qty" min={0} step={0.01} className="w-full" />
                                                                    </Form.Item>
                                                                </div>
                                                            )}
                                                        </Col>
                                                        <Col span={6}>
                                                            <Form.Item
                                                                {...restField}
                                                                label={rowSaleUnit[name] === 'PIECES' ? "Selling Rate / Piece" : (rowSaleUnit[name] && rowSaleUnit[name] !== 'KG' ? `Selling Rate / ${rowSaleUnit[name] === 'THAAR' ? 'Thaar' : (rowLot[name]?.unit || rowSaleUnit[name])}` : "Selling Rate / Kg")}
                                                                name={[name, 'sellingRate']}
                                                                rules={[{ required: true, message: 'Required' }]}
                                                            >
                                                                <InputNumber
                                                                    placeholder="Rate"
                                                                    min={0}
                                                                    step={0.01}
                                                                    className={`w-full ${isBelowCost ? 'border-yellow-500' : ''}`}
                                                                    onChange={(val) => {
                                                                        setRowSellingRate(prev => ({ ...prev, [name]: Number(val) }));
                                                                    }}
                                                                />
                                                            </Form.Item>
                                                            {isBelowCost && (
                                                                <Tooltip title={`Selling rate ₹${sellingRate.toFixed(2)} is below cost ₹${(unitCost || costPerUnit).toFixed(2)}. You will incur a loss on this item.`}>
                                                                    <div className="-mt-4 mb-2 text-xs text-yellow-500 cursor-help">
                                                                        <WarningOutlined /> Below cost — selling at a loss
                                                                    </div>
                                                                </Tooltip>
                                                            )}
                                                        </Col>
                                                        <Col span={6} className="flex justify-end pt-7">
                                                            <Button type="primary" danger onClick={() => remove(name)} icon={<DeleteOutlined />}>
                                                                Remove Item
                                                            </Button>
                                                        </Col>
                                                    </Row>
                                                </div>
                                            );
                                        })}
                                        <Button type="dashed" onClick={() => add({ isNew: true })} block icon={<PlusOutlined />}>
                                            Add Item
                                        </Button>
                                    </>
                                )}
                            </Form.List>
                        </div>

                        <Form.Item noStyle shouldUpdate>
                            {() => {
                                const isCashBill = form.getFieldValue('walkInName') && !form.getFieldValue('customerId');
                                return isCashBill ? (
                                    <Row gutter={16}>
                                        <Col span={6}>
                                            <Form.Item name="freightCharge" label="Freight Charge">
                                                <InputNumber min={0} step={0.01} style={{ width: '100%' }} />
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item name="_grandTotalDisplay" label="Received Amount (Auto)">
                                                <InputNumber min={0} step={0.01} style={{ width: '100%' }} disabled />
                                            </Form.Item>
                                        </Col>
                                        <Col span={6}>
                                            <Form.Item name="remarks" label="Remarks">
                                                <Input />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                ) : (
                                    <>
                                        <Row gutter={16}>
                                            {/* <Col span={6}>
                                                <Form.Item name="discount" label="Discount">
                                                    <InputNumber min={0} step={0.01} style={{ width: '100%' }} />
                                                </Form.Item>
                                            </Col> */}
                                            <Col span={6}>
                                                <Form.Item name="freightCharge" label="Freight Charge">
                                                    <InputNumber min={0} step={0.01} style={{ width: '100%' }} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={6}>
                                                <Form.Item
                                                    name="cashAmount"
                                                    label="Cash"
                                                >
                                                    <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="Cash" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={6}>
                                                <Form.Item
                                                    name="upiAmount"
                                                    label="UPI"
                                                >
                                                    <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="UPI" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={6}>
                                                <Form.Item
                                                    name="bankAmount"
                                                    label="Bank"
                                                >
                                                    <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="Bank" />
                                                </Form.Item>
                                            </Col>
                                        </Row>

                                        <Row gutter={16}>
                                            <Col span={6}>
                                                <Form.Item name="remarks" label="Remarks">
                                                    <Input />
                                                </Form.Item>
                                            </Col>
                                            <Col span={18} />
                                        </Row>
                                    </>
                                );
                            }}
                        </Form.Item>

                        <Form.Item noStyle shouldUpdate={(prev, cur) =>
                            prev.cashAmount !== cur.cashAmount ||
                            prev.upiAmount !== cur.upiAmount ||
                            prev.bankAmount !== cur.bankAmount ||
                            prev._grandTotalDisplay !== cur._grandTotalDisplay ||
                            prev.customerId !== cur.customerId
                        }>
                            {({ getFieldValue }) => {
                                const grandTotal = Number(getFieldValue('_grandTotalDisplay') || 0);
                                const cash = Number(getFieldValue('cashAmount') || 0);
                                const upi = Number(getFieldValue('upiAmount') || 0);
                                const bank = Number(getFieldValue('bankAmount') || 0);
                                const totalReceived = cash + upi + bank;

                                let invoiceBalance = grandTotal - totalReceived;
                                let excessReceived = 0;

                                if (invoiceBalance < 0) {
                                    excessReceived = Math.abs(invoiceBalance);
                                    invoiceBalance = 0;
                                }

                                const customerId = getFieldValue('customerId');
                                const customer = meta.customers?.find(c => String(c.id) === String(customerId));
                                const previousOutstanding = customer ? Number(customer.outstandingBalance || 0) : 0;

                                let customerAdvance = 0;

                                if (excessReceived > 0) {
                                    if (excessReceived > previousOutstanding) {
                                        customerAdvance = excessReceived - previousOutstanding;
                                    } else {
                                        customerAdvance = 0;
                                    }
                                }

                                return (
                                    <div style={{ marginTop: '24px', padding: '16px', background: '#fafafa', borderRadius: '8px', border: '1px solid #f0f0f0' }}>
                                        <Row gutter={[16, 12]}>
                                            <Col span={8}>
                                                <div style={{ color: '#8c8c8c', marginBottom: 4 }}>Invoice Total</div>
                                                <div style={{ fontWeight: 'bold', fontSize: '1.2em' }}>₹{grandTotal.toFixed(2)}</div>
                                            </Col>
                                            <Col span={8}>
                                                <div style={{ color: '#8c8c8c', marginBottom: 4 }}>Total Received</div>
                                                <div style={{ fontWeight: 'bold', fontSize: '1.2em', color: totalReceived > 0 ? '#389e0d' : undefined }}>₹{totalReceived.toFixed(2)}</div>
                                            </Col>
                                            <Col span={8}>
                                                <div style={{ color: '#8c8c8c', marginBottom: 4 }}>Invoice Balance</div>
                                                <div style={{ fontWeight: 'bold', fontSize: '1.2em', color: invoiceBalance > 0 ? '#cf1322' : '#389e0d' }}>₹{invoiceBalance.toFixed(2)}</div>
                                            </Col>
                                        </Row>

                                        {excessReceived > 0 && (
                                            <>
                                                <div style={{ margin: '16px 0', borderTop: '1px dashed #d9d9d9' }} />
                                                <Row gutter={[16, 12]}>
                                                    <Col span={8}>
                                                        <div style={{ color: '#8c8c8c', marginBottom: 4 }}>Excess Received</div>
                                                        <div style={{ fontWeight: 'bold', fontSize: '1.1em', color: '#1890ff' }}>₹{excessReceived.toFixed(2)}</div>
                                                    </Col>
                                                    {previousOutstanding > 0 && (
                                                        <>
                                                            <Col span={8}>
                                                                <div style={{ color: '#8c8c8c', marginBottom: 4 }}>Previous Outstanding</div>
                                                                <div style={{ fontWeight: 'bold', fontSize: '1.1em' }}>₹{previousOutstanding.toFixed(2)}</div>
                                                            </Col>
                                                            <Col span={8}>
                                                                <div style={{ color: '#8c8c8c', marginBottom: 4 }}>Customer Advance</div>
                                                                <div style={{ fontWeight: 'bold', fontSize: '1.1em', color: '#1890ff' }}>₹{customerAdvance.toFixed(2)}</div>
                                                            </Col>
                                                        </>
                                                    )}
                                                </Row>
                                            </>
                                        )}
                                    </div>
                                );
                            }}
                        </Form.Item>

                        {/* INVOICE IMAGES UPLOAD SECTION */}
                        <div style={{ marginTop: 16, border: '1px solid #d9d9d9', padding: 16, borderRadius: 8 }}>
                            <h4 style={{ marginBottom: 12 }}>Invoice Images (Max 10 images, up to 5MB each)</h4>
                            <Upload
                                accept="image/jpeg,image/png,image/jpg"
                                listType="picture-card"
                                fileList={fileList}
                                multiple
                                maxCount={10}
                                beforeUpload={(file) => {
                                    const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
                                    if (!isImage) {
                                        message.error(`${file.name} is not an image file! Only JPG, JPEG, and PNG images are allowed.`);
                                        return Upload.LIST_IGNORE;
                                    }
                                    const isLt5M = file.size / 1024 / 1024 < 5;
                                    if (!isLt5M) {
                                        message.error('Image must be smaller than 5MB!');
                                        return Upload.LIST_IGNORE;
                                    }
                                    return false;
                                }}
                                onChange={({ fileList }) => setFileList(fileList)}
                                onPreview={handlePreview}
                            >
                                {fileList.length >= 10 ? null : (
                                    <div>
                                        <PlusOutlined />
                                        <div style={{ marginTop: 8 }}>Upload</div>
                                    </div>
                                )}
                            </Upload>
                        </div>
                    </Form>
                </Modal>

                {/* VIEW MODAL */}
                <Modal
                    title={`Sale Details - ${viewRecord?.invoiceNo}`}
                    open={viewOpen}
                    onCancel={() => setViewOpen(false)}
                    footer={null}
                    width={800}
                >
                    <Spin spinning={viewLoading}>
                        {viewRecord && (
                            <>
                                <Descriptions bordered column={2}>
                                    <Descriptions.Item label="Invoice No">{viewRecord.invoiceNo}</Descriptions.Item>
                                    <Descriptions.Item label="Date">{dayjs(viewRecord.invoiceDate).format('DD/MM/YYYY')}</Descriptions.Item>
                                    <Descriptions.Item label="Customer">{viewRecord.customer?.name || (viewRecord.walkInName ? `${viewRecord.walkInName} (Walk-in)` : 'Walk-in Customer')}</Descriptions.Item>
                                    {/* <Descriptions.Item label="Payment Status">{viewRecord.paymentStatus}</Descriptions.Item> */}
                                    <Descriptions.Item label="Sub Total">₹{Number(viewRecord.subTotal).toFixed(2)}</Descriptions.Item>
                                    {/* <Descriptions.Item label="Discount">₹{Number(viewRecord.discount).toFixed(2)}</Descriptions.Item> */}
                                    <Descriptions.Item label="Freight">₹{Number(viewRecord.freightCharge).toFixed(2)}</Descriptions.Item>
                                    <Descriptions.Item label="Grand Total">₹{Number(viewRecord.grandTotal).toFixed(2)}</Descriptions.Item>
                                    <Descriptions.Item label="Received">₹{Number(viewRecord.receivedAmount).toFixed(2)}</Descriptions.Item>
                                    {Number(viewRecord.cashAmount) > 0 && (
                                        <Descriptions.Item label="  — Cash">₹{Number(viewRecord.cashAmount).toFixed(2)}</Descriptions.Item>
                                    )}
                                    {Number(viewRecord.upiAmount) > 0 && (
                                        <Descriptions.Item label="  — UPI">₹{Number(viewRecord.upiAmount).toFixed(2)}</Descriptions.Item>
                                    )}
                                    {Number(viewRecord.bankAmount) > 0 && (
                                        <Descriptions.Item label="  — Bank">₹{Number(viewRecord.bankAmount).toFixed(2)}</Descriptions.Item>
                                    )}
                                    <Descriptions.Item label="Balance">₹{Number(viewRecord.balanceAmount).toFixed(2)}</Descriptions.Item>
                                </Descriptions>

                                <h4 style={{ marginTop: 24 }}>Items</h4>
                                <Table
                                    dataSource={viewRecord.items}
                                    pagination={false}
                                    rowKey="id"
                                    columns={[
                                        { title: 'Vegetable', dataIndex: ['purchase', 'vegetable', 'name'] },
                                        { title: 'Lot No', dataIndex: ['purchase', 'lotNo'] },
                                        { title: 'Sold By', dataIndex: 'saleUnit' },
                                        { title: 'Qty (Kg/Pcs)', dataIndex: 'quantity' },
                                        { title: 'Bag/Box', render: (r: any) => (r.saleUnit === 'PIECES' || r.saleUnit === 'THAAR') ? '-' : (r.bags ?? '-') },
                                        { title: 'Rate', dataIndex: 'sellingRate' },
                                        { title: 'Total', dataIndex: 'total' },
                                        // {
                                        //     title: 'Actions',
                                        //     render: (_: any, record: any) => {
                                        //         const remainingQty = Number(record.quantity ?? 0);
                                        //         return (
                                        //             <Button
                                        //                 type="link"
                                        //                 danger
                                        //                 icon={<UndoOutlined />}
                                        //                 disabled={record.saleUnit !== 'KG' && Number(record.quantity ?? 0) <= 0 ? Number(record.bags ?? 0) <= 0 : remainingQty <= 0}
                                        //                 onClick={() => {
                                        //                     setSelectedItemToReturn(record);
                                        //                     setReturnModalOpen(true);
                                        //                 }}
                                        //             >
                                        //                 Return
                                        //             </Button>
                                        //         );
                                        //     }
                                        // }
                                    ]}
                                />

                                <h4 style={{ marginTop: 24, marginBottom: 12 }}>Attached Invoice Images</h4>
                                {(() => {
                                    let imgs: string[] = [];
                                    if (viewRecord.images) {
                                        try {
                                            imgs = typeof viewRecord.images === 'string' ? JSON.parse(viewRecord.images) : viewRecord.images;
                                        } catch {
                                            imgs = [];
                                        }
                                    }
                                    const baseUrl = (import.meta.env.VITE_API_BASE_URL || "").replace(/\/$/, "");

                                    if (!imgs || imgs.length === 0) {
                                        return <div style={{ color: '#8c8c8c' }}>No invoice images attached.</div>;
                                    }

                                    return (
                                        <Image.PreviewGroup>
                                            <Space size={[12, 12]} wrap>
                                                {imgs.map((fileName: string, index: number) => {
                                                    const fullUrl = `${baseUrl}/uploads/sales/${fileName}`;
                                                    return (
                                                        <Image
                                                            key={index}
                                                            width={100}
                                                            height={100}
                                                            src={fullUrl}
                                                            style={{ objectFit: 'cover', borderRadius: 6, border: '1px solid #d9d9d9' }}
                                                        />
                                                    );
                                                })}
                                            </Space>
                                        </Image.PreviewGroup>
                                    );
                                })()}
                            </>
                        )}
                    </Spin>
                </Modal>

                <AddSaleReturnModal
                    open={returnModalOpen}
                    selectedItem={selectedItemToReturn}
                    onCancel={() => {
                        setReturnModalOpen(false);
                        setSelectedItemToReturn(null);
                    }}
                    onSuccess={() => {
                        setReturnModalOpen(false);
                        setSelectedItemToReturn(null);
                        // Refresh data (sale balances might have changed)
                        fetchData(pagination.current, pagination.pageSize, searchText, dateRange);
                        // Hide view modal or refresh it. Hiding is safer.
                        setViewOpen(false);
                    }}
                />

                <Modal
                    title="Print Invoice Options"
                    open={printModalOpen}
                    onOk={executePrintInvoice}
                    onCancel={() => {
                        setPrintModalOpen(false);
                        setPdfName("");
                    }}
                    okText="Generate Invoice"
                    confirmLoading={loading}
                >
                    <Form layout="vertical">
                        <Form.Item label="Language">
                            <Select
                                value={printLang}
                                onChange={setPrintLang}
                                options={invoiceLanguages.map((l) => ({ label: l.name, value: l.code }))}
                            />
                        </Form.Item>

                        <Form.Item label="PDF Name">
                            <Input value={pdfName} onChange={(e) => setPdfName(e.target.value)} />
                        </Form.Item>
                        {/* TEMP: Digital signature UI disabled — uncomment below to re-enable
                        <Form.Item label="Include Authorized Signature">
                            <Switch checked={printSign} onChange={setPrintSign} />
                        </Form.Item>
                        */}
                    </Form>
                </Modal>

                {/* MODAL FOR IMAGE UPLOAD PREVIEW */}
                <Modal
                    open={previewOpen}
                    title={previewTitle}
                    footer={null}
                    onCancel={() => setPreviewOpen(false)}
                >
                    <img alt="preview" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </AppContainer>
        </div>
    );
};
