import { useEffect, useState, useCallback } from 'react';
import {
    Button,
    DatePicker,
    Input,
    Select,
    Space,
    Table,
    Tag,
    message,
    Spin,
    Row,
    Col,
    Card,
} from 'antd';
import {
    DownloadOutlined,
    FilePdfOutlined,
    RedoOutlined,
    SearchOutlined,
    InboxOutlined,
    // CheckCircleOutlined,
    // ClockCircleOutlined,
    // CloseCircleOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { AppContainer } from '../../../components/AppContainer';
import jwtAxios from '../../../api/axiosInstance';
import { ENDPOINTS } from '../../../api/endpoints';
import SummaryCard from '../../../components/SummaryCard';

const ENTITY_LABEL = 'Whole Sale - Lot-wise Sales Report';
const ENTITY_ENDPOINT = ENDPOINTS.SALES_LOT_WISE_REPORT;

interface LotOption {
    lotNo: string;
    vegetableName?: string;
}

interface VegetableOption {
    id: string;
    name: string;
    tamilName?: string;
}

interface LotWiseMeta {
    lots: LotOption[];
    vegetables: VegetableOption[];
}

export const LotWiseSales = () => {
    // Single date filter: default to today's date
    const [selectedDate, setSelectedDate] = useState<Dayjs>(dayjs());
    const [selectedLotNo, setSelectedLotNo] = useState<string>('');
    const [selectedVegetable, setSelectedVegetable] = useState<string | undefined>(undefined);
    const [searchText, setSearchText] = useState<string>('');

    const [data, setData] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [exportLoading, setExportLoading] = useState<boolean>(false);
    const [exportPdfLoading, setExportPdfLoading] = useState<boolean>(false);

    const [meta, setMeta] = useState<LotWiseMeta>({ lots: [], vegetables: [] });
    const [sum, setSum] = useState({
        grand_total: 0,
        total_quantity: 0,
        total_bags: 0,
        total_records: 0,
    });

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

    const fetchMeta = async (dateStr: string) => {
        try {
            const res = await jwtAxios.get(`${ENDPOINTS.SALES_LOT_WISE_META}?date=${dateStr}`);
            const result = res.data?.result || {};
            setMeta({
                lots: result.lots || [],
                vegetables: result.vegetables || [],
            });
        } catch {
            setMeta({ lots: [], vegetables: [] });
        }
    };

    const fetchData = useCallback(
        async (
            page: number = pagination.current,
            limit: number = pagination.pageSize,
            date: Dayjs = selectedDate,
            lotNo: string = selectedLotNo,
            vegetableId: string | undefined = selectedVegetable,
            search: string = searchText
        ) => {
            setLoading(true);
            try {
                const dateStr = date ? date.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD');
                let url = `${ENTITY_ENDPOINT}?page=${page}&limit=${limit}&date=${dateStr}`;

                if (lotNo && lotNo.trim()) {
                    url += `&lotNo=${encodeURIComponent(lotNo.trim())}`;
                }
                if (vegetableId) {
                    url += `&vegetableId=${vegetableId}`;
                }
                if (search && search.trim()) {
                    url += `&search=${encodeURIComponent(search.trim())}`;
                }

                const res = await jwtAxios.get(url);
                const records = res.data?.result?.items || res.data?.result?.data || [];
                const metaInfo = res.data?.result?.meta || {};
                const sumInfo = res.data?.result?.sum || {};

                setData(records.map((item: any, idx: number) => ({ key: item.id || idx, ...item })));
                setPagination((prev) => ({
                    ...prev,
                    current: metaInfo.page ?? page,
                    pageSize: metaInfo.limit ?? limit,
                    total: metaInfo.total ?? prev.total,
                    totalPages: metaInfo.totalPages ?? prev.totalPages,
                }));
                setSum({
                    grand_total: Number(sumInfo.grand_total ?? 0),
                    total_quantity: Number(sumInfo.total_quantity ?? 0),
                    total_bags: Number(sumInfo.total_bags ?? 0),
                    total_records: Number(sumInfo.total_records ?? metaInfo.total ?? 0),
                });
            } catch (err: any) {
                message.error(err.response?.data?.message || 'Failed to fetch lot-wise sales data');
            } finally {
                setLoading(false);
            }
        },
        [pagination.current, pagination.pageSize, selectedDate, selectedLotNo, selectedVegetable, searchText]
    );

    useEffect(() => {
        const todayStr = dayjs().format('YYYY-MM-DD');
        fetchMeta(todayStr);
        fetchData(1, pagination.pageSize, dayjs(), '', undefined, '');
    }, []);

    const handleDateChange = (date: Dayjs | null) => {
        const newDate = date || dayjs();
        setSelectedDate(newDate);
        const dateStr = newDate.format('YYYY-MM-DD');
        fetchMeta(dateStr);
        fetchData(1, pagination.pageSize, newDate, selectedLotNo, selectedVegetable, searchText);
    };

    const handleLotChange = (val: string) => {
        const lot = val || '';
        setSelectedLotNo(lot);
        fetchData(1, pagination.pageSize, selectedDate, lot, selectedVegetable, searchText);
    };

    const handleVegetableChange = (val: string | undefined) => {
        setSelectedVegetable(val);
        fetchData(1, pagination.pageSize, selectedDate, selectedLotNo, val, searchText);
    };

    const handleSearch = (val: string) => {
        setSearchText(val);
        fetchData(1, pagination.pageSize, selectedDate, selectedLotNo, selectedVegetable, val);
    };

    const handleReset = () => {
        const today = dayjs();
        setSelectedDate(today);
        setSelectedLotNo('');
        setSelectedVegetable(undefined);
        setSearchText('');
        fetchMeta(today.format('YYYY-MM-DD'));
        fetchData(1, pagination.pageSize, today, '', undefined, '');
    };

    const handleExportExcel = async () => {
        if (!data || data.length === 0) {
            message.warning('No data available to export');
            return;
        }
        setExportLoading(true);
        try {
            const params = new URLSearchParams();
            if (selectedDate) params.set('date', selectedDate.format('YYYY-MM-DD'));
            if (selectedLotNo) params.set('lotNo', selectedLotNo.trim());
            if (selectedVegetable) params.set('vegetableId', selectedVegetable);
            if (searchText) params.set('search', searchText.trim());

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

            const disposition = response.headers['content-disposition'];
            let fileName = `lot-wise-sales-report-${selectedDate.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('Lot-wise sales report exported to Excel successfully');
        } catch {
            message.error('Failed to export Excel report. Please try again.');
        } finally {
            setExportLoading(false);
        }
    };

    const handleExportPdf = async () => {
        if (!data || data.length === 0) {
            message.warning('No data available to export');
            return;
        }
        setExportPdfLoading(true);
        try {
            const params = new URLSearchParams();
            if (selectedDate) params.set('date', selectedDate.format('YYYY-MM-DD'));
            if (selectedLotNo) params.set('lotNo', selectedLotNo.trim());
            if (selectedVegetable) params.set('vegetableId', selectedVegetable);
            if (searchText) params.set('search', searchText.trim());

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

            const disposition = response.headers['content-disposition'];
            let fileName = `lot-wise-sales-report-${selectedDate.format('YYYY-MM-DD')}.pdf`;
            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/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('Lot-wise sales report exported to PDF successfully');
        } catch {
            message.error('Failed to export PDF report. Please try again.');
        } finally {
            setExportPdfLoading(false);
        }
    };

    const columns = [
        {
            title: 'S.No',
            key: 'sNo',
            width: 65,
            align: 'center' as const,
            render: (_: any, __: any, index: number) =>
                (pagination.current - 1) * pagination.pageSize + index + 1,
        },
        {
            title: 'LOT Number',
            key: 'lotNo',
            width: 140,
            render: (_: any, record: any) => {
                const lot = record.purchase?.lotNo || record.lotNo || '-';
                return (
                    <Tag color="cyan" style={{ fontSize: '13px', fontWeight: 600, padding: '2px 8px' }}>
                        <InboxOutlined style={{ marginRight: 4 }} />
                        {lot}
                    </Tag>
                );
            },
        },
        {
            title: 'Vegetable',
            key: 'vegetable',
            width: 180,
            render: (_: any, record: any) => {
                const veg = record.purchase?.vegetable;
                if (!veg) return record.vegetableName || '-';
                return (
                    <div>
                        <span style={{ fontWeight: 500, color: '#1f2937' }}>{veg.name}</span>
                        {veg.tamilName && (
                            <span style={{ display: 'block', fontSize: '11px', color: '#6b7280' }}>
                                {veg.tamilName}
                            </span>
                        )}
                    </div>
                );
            },
        },
        {
            title: 'Sold Date',
            key: 'invoiceDate',
            width: 110,
            render: (_: any, record: any) => {
                const date = record.sale?.invoiceDate || record.invoiceDate;
                return date ? dayjs(date).format('DD/MM/YYYY') : '-';
            },
        },
        {
            title: 'Invoice No',
            key: 'invoiceNo',
            width: 140,
            render: (_: any, record: any) => {
                const inv = record.sale?.invoiceNo || record.invoiceNo || '-';
                return <span style={{ fontWeight: 500, color: '#2563eb' }}>{inv}</span>;
            },
        },
        {
            title: 'Customer Name',
            key: 'customer',
            width: 200,
            render: (_: any, record: any) => {
                const custName = record.sale?.customer?.name || record.customerName || record.sale?.walkInName || 'Walk-In';
                const isWalkIn = !record.sale?.customer?.name && (record.sale?.walkInName || record.customerName);
                const mobile = record.sale?.customer?.mobileNo || record.sale?.walkInMobile;
                return (
                    <div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span style={{ fontWeight: 600, color: '#111827' }}>{custName}</span>
                            {isWalkIn && <Tag color="orange" style={{ fontSize: '10px' }}>Walk-In</Tag>}
                        </div>
                        {mobile && (
                            <span style={{ fontSize: '11px', color: '#6b7280' }}>
                                📞 {mobile}
                            </span>
                        )}
                    </div>
                );
            },
        },
        {
            title: 'Quantity (KG)',
            dataIndex: 'quantity',
            key: 'quantity',
            width: 120,
            align: 'right' as const,
            render: (val: any) => (
                <span style={{ fontWeight: 600, color: '#047857' }}>
                    {Number(val ?? 0).toFixed(2)}
                </span>
            ),
        },
        {
            title: 'Sold By',
            dataIndex: 'saleUnit',
            key: 'saleUnit',
            width: 90,
            align: 'center' as const,
            render: (val: string) => <Tag color="blue">{val || 'KG'}</Tag>,
        },
        {
            title: 'Bags / Boxes',
            dataIndex: 'bags',
            key: 'bags',
            width: 110,
            align: 'right' as const,
            render: (val: any) => (val != null && Number(val) > 0 ? Number(val).toFixed(2) : '-'),
        },
        {
            title: 'Rate (₹)',
            key: 'rate',
            width: 110,
            align: 'right' as const,
            render: (_: any, record: any) => {
                const qty = Number(record.quantity ?? 0);
                const total = Number(record.total ?? 0);
                const effective = qty > 0 ? total / qty : Number(record.sellingRate ?? 0);
                return `₹${effective.toFixed(2)}`;
            },
        },
        {
            title: 'Total Amount (₹)',
            dataIndex: 'total',
            key: 'total',
            width: 140,
            align: 'right' as const,
            render: (val: any) => (
                <span style={{ fontWeight: 700, color: '#1e40af' }}>
                    ₹{Number(val ?? 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </span>
            ),
        },
        {
            title: 'Supplier',
            key: 'supplier',
            width: 160,
            render: (_: any, record: any) => {
                const sup = record.purchase?.supplier?.name || record.purchase?.cashSupplierName || record.supplierName;
                return sup ? <Tag color="purple">{sup}</Tag> : <span style={{ color: '#9ca3af' }}>-</span>;
            },
        },
    ];

    return (
        <Spin spinning={loading}>
            <AppContainer
                title={ENTITY_LABEL}
                headerAction={
                    <Space wrap>
                        <Button
                            icon={<DownloadOutlined />}
                            style={{ color: '#52c41a', borderColor: '#52c41a' }}
                            loading={exportLoading}
                            onClick={handleExportExcel}
                        >
                            Export Excel
                        </Button>
                        <Button
                            icon={<FilePdfOutlined />}
                            danger
                            loading={exportPdfLoading}
                            onClick={handleExportPdf}
                        >
                            Export PDF
                        </Button>
                        <Button
                            icon={<RedoOutlined />}
                            onClick={handleReset}
                            title="Reset all filters to today"
                        >
                            Reset
                        </Button>
                    </Space>
                }
            >
                {/* Summary Cards */}
                <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Sales Amount"
                            value={sum.grand_total}
                            color="#1677ff"
                            icon={<span style={{ fontSize: 22 }}>💰</span>}
                        />
                    </Col>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Quantity Sold"
                            value={sum.total_quantity}
                            color="#52c41a"
                            icon={<span style={{ fontSize: 22 }}>🥦</span>}
                            showCurrency={false}
                        />
                    </Col>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Bags Sold"
                            value={sum.total_bags}
                            color="#faad14"
                            icon={<span style={{ fontSize: 22 }}>📦</span>}
                            showCurrency={false}
                        />
                    </Col>
                    <Col xs={24} sm={12} md={6}>
                        <SummaryCard
                            label="Total Sales Records"
                            value={sum.total_records}
                            color="#722ed1"
                            icon={<span style={{ fontSize: 22 }}>📋</span>}
                            showCurrency={false}
                        />
                    </Col>
                </Row>

                {/* Filter Controls Card */}
                <Card
                    size="small"
                    style={{
                        marginBottom: 16,
                        backgroundColor: '#f9fafb',
                        borderColor: '#e5e7eb',
                        borderRadius: 8,
                    }}
                >
                    <Row gutter={[12, 12]} align="middle">
                        {/* Single Date Filter - Defaults to Today */}
                        <Col xs={24} sm={12} md={6} lg={5}>
                            <div style={{ marginBottom: 4, fontSize: 12, fontWeight: 600, color: '#4b5563' }}>
                                Select Date:
                            </div>
                            <DatePicker
                                value={selectedDate}
                                onChange={handleDateChange}
                                format="DD/MM/YYYY"
                                allowClear={false}
                                style={{ width: '100%' }}
                            />
                        </Col>

                        {/* LOT Number Filter */}
                        <Col xs={24} sm={12} md={6} lg={6}>
                            <div style={{ marginBottom: 4, fontSize: 12, fontWeight: 600, color: '#4b5563' }}>
                                LOT Number:
                            </div>
                            <Select
                                placeholder="Select or type LOT Number"
                                allowClear
                                showSearch
                                value={selectedLotNo || undefined}
                                onChange={(val) => handleLotChange(val || '')}
                                onSearch={(val) => {
                                    if (val && !meta.lots.some((l) => l.lotNo.toLowerCase() === val.toLowerCase())) {
                                        // Allow free-text typing if desired
                                    }
                                }}
                                style={{ width: '100%' }}
                                options={meta.lots.map((l) => ({
                                    value: l.lotNo,
                                    label: `${l.lotNo}${l.vegetableName ? ` (${l.vegetableName})` : ''}`,
                                }))}
                                filterOption={(input, option) =>
                                    (option?.label as string)?.toLowerCase().includes(input.toLowerCase())
                                }
                            />
                        </Col>

                        {/* Vegetable Filter */}
                        <Col xs={24} sm={12} md={6} lg={5}>
                            <div style={{ marginBottom: 4, fontSize: 12, fontWeight: 600, color: '#4b5563' }}>
                                Vegetable:
                            </div>
                            <Select
                                placeholder="All Vegetables"
                                allowClear
                                showSearch
                                value={selectedVegetable}
                                onChange={handleVegetableChange}
                                style={{ width: '100%' }}
                                options={meta.vegetables.map((v) => ({
                                    value: v.id,
                                    label: `${v.name}${v.tamilName ? ` (${v.tamilName})` : ''}`,
                                }))}
                                filterOption={(input, option) =>
                                    (option?.label as string)?.toLowerCase().includes(input.toLowerCase())
                                }
                            />
                        </Col>

                        {/* Search Input */}
                        <Col xs={24} sm={12} md={6} lg={6}>
                            <div style={{ marginBottom: 4, fontSize: 12, fontWeight: 600, color: '#4b5563' }}>
                                Search Customer / Invoice:
                            </div>
                            <Input.Search
                                placeholder="Search customer, invoice..."
                                allowClear
                                enterButton={<SearchOutlined />}
                                onSearch={handleSearch}
                                defaultValue={searchText}
                                style={{ width: '100%' }}
                            />
                        </Col>

                        {/* Reset button */}
                        <Col xs={24} sm={12} md={4} lg={2} style={{ display: 'flex', alignItems: 'flex-end', paddingTop: 20 }}>
                            <Button onClick={handleReset} icon={<RedoOutlined />}>
                                Reset
                            </Button>
                        </Col>
                    </Row>
                </Card>

                {/* Table */}
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey={(record) => record.id || record.key}
                    scroll={{ x: 1400 }}
                    pagination={{
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '50', '100'],
                        onChange: (page, pageSize) => {
                            fetchData(page, pageSize, selectedDate, selectedLotNo, selectedVegetable, searchText);
                        },
                    }}
                    bordered
                    size="middle"
                />
            </AppContainer>
        </Spin>
    );
};

export default LotWiseSales;
