import { useEffect, useState, useCallback, useRef } from 'react';
import {
    AutoComplete,
    Button,
    Col,
    DatePicker,
    Descriptions,
    Divider,
    Form,
    Input,
    InputNumber,
    Modal,
    Popconfirm,
    Popover,
    Row,
    Select,
    Space,
    Spin,
    Table,
    Tag,
    Tooltip,
    message,
} from 'antd';
import {
    ArrowLeftOutlined,
    DeleteOutlined,
    EditOutlined,
    EyeOutlined,
    FilePdfOutlined,
    PlusOutlined,
    SaveOutlined,
    SearchOutlined,
    UserAddOutlined,
} from '@ant-design/icons';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';
import dayjs from 'dayjs';

// ─── Types ────────────────────────────────────────────────────────────────────

interface VegetableMaster {
    id: string;
    name: string;
    hsnCode: string;
}

interface CustomerOption {
    id: string;
    name: string;
    value: string; // for AutoComplete
    label: string;
}

// ─── Component ────────────────────────────────────────────────────────────────

const Quotations = () => {
    // ── View toggle: 'list' | 'form' ─────────────────────────────────────────
    const [view, setView] = useState<'list' | 'form'>('list');
    const [editingId, setEditingId] = useState<string | null>(null);
    const [form] = Form.useForm();

    // ── List state ────────────────────────────────────────────────────────────
    const [data, setData] = useState<any[]>([]);
    const [listLoading, setListLoading] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: Number(import.meta.env.VITE_PAGE_SIZE) || 10,
        total: 0,
        totalPages: 0,
    });

    // ── Masters ───────────────────────────────────────────────────────────────
    const [vegetables, setVegetables] = useState<VegetableMaster[]>([]);
    const [purchaseUnits, setPurchaseUnits] = useState<{ label: string; value: string }[]>([]);

    // ── Customer search ───────────────────────────────────────────────────────
    const [customerOptions, setCustomerOptions] = useState<CustomerOption[]>([]);
    const [selectedCustomerId, setSelectedCustomerId] = useState<string | null>(null);
    const [customerSearchValue, setCustomerSearchValue] = useState('');
    const [showManualName, setShowManualName] = useState(false);
    const customerSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

    // ── Form state ────────────────────────────────────────────────────────────
    const [saving, setSaving] = useState(false);
    const [grandTotal, setGrandTotal] = useState(0);
    const [subTotal, setSubTotal] = useState(0);

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

    // ─── Load Purchase Meta for Units ─────────────────────────────────────────
    const fetchPurchaseMeta = useCallback(async () => {
        try {
            const res = await jwtAxios.get(ENDPOINTS.PURCHASE_META);
            if (res.data?.result?.purchaseUnits) {
                setPurchaseUnits(res.data.result.purchaseUnits);
            }
        } catch {
            // silently fail or fallback
        }
    }, []);

    // ─── Load all vegetables for autocomplete ─────────────────────────────────
    const fetchVegetables = useCallback(async () => {
        try {
            const res = await jwtAxios.get(`${ENDPOINTS.VEGETABLES}?limit=500&status=true`);
            const records = res.data?.result?.data || [];
            setVegetables(
                records.map((v: any) => ({
                    id: String(v.id),
                    name: v.name,
                    hsnCode: v.hsnCode || '',
                }))
            );
        } catch {
            /* silently fail — user can still enter manually */
        }
    }, []);

    // ─── Fetch quotation list ─────────────────────────────────────────────────
    const fetchData = useCallback(async (page: number, limit: number, search: string) => {
        setListLoading(true);
        try {
            const res = await jwtAxios.get(
                `${ENDPOINTS.QUOTATIONS}?page=${page}&limit=${limit}&search=${search}`
            );
            const records = res.data?.result?.data || [];
            const meta = res.data?.result?.meta || {};
            setData(records.map((item: any) => ({ key: item.id, ...item })));
            setPagination((prev) => ({
                ...prev,
                current: meta.page ?? page,
                pageSize: meta.limit ?? limit,
                total: meta.total ?? prev.total,
                totalPages: meta.totalPages ?? prev.totalPages,
            }));
        } catch (err: any) {
            message.error(err.response?.data?.message || 'Failed to fetch quotations');
        } finally {
            setListLoading(false);
        }
    }, []);

    // ─── On mount: load vegetables + first page ───────────────────────────────
    useEffect(() => {
        fetchPurchaseMeta();
        fetchVegetables();
        fetchData(1, pagination.pageSize, '');
    }, [fetchPurchaseMeta, fetchVegetables, fetchData, pagination.pageSize]);

    // ─── Customer search (debounced) ──────────────────────────────────────────
    const handleCustomerSearch = useCallback((value: string) => {
        setCustomerSearchValue(value);
        setSelectedCustomerId(null); // clear selection when typing again
        if (customerSearchTimer.current) clearTimeout(customerSearchTimer.current);
        if (!value.trim()) { setCustomerOptions([]); return; }
        customerSearchTimer.current = setTimeout(async () => {
            try {
                const res = await jwtAxios.get(
                    `${ENDPOINTS.CUSTOMERS}?search=${encodeURIComponent(value)}&limit=10`
                );
                const records = res.data?.result?.data || [];
                setCustomerOptions(
                    records.map((c: any) => ({
                        id: String(c.id),
                        name: c.name,
                        value: c.name,
                        label: c.name,
                    }))
                );
            } catch {
                setCustomerOptions([]);
            }
        }, 300);
    }, []);

    const handleCustomerSelect = (value: string, option: any) => {
        setSelectedCustomerId(option.id);
        setCustomerSearchValue(value);
        setShowManualName(false);
        form.setFieldsValue({ customerName: value, searchCustomer: value });
    };

    // ─── Recalculate totals ────────────────────────────────────────────────────
    const recalculate = () => {
        const items: any[] = form.getFieldValue('items') || [];
        let sub = 0;
        items.forEach((item: any, idx: number) => {
            const qty = Number(item?.quantity) || 0;
            const price = Number(item?.price) || 0;
            const amt = qty * price;
            sub += amt;
            // patch individual row amount
            form.setFieldValue(['items', idx, 'amount'], amt ? Number(amt.toFixed(2)) : undefined);
        });
        const extra = Number(form.getFieldValue('extraCharge')) || 0;
        const disc = Number(form.getFieldValue('discount')) || 0;
        const grand = sub + extra - disc;
        setSubTotal(sub);
        setGrandTotal(grand > 0 ? grand : 0);
    };

    // ─── Open create form ──────────────────────────────────────────────────────
    const handleCreate = () => {
        setEditingId(null);
        form.resetFields();
        form.setFieldsValue({
            quotationDate: dayjs(),
            items: [{ unit: 'Kg' }],
            extraCharge: 0,
            discount: 0,
        });
        setCustomerSearchValue('');
        setSelectedCustomerId(null);
        setCustomerOptions([]);
        setShowManualName(false);
        form.setFieldsValue({ searchCustomer: undefined, customerName: undefined });
        setSubTotal(0);
        setGrandTotal(0);
        setView('form');
    };

    // ─── Open edit form ────────────────────────────────────────────────────────
    const handleEdit = async (id: string) => {
        setSaving(true);
        try {
            const res = await jwtAxios.get(`${ENDPOINTS.QUOTATIONS}/${id}`);
            const rec = res.data?.result ?? res.data;

            setEditingId(id);
            const custName = rec.customer?.name || rec.customerName || '';
            setCustomerSearchValue(custName);
            setSelectedCustomerId(rec.customerId ? String(rec.customerId) : null);
            setShowManualName(!rec.customerId);

            form.setFieldsValue({
                searchCustomer: custName,
                customerName: custName,
                quotationDate: dayjs(rec.quotationDate),
                extraCharge: Number(rec.extraCharge) || 0,
                discount: Number(rec.discount) || 0,
                items: (rec.items || []).map((it: any) => ({
                    vegetableId: it.vegetableId ? String(it.vegetableId) : undefined,
                    vegName: it.vegName,
                    hsnCode: it.hsnCode || '',
                    quantity: Number(it.quantity),
                    unit: it.unit || 'Kg',
                    price: Number(it.price),
                    amount: Number(it.amount),
                })),
            });

            // Recalc after a tick so form values settle
            setTimeout(recalculate, 50);
            setView('form');
        } catch (err: any) {
            message.error(err.response?.data?.message || 'Failed to load quotation');
        } finally {
            setSaving(false);
        }
    };

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

    // ─── Delete ────────────────────────────────────────────────────────────────
    const handleDelete = async (id: string) => {
        setListLoading(true);
        try {
            await jwtAxios.delete(`${ENDPOINTS.QUOTATIONS}/${id}`);
            message.success('Quotation deleted');
            fetchData(pagination.current, pagination.pageSize, searchText);
        } catch (err: any) {
            message.error(err.response?.data?.message || 'Failed to delete');
        } finally {
            setListLoading(false);
        }
    };

    // ─── Build payload ────────────────────────────────────────────────────────
    const buildPayload = (values: any) => {
        const items = (values.items || []).map((it: any) => ({
            vegetableId: it.vegetableId ? Number(it.vegetableId) : null,
            vegName: it.vegName,
            hsnCode: it.hsnCode || '',
            quantity: Number(it.quantity),
            unit: it.unit,
            price: Number(it.price),
            amount: Number(it.quantity) * Number(it.price),
        }));

        const sub = items.reduce((s: number, i: any) => s + i.amount, 0);
        const extra = Number(values.extraCharge) || 0;
        const disc = Number(values.discount) || 0;
        const total = sub + extra - disc;

        const finalCustomerName = values.customerName || customerSearchValue;
        if (!finalCustomerName?.trim()) {
            throw new Error('Please select or enter a Customer Name.');
        }

        return {
            customerId: selectedCustomerId ? Number(selectedCustomerId) : null,
            customerName: finalCustomerName,
            quotationDate: values.quotationDate.format('YYYY-MM-DD'),
            amount: sub,
            extraCharge: extra,
            discount: disc,
            totalAmount: total > 0 ? total : 0,
            items,
        };
    };

    // ─── Save draft ────────────────────────────────────────────────────────────
    const handleSaveDraft = async () => {
        try {
            const values = await form.validateFields();
            
            let payload;
            try {
                payload = buildPayload(values);
            } catch (err: any) {
                message.error(err.message);
                return;
            }

            setSaving(true);
            let savedId: string;
            if (editingId) {
                await jwtAxios.put(`${ENDPOINTS.QUOTATIONS}/${editingId}`, payload);
                savedId = editingId;
                message.success('Quotation updated successfully');
            } else {
                const res = await jwtAxios.post(ENDPOINTS.QUOTATIONS, payload);
                savedId = String(res.data?.result?.id || res.data?.id || '');
                setEditingId(savedId);
                message.success('Quotation saved as draft');
            }

            fetchData(1, pagination.pageSize, '');
            setView('list');
        } catch (err: any) {
            if (err?.errorFields) return; // validation error — stay on form
            message.error(err.response?.data?.message || 'Failed to save quotation');
        } finally {
            setSaving(false);
        }
    };

    // ─── Generate PDF ──────────────────────────────────────────────────────────
    const handleGeneratePDF = async () => {
        try {
            const values = await form.validateFields();
            setSaving(true);
            const payload = buildPayload(values);

            let pdfId: string;
            if (editingId) {
                await jwtAxios.put(`${ENDPOINTS.QUOTATIONS}/${editingId}`, payload);
                pdfId = editingId;
            } else {
                const res = await jwtAxios.post(ENDPOINTS.QUOTATIONS, payload);
                pdfId = String(res.data?.result?.id || res.data?.id || '');
                setEditingId(pdfId);
            }

            // Download PDF
            const pdfRes = await jwtAxios.get(ENDPOINTS.QUOTATION_PDF(pdfId), {
                responseType: 'blob',
            });
            const blob = new Blob([pdfRes.data], { type: 'application/pdf' });
            const url = window.URL.createObjectURL(blob);
            const disposition = pdfRes.headers['content-disposition'];
            let fileName = `quotation-${pdfId}.pdf`;
            if (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('PDF downloaded successfully');
            fetchData(1, pagination.pageSize, '');
            setView('list');
        } catch (err: any) {
            if (err?.errorFields) return;
            message.error(err.response?.data?.message || 'Failed to generate PDF');
        } finally {
            setSaving(false);
        }
    };

    // ─── Download PDF from list ────────────────────────────────────────────────
    const handleDownloadPDF = async (id: string, quotationNo: string) => {
        try {
            const res = await jwtAxios.get(ENDPOINTS.QUOTATION_PDF(id), { responseType: 'blob' });
            const blob = new Blob([res.data], { type: 'application/pdf' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `${quotationNo}.pdf`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            message.success('PDF downloaded');
        } catch {
            message.error('Failed to download PDF');
        }
    };

    // ─── Vegetable autocomplete options ────────────────────────────────────────
    const getVegOptions = (inputValue: string) =>
        vegetables
            .filter((v) => v.name.toLowerCase().includes(inputValue.toLowerCase()))
            .slice(0, 15)
            .map((v) => ({ value: v.name, label: v.name, id: v.id, hsnCode: v.hsnCode }));

    // ─── List columns ──────────────────────────────────────────────────────────
    const columns = [
        {
            title: 'Quotation No',
            dataIndex: 'quotationNo',
            render: (v: string) => <span style={{ fontWeight: 600 }}>{v}</span>,
        },
        {
            title: 'Date',
            dataIndex: 'quotationDate',
            render: (d: string) => dayjs(d).format('DD/MM/YYYY'),
        },
        {
            title: 'Customer',
            dataIndex: 'customerName',
            render: (v: string) => v || '-',
        },
        {
            title: 'Amount (₹)',
            dataIndex: 'amount',
            render: (v: any) => Number(v).toFixed(2),
        },
        {
            title: 'Grand Total (₹)',
            dataIndex: 'totalAmount',
            render: (v: any) => (
                <span style={{ fontWeight: 700, color: '#0f6b3e' }}>
                    ₹{Number(v).toFixed(2)}
                </span>
            ),
        },
        {
            title: 'Actions',
            render: (_: any, record: any) => (
                <Space>
                    <Popover content="View">
                        <Button
                            type="link"
                            icon={<EyeOutlined />}
                            onClick={() => handleView(record.id)}
                        />
                    </Popover>
                    <Popover content="Edit">
                        <Button
                            type="link"
                            icon={<EditOutlined />}
                            onClick={() => handleEdit(record.id)}
                        />
                    </Popover>
                    <Popover content="Download PDF">
                        <Button
                            type="link"
                            style={{ color: '#d4380d' }}
                            icon={<FilePdfOutlined />}
                            onClick={() => handleDownloadPDF(record.id, record.quotationNo)}
                        />
                    </Popover>
                    <Popconfirm
                        title="Delete Quotation"
                        description="Are you sure you want to delete this quotation?"
                        okText="Delete"
                        cancelText="Cancel"
                        okButtonProps={{ danger: true }}
                        onConfirm={() => handleDelete(record.id)}
                    >
                        <Button type="link" danger icon={<DeleteOutlined />} />
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    // ─────────────────────────────────────────────────────────────────────────
    // FORM VIEW
    // ─────────────────────────────────────────────────────────────────────────
    if (view === 'form') {
        return (
            <div style={{ minHeight: '100vh', background: '#f0f2f5', padding: '24px' }}>
                {/* ── Page Header ─── */}
                <div
                    style={{
                        background: 'linear-gradient(135deg, #1a3c2e 0%, #0f6b3e 100%)',
                        borderRadius: 16,
                        padding: '20px 28px',
                        marginBottom: 24,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        boxShadow: '0 4px 20px rgba(15,107,62,0.3)',
                    }}
                >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                        <Button
                            icon={<ArrowLeftOutlined />}
                            onClick={() => setView('list')}
                            style={{
                                background: 'rgba(255,255,255,0.15)',
                                border: '1px solid rgba(255,255,255,0.3)',
                                color: '#fff',
                                borderRadius: 8,
                            }}
                        >
                            Back
                        </Button>
                        <div>
                            <h1
                                style={{
                                    color: '#fff',
                                    margin: 0,
                                    fontSize: 22,
                                    fontWeight: 700,
                                    letterSpacing: 1,
                                }}
                            >
                                {editingId ? 'EDIT QUOTATION' : 'CREATE QUOTATION'}
                            </h1>
                            {editingId && (
                                <span style={{ color: 'rgba(255,255,255,0.7)', fontSize: 13 }}>
                                    Editing saved quotation
                                </span>
                            )}
                        </div>
                    </div>
                </div>

                <Form
                    form={form}
                    layout="vertical"
                    onValuesChange={recalculate}
                >
                    {/* ── Quotation Info Card ─── */}
                    <div
                        style={{
                            background: '#fff',
                            borderRadius: 12,
                            padding: '20px 24px',
                            marginBottom: 20,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                            border: '1px solid #e8f4ec',
                        }}
                    >
                        <Row gutter={24} align="middle">
                            <Col xs={24} sm={8}>
                                <div>
                                    <div
                                        style={{
                                            fontSize: 12,
                                            color: '#8c8c8c',
                                            textTransform: 'uppercase',
                                            letterSpacing: 1,
                                            marginBottom: 4,
                                        }}
                                    >
                                        Quotation No
                                    </div>
                                    <div
                                        style={{
                                            fontSize: 18,
                                            fontWeight: 700,
                                            color: '#0f6b3e',
                                        }}
                                    >
                                        {editingId ? `#${editingId}` : 'Auto-generated'}
                                    </div>
                                </div>
                            </Col>
                            <Col xs={24} sm={8}>
                                <Form.Item
                                    name="quotationDate"
                                    label="Date"
                                    rules={[{ required: true, message: 'Select date' }]}
                                    style={{ marginBottom: 0 }}
                                >
                                    <DatePicker
                                        format="DD-MM-YYYY"
                                        style={{ width: '100%' }}
                                        allowClear={false}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    </div>

                    {/* ── Customer Card ─── */}
                    <div
                        style={{
                            background: '#fff',
                            borderRadius: 12,
                            padding: '20px 24px',
                            marginBottom: 20,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                            border: '1px solid #e8f4ec',
                        }}
                    >
                        <div
                            style={{
                                fontSize: 14,
                                fontWeight: 600,
                                color: '#1a3c2e',
                                marginBottom: 16,
                                display: 'flex',
                                alignItems: 'center',
                                gap: 8,
                            }}
                        >
                            <SearchOutlined style={{ color: '#0f6b3e' }} />
                            Customer
                        </div>

                        <Row gutter={24}>
                            <Col xs={24} md={12}>
                                <Form.Item
                                    name="searchCustomer"
                                    label="Search Customer"
                                    style={{ marginBottom: showManualName ? 8 : 0 }}
                                    rules={[
                                        {
                                            required: !showManualName && !selectedCustomerId,
                                            message: 'Please search and select or enter manually',
                                        },
                                    ]}
                                >
                                    <AutoComplete
                                        options={customerOptions}
                                        onSearch={handleCustomerSearch}
                                        onSelect={handleCustomerSelect}
                                        onChange={(val) => setCustomerSearchValue(val)}
                                        placeholder="Type customer name to search..."
                                        allowClear
                                        onClear={() => {
                                            setCustomerSearchValue('');
                                            setSelectedCustomerId(null);
                                            setCustomerOptions([]);
                                            setShowManualName(false);
                                            form.setFieldsValue({ customerName: undefined, searchCustomer: undefined });
                                        }}
                                        style={{ width: '100%' }}
                                        notFoundContent={
                                            customerSearchValue ? (
                                                <div
                                                    style={{
                                                        padding: '8px 12px',
                                                        color: '#8c8c8c',
                                                        fontSize: 13,
                                                    }}
                                                >
                                                    No customer found
                                                </div>
                                            ) : null
                                        }
                                    />
                                </Form.Item>

                                {/* "Not found?" hint */}
                                {customerSearchValue && !selectedCustomerId && (
                                    <div
                                        style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            gap: 8,
                                            marginBottom: 12,
                                        }}
                                    >
                                        <span style={{ fontSize: 13, color: '#8c8c8c' }}>
                                            Customer not found?
                                        </span>
                                        <Button
                                            type="link"
                                            size="small"
                                            icon={<UserAddOutlined />}
                                            style={{ padding: 0, color: '#0f6b3e', fontSize: 13 }}
                                            onClick={() => {
                                                setShowManualName(true);
                                                form.setFieldsValue({
                                                    customerName: customerSearchValue,
                                                    searchCustomer: customerSearchValue,
                                                });
                                            }}
                                        >
                                            Enter manually
                                        </Button>
                                    </div>
                                )}
                            </Col>

                            {/* Manual name input */}
                            {(showManualName || selectedCustomerId) && (
                                <Col xs={24} md={12}>
                                    <Form.Item
                                        name="customerName"
                                        label="Customer Name"
                                        rules={[
                                            { required: true, message: 'Customer name is required' },
                                        ]}
                                        style={{ marginBottom: 0 }}
                                    >
                                        <Input
                                            placeholder="Enter customer name"
                                            readOnly={!!selectedCustomerId}
                                            style={{
                                                background: selectedCustomerId ? '#f6ffed' : '#fff',
                                                borderColor: selectedCustomerId ? '#b7eb8f' : undefined,
                                                fontWeight: selectedCustomerId ? 600 : undefined,
                                            }}
                                            suffix={
                                                selectedCustomerId ? (
                                                    <Tag color="green" style={{ margin: 0 }}>
                                                        From Master
                                                    </Tag>
                                                ) : undefined
                                            }
                                        />
                                    </Form.Item>
                                </Col>
                            )}
                        </Row>
                    </div>

                    {/* ── Items Card ─── */}
                    <div
                        style={{
                            background: '#fff',
                            borderRadius: 12,
                            padding: '20px 24px',
                            marginBottom: 20,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                            border: '1px solid #e8f4ec',
                        }}
                    >
                        <div
                            style={{
                                fontSize: 14,
                                fontWeight: 600,
                                color: '#1a3c2e',
                                marginBottom: 16,
                            }}
                        >
                            Items
                        </div>

                        {/* Header row */}
                        <Row
                            gutter={8}
                            style={{
                                background: '#f6ffed',
                                borderRadius: 8,
                                padding: '8px 12px',
                                marginBottom: 8,
                                border: '1px solid #d9f7be',
                            }}
                        >
                            {[
                                { label: 'Vegetable', span: 6 },
                                { label: 'HSN Code', span: 4 },
                                { label: 'Qty', span: 3 },
                                { label: 'Unit', span: 3 },
                                { label: 'Price / Kg', span: 4 },
                                { label: 'Amount (₹)', span: 3 },
                                { label: '', span: 1 },
                            ].map((col) => (
                                <Col
                                    span={col.span}
                                    key={col.label}
                                    style={{
                                        fontSize: 12,
                                        fontWeight: 600,
                                        color: '#0f6b3e',
                                        textTransform: 'uppercase',
                                        letterSpacing: 0.5,
                                    }}
                                >
                                    {col.label}
                                </Col>
                            ))}
                        </Row>

                        <Form.List name="items">
                            {(fields, { add, remove }) => (
                                <>
                                    {fields.map(({ key, name, ...restField }) => (
                                        <div
                                            key={key}
                                            style={{
                                                background: '#fafcfb',
                                                border: '1px solid #e8f4ec',
                                                borderRadius: 8,
                                                padding: '10px 12px',
                                                marginBottom: 8,
                                                transition: 'border-color 0.2s',
                                            }}
                                        >
                                            <Row gutter={8} align="middle">
                                                {/* Vegetable */}
                                                <Col span={6}>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'vegName']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: 'Required',
                                                            },
                                                        ]}
                                                        style={{ marginBottom: 0 }}
                                                    >
                                                        <AutoComplete
                                                            placeholder="Vegetable name"
                                                            options={getVegOptions(
                                                                form.getFieldValue([
                                                                    'items',
                                                                    name,
                                                                    'vegName',
                                                                ]) || ''
                                                            )}
                                                            filterOption={false}
                                                            onChange={(val) => {
                                                                form.setFieldValue(['items', name, 'vegName'], val);
                                                                
                                                                // Check if it matches a vegetable exactly
                                                                const matched = vegetables.find(v => v.name === val);
                                                                if (matched) {
                                                                    form.setFieldValue(['items', name, 'vegetableId'], matched.id);
                                                                    form.setFieldValue(['items', name, 'hsnCode'], matched.hsnCode || '');
                                                                } else {
                                                                    form.setFieldValue(['items', name, 'vegetableId'], undefined);
                                                                }
                                                            }}
                                                        />
                                                    </Form.Item>
                                                </Col>

                                                {/* HSN Code */}
                                                <Col span={4}>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'hsnCode']}
                                                        style={{ marginBottom: 0 }}
                                                    >
                                                        <Input placeholder="HSN" />
                                                    </Form.Item>
                                                </Col>

                                                {/* Qty */}
                                                <Col span={3}>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'quantity']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: 'Required',
                                                            },
                                                        ]}
                                                        style={{ marginBottom: 0 }}
                                                    >
                                                        <InputNumber
                                                            placeholder="0"
                                                            min={0}
                                                            step={0.5}
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>

                                                {/* Unit */}
                                                <Col span={3}>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'unit']}
                                                        initialValue="KG"
                                                        style={{ marginBottom: 0 }}
                                                    >
                                                        <Select
                                                            options={purchaseUnits.length > 0 ? purchaseUnits : [{ label: 'KG', value: 'KG' }]}
                                                        />
                                                    </Form.Item>
                                                </Col>

                                                {/* Price */}
                                                <Col span={4}>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'price']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: 'Required',
                                                            },
                                                        ]}
                                                        style={{ marginBottom: 0 }}
                                                    >
                                                        <InputNumber
                                                            placeholder="0.00"
                                                            min={0}
                                                            step={0.5}
                                                            prefix="₹"
                                                            style={{ width: '100%' }}
                                                        />
                                                    </Form.Item>
                                                </Col>

                                                {/* Amount (read-only) */}
                                                <Col span={3}>
                                                    <Form.Item
                                                        name={[name, 'amount']}
                                                        style={{ marginBottom: 0 }}
                                                    >
                                                        <InputNumber
                                                            readOnly
                                                            prefix="₹"
                                                            style={{
                                                                width: '100%',
                                                                background: '#f6ffed',
                                                                fontWeight: 600,
                                                                cursor: 'default',
                                                                borderColor: '#b7eb8f',
                                                                color: '#1a3c2e',
                                                            }}
                                                            precision={2}
                                                        />
                                                    </Form.Item>
                                                </Col>

                                                {/* Delete */}
                                                <Col span={1} style={{ textAlign: 'center' }}>
                                                    <Tooltip title="Remove row">
                                                        <Button
                                                            type="text"
                                                            danger
                                                            icon={<DeleteOutlined />}
                                                            onClick={() => {
                                                                remove(name);
                                                                setTimeout(recalculate, 50);
                                                            }}
                                                            style={{ marginTop: 2 }}
                                                        />
                                                    </Tooltip>
                                                </Col>
                                            </Row>
                                        </div>
                                    ))}

                                    <Button
                                        type="dashed"
                                        onClick={() => add({ unit: 'Kg' })}
                                        block
                                        icon={<PlusOutlined />}
                                        style={{
                                            marginTop: 4,
                                            borderColor: '#0f6b3e',
                                            color: '#0f6b3e',
                                            borderRadius: 8,
                                            height: 40,
                                        }}
                                    >
                                        + Add Row
                                    </Button>
                                </>
                            )}
                        </Form.List>
                    </div>

                    {/* ── Totals Card ─── */}
                    <div
                        style={{
                            background: '#fff',
                            borderRadius: 12,
                            padding: '20px 24px',
                            marginBottom: 24,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                            border: '1px solid #e8f4ec',
                        }}
                    >
                        <Row gutter={24} align="middle">
                            <Col xs={24} sm={8}>
                                <Form.Item
                                    name="extraCharge"
                                    label="Extra Charge (₹)"
                                    style={{ marginBottom: 0 }}
                                >
                                    <InputNumber
                                        min={0}
                                        step={0.5}
                                        prefix="₹"
                                        style={{ width: '100%' }}
                                        placeholder="0.00"
                                    />
                                </Form.Item>
                            </Col>
                            <Col xs={24} sm={8}>
                                <Form.Item
                                    name="discount"
                                    label="Discount (₹)"
                                    style={{ marginBottom: 0 }}
                                >
                                    <InputNumber
                                        min={0}
                                        step={0.5}
                                        prefix="₹"
                                        style={{ width: '100%' }}
                                        placeholder="0.00"
                                    />
                                </Form.Item>
                            </Col>
                            <Col xs={24} sm={8}>
                                <Divider
                                    type="vertical"
                                    style={{ height: 40, display: 'none' }}
                                />
                                <div
                                    style={{
                                        background:
                                            'linear-gradient(135deg, #1a3c2e 0%, #0f6b3e 100%)',
                                        borderRadius: 10,
                                        padding: '14px 20px',
                                        textAlign: 'center',
                                    }}
                                >
                                    <div
                                        style={{
                                            color: 'rgba(255,255,255,0.7)',
                                            fontSize: 12,
                                            letterSpacing: 1,
                                            textTransform: 'uppercase',
                                        }}
                                    >
                                        Grand Total
                                    </div>
                                    <div
                                        style={{
                                            color: '#fff',
                                            fontSize: 28,
                                            fontWeight: 800,
                                            letterSpacing: 1,
                                        }}
                                    >
                                        ₹{grandTotal.toFixed(2)}
                                    </div>
                                    <div
                                        style={{
                                            color: 'rgba(255,255,255,0.5)',
                                            fontSize: 12,
                                            marginTop: 2,
                                        }}
                                    >
                                        Subtotal: ₹{subTotal.toFixed(2)}
                                    </div>
                                </div>
                            </Col>
                        </Row>
                    </div>

                    {/* ── Action Buttons ─── */}
                    <div
                        style={{
                            display: 'flex',
                            gap: 12,
                            justifyContent: 'flex-end',
                            flexWrap: 'wrap',
                        }}
                    >
                        <Button
                            size="large"
                            onClick={() => setView('list')}
                            style={{ borderRadius: 8, minWidth: 120 }}
                        >
                            Cancel
                        </Button>
                        <Button
                            size="large"
                            type="default"
                            icon={<SaveOutlined />}
                            loading={saving}
                            onClick={handleSaveDraft}
                            style={{
                                borderRadius: 8,
                                minWidth: 140,
                                borderColor: '#0f6b3e',
                                color: '#0f6b3e',
                            }}
                        >
                            Save Draft
                        </Button>
                        <Button
                            size="large"
                            type="primary"
                            icon={<FilePdfOutlined />}
                            loading={saving}
                            onClick={handleGeneratePDF}
                            style={{
                                borderRadius: 8,
                                minWidth: 160,
                                background:
                                    'linear-gradient(135deg, #1a3c2e 0%, #0f6b3e 100%)',
                                border: 'none',
                                boxShadow: '0 4px 12px rgba(15,107,62,0.4)',
                            }}
                        >
                            Generate PDF
                        </Button>
                    </div>
                </Form>
            </div>
        );
    }

    // ─────────────────────────────────────────────────────────────────────────
    // LIST VIEW
    // ─────────────────────────────────────────────────────────────────────────
    return (
        <div>
            <AppContainer
                title="Quotations"
                headerAction={
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={handleCreate}
                        style={{
                            background:
                                'linear-gradient(135deg, #1a3c2e 0%, #0f6b3e 100%)',
                            border: 'none',
                            borderRadius: 8,
                        }}
                    >
                        Create Quotation
                    </Button>
                }
            >
                {/* Toolbar */}
                <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
                    <Input.Search
                        placeholder="Search by customer or quotation no..."
                        value={searchText}
                        onChange={(e) => setSearchText(e.target.value)}
                        onSearch={(val) => fetchData(1, pagination.pageSize, val)}
                        allowClear
                        style={{ width: 300 }}
                    />
                </div>

                <Table
                    columns={columns}
                    dataSource={data}
                    loading={listLoading}
                    rowKey="id"
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        onChange: (page, pageSize) => fetchData(page, pageSize, searchText),
                    }}
                    scroll={{ x: 'max-content' }}
                />
                <div className="text-center mt-2">
                    <Tag color="cyan">
                        Page {pagination.current} of {pagination.totalPages}
                    </Tag>
                </div>
            </AppContainer>

            {/* ── View Modal ─── */}
            <Modal
                title={
                    <span style={{ fontWeight: 700, color: '#1a3c2e' }}>
                        Quotation — {viewRecord?.quotationNo}
                    </span>
                }
                open={viewOpen}
                onCancel={() => { setViewOpen(false); setViewRecord(null); }}
                footer={
                    viewRecord ? (
                        <Space>
                            <Button
                                icon={<EditOutlined />}
                                onClick={() => {
                                    setViewOpen(false);
                                    handleEdit(viewRecord.id);
                                }}
                            >
                                Edit
                            </Button>
                            <Button
                                type="primary"
                                icon={<FilePdfOutlined />}
                                style={{
                                    background: 'linear-gradient(135deg, #1a3c2e 0%, #0f6b3e 100%)',
                                    border: 'none',
                                }}
                                onClick={() =>
                                    handleDownloadPDF(viewRecord.id, viewRecord.quotationNo)
                                }
                            >
                                Download PDF
                            </Button>
                        </Space>
                    ) : null
                }
                width={780}
            >
                <Spin spinning={viewLoading}>
                    {viewRecord && (
                        <>
                            <Descriptions bordered column={2} size="small">
                                <Descriptions.Item label="Quotation No">
                                    <strong>{viewRecord.quotationNo}</strong>
                                </Descriptions.Item>
                                <Descriptions.Item label="Date">
                                    {dayjs(viewRecord.quotationDate).format('DD/MM/YYYY')}
                                </Descriptions.Item>
                                <Descriptions.Item label="Customer" span={2}>
                                    {viewRecord.customer?.name || viewRecord.customerName || '-'}
                                </Descriptions.Item>
                                <Descriptions.Item label="Subtotal">
                                    ₹{Number(viewRecord.amount).toFixed(2)}
                                </Descriptions.Item>
                                <Descriptions.Item label="Extra Charge">
                                    ₹{Number(viewRecord.extraCharge).toFixed(2)}
                                </Descriptions.Item>
                                <Descriptions.Item label="Discount">
                                    ₹{Number(viewRecord.discount).toFixed(2)}
                                </Descriptions.Item>
                                <Descriptions.Item label="Grand Total">
                                    <span
                                        style={{
                                            fontWeight: 700,
                                            fontSize: 16,
                                            color: '#0f6b3e',
                                        }}
                                    >
                                        ₹{Number(viewRecord.totalAmount).toFixed(2)}
                                    </span>
                                </Descriptions.Item>
                            </Descriptions>

                            <div style={{ marginTop: 20 }}>
                                <div
                                    style={{
                                        fontWeight: 600,
                                        marginBottom: 8,
                                        color: '#1a3c2e',
                                        fontSize: 14,
                                    }}
                                >
                                    Items
                                </div>
                                <Table
                                    dataSource={viewRecord.items || []}
                                    pagination={false}
                                    rowKey={(_, idx) => String(idx)}
                                    size="small"
                                    bordered
                                    columns={[
                                        {
                                            title: '#',
                                            render: (_: any, __: any, idx: number) => idx + 1,
                                            width: 40,
                                        },
                                        { title: 'Vegetable', dataIndex: 'vegName' },
                                        { title: 'HSN Code', dataIndex: 'hsnCode' },
                                        {
                                            title: 'Qty',
                                            dataIndex: 'quantity',
                                            render: (v: any, row: any) =>
                                                `${Number(v).toFixed(2)} ${row.unit || ''}`,
                                        },
                                        {
                                            title: 'Price',
                                            dataIndex: 'price',
                                            render: (v: any) => `₹${Number(v).toFixed(2)}`,
                                        },
                                        {
                                            title: 'Amount',
                                            dataIndex: 'amount',
                                            render: (v: any) => (
                                                <strong>₹{Number(v).toFixed(2)}</strong>
                                            ),
                                        },
                                    ]}
                                />
                            </div>
                        </>
                    )}
                </Spin>
            </Modal>
        </div>
    );
};

export default Quotations;