import { useDispatch } from "react-redux";
import { changeOrderCardDetails, CustomerOrderList, getProductsearch } from "../../../../Features/BookingScreen/BookingData/BookingData";
import { useEffect, useState } from "react";
import { ExtractDateFormate, getSession } from "../../../../Services/Others";
import { Tables } from "../../../../Components/Tables/Table";
import { IoEye } from "react-icons/io5";
import { DatePicker, Modal } from "antd";
import dayjs from "dayjs";
import { v4 as uuidv4 } from 'uuid';

const CustomerOrders = ({ CustomerDetails, close }) => {

    const CompId = getSession('CompId');
    const BranchId = getSession('BranchId');
    const AppId = getSession('AppId');
    const { RangePicker } = DatePicker;
    const dispatch = useDispatch();
    const [custpmerOrderData, setCustpmerOrderData] = useState();
    console.log(CustomerDetails, 'CustomerDetails');

    const [page, setpage] = useState(1);
    const [selectedProducts, setSelectedProducts] = useState();
    const [productModal, setProductModal] = useState(false);
    const [selectedRange, setSelectedRange] = useState([dayjs(), dayjs()]);

    useEffect(() => {
        setSelectedRange([dayjs(), dayjs()]);
        customerFetch();
    }, []);

    useEffect(() => {
        if (selectedRange && selectedRange[0] && selectedRange[1]) {
            customerFetch();
        }
    }, [selectedRange]);

    const getApiRange = () => {
        if (!selectedRange || !selectedRange[0] || !selectedRange[1]) return { fromDate: '', toDate: '' };

        return {
            fromDate: selectedRange[0].format('YYYY-MM-DD'),
            toDate: selectedRange[1].format('YYYY-MM-DD'),
        };
    };

    const customerFetch = async () => {
        const { fromDate, toDate } = getApiRange();
        const data = {
            AppId: AppId,
            BranchId: BranchId,
            CompId: CompId,
            MobileNo: CustomerDetails?.value,
            FromDate: fromDate,
            ToDate: toDate,
        }
        const response = await dispatch(CustomerOrderList(data)).unwrap();
        if (response?.data?.statusCode === 1) {
            setCustpmerOrderData(response?.data?.data)
        }
        else {
            setCustpmerOrderData()
        }

    }


    const ViewProductdetails = (products) => {
        setSelectedProducts(products);
        setProductModal(true);
    };
    const handlePageChange = (current) => {
        setpage(current);
    };
    // const handleRowDataClick = (record) => {
    //     dispatch(changeOrderCardDetails(record?.productDetails));
    //     close();
    // };



    const getProductsearchData = async (prodName) => {
        const data = {
            CompId,
            BranchId,
            AppId,
            ProdName: prodName
        }
        const response = await dispatch(getProductsearch(data)).unwrap();
        console.log(response, 'response23232323');

    }

    const handleRowDataClick = (record) => {
        if (!record?.productDetails?.length) return;
        const prodName = record.productDetails[0]?.ProdName;
        getProductsearchData(prodName);

        console.log(record.productDetails[0]?.ProdName, 'record?.productDetails');

        const formattedData = record.productDetails.map((prod) => ({
            ProdCat: prod.ProdCat,
            Type: prod.Type,

            OverallQuantity: prod.OverallQuantity ?? 0,
            ActiveStatus: record.ActiveStatus,

            AvailableFrom: prod.AvailableFrom,
            AvailableTo: prod.AvailableTo,

            Cess: prod.Cess ?? 0,
            HSNCode: prod.HSN ?? null,

            BrandName: prod.BrandName ?? null,
            OpeningQty: prod.OpeningQty ?? 0,
            PartNumber: prod.PartNumber ?? null,

            ProdId: prod.ProdId,
            ProdLogo: prod.ProdLogo ?? null,
            ProdName: prod.ProdName,

            QRCode: prod.QRCode ?? null,
            QtyBasedPrice: prod.QtyBasedPrice ?? null,
            Rack: prod.Rack ?? null,
            Size: prod.Size,

            StockAvailable: prod.StockAvailable ?? null,
            TokenAvailable: prod.TokenAvailable ?? null,

            TaxId: prod.ProdTaxId ?? null,
            TaxPercentage: prod.ProdTaxPercentage ?? 0,
            TaxName: prod.TaxName ?? null,

            UniqueId: prod.UniqueId ?? null,
            UomName: prod.UomName,

            SinglePc: prod.SinglePc ?? null,
            NoOfPcs: prod.NoOfPcs ?? 0,

            ProdVariantName: prod.ProdVariantName ?? null,
            VariantAvailableFrom: prod.VariantAvailableFrom ?? null,
            VariantAvailableTo: prod.VariantAvailableTo ?? null,

            BalanceQty: prod.BalanceQty ?? 0,
            BatchRef: prod.BatchRef ?? null,

            FullProductIdentifierDtls: prod.ProductIdentifierDtls ?? [],

            InwardDate: prod.BookingDate ?? null,
            InwardDtlId: prod.InwardDtlId ?? null,
            InwardId: prod.InwardId ?? null,

            MRP: prod.MRP ?? 0,
            OrderRate: prod.Rate ?? 0,
            SellingPrice: prod.Rate ?? 0,

            SuppId: prod.SuppId ?? null,
            SuppName: prod.SuppName ?? null,

            OverAllPcs: prod.OverAllPcs ?? 0,
            Offer: prod.OfferAmt ?? 0,

            BookingTypeName: prod.BookingTypeName ?? null,
            CounterName: prod.CounterName ?? null,

            DiscountLimitType: prod.DiscountLimitType ?? null,
            DiscountLimit: prod.DiscountLimit ?? 0,

            BookedDate: prod.BookedDate ?? [],
            BalanceBookedQty: prod.BalanceBookedQty ?? null,

            ScaleType: prod.ScaleType ?? "",

            localId: prod.localId ?? uuidv4(),

            OrderQty: prod.SalesQty ?? 0,
            TotalAmt: prod.TotalAmt ?? 0,
            TaxAmt: prod.TaxAmt ?? 0,
            WithoutTaxRate: prod.WithoutTaxRate ?? 0,
        }));

        dispatch(changeOrderCardDetails(formattedData));
        close();
    };


    const columns = [
        {
            title: 'Sl.No',
            key: 'sno',
            align: 'center',
            render: (_, __, index) => (page - 1) * 10 + index + 1,
            onCell: (record) => ({
                onClick: () => handleRowDataClick(record),
                style: { cursor: 'pointer' },
            }),
        },
        {
            title: 'Sales Date',
            dataIndex: 'SalesDate',
            key: 'SalesDate',
            align: 'center',
            render: (text) => ExtractDateFormate(text),
            onCell: (record) => ({
                onClick: () => handleRowDataClick(record),
                style: { cursor: 'pointer' },
            }),
        },
        {
            title: 'Amount',
            dataIndex: 'NetAmount',
            key: 'NetAmount',
            align: 'center',
            onCell: (record) => ({
                onClick: () => handleRowDataClick(record),
                style: { cursor: 'pointer' },
            }),
        },

        {
            title: 'No of Products',
            key: 'productCount',
            align: 'center',
            render: (_, record) => (
                <span
                    style={{ color: '#1292EE', fontSize: '16px', cursor: 'pointer' }}
                    onClick={(e) => {
                        e.stopPropagation(); // 👈 IMPORTANT
                        ViewProductdetails(record.productDetails);
                    }}
                >
                    {record?.productDetails?.length || 0}
                </span>
            ),
        },
    ];

    const productColumns = [
        {
            title: 'Sl.No',
            key: 'sno',
            align: 'center',
            render: (_, __, index) => index + 1,
        },
        {
            title: 'Product Name',
            dataIndex: 'ProdName',
            key: 'ProdName',
            align: 'center',
            render: (_, record) =>
                `${record?.ProdName || '-'}${record?.UomName ? ` ${record.Size + record.UomName}` : ''}`,
        },
        {
            title: 'Qty',
            dataIndex: 'SalesQty',
            key: 'SalesQty',
            align: 'center',
            render: (_, record) =>
                record?.SalesQty || '-',
        },
        {
            title: 'Variant',
            key: 'ProdVariantName',
            align: 'ProdVariantName',
            render: (_, record) =>
                record?.ProdVariantName || '-',
        },
        {
            title: 'Rate',
            key: 'Rate',
            align: 'right',
            render: (_, record) =>
                record?.Rate || 0,
        },
        {
            title: 'MRP',
            key: 'MRP',
            align: 'right',
            render: (_, record) =>
                record?.MRP || 0,
        },
    ];

    const disableFutureDates = (current) => {
        return current && current > dayjs().endOf('day');
    };
    const onRangeChange = (dates) => {
        setSelectedRange(dates);
    };
    const getRangePickerValue = () => selectedRange || [dayjs(), dayjs()];


    return (
        <>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div>
                    <p>Customer Name : {CustomerDetails?.CustName}</p>
                    <p>Customer Name : {CustomerDetails?.value}</p>
                </div>
                <div className='fromlabelDate'>
                    <label>Select Date</label>
                    <RangePicker
                        onChange={onRangeChange}
                        format="DD-MMM-YYYY" // display format
                        disabledDate={disableFutureDates}
                        inputReadOnly={true}
                        value={getRangePickerValue()}
                    />
                </div>
            </div>

            <div className="reportTable">
                <Tables
                    columns={columns}
                    data={custpmerOrderData}
                    dataSource={custpmerOrderData}
                    pagination={handlePageChange}
                />{' '}


                <Modal
                    open={productModal}
                    title="Product Details"
                    width={700}
                    footer={null}
                    onCancel={() => setProductModal(false)}
                >
                    <Tables
                        columns={productColumns}
                        data={selectedProducts}
                        pagination={false}
                    />
                </Modal>

            </div>
        </>
    )
}

export default CustomerOrders;