import { useCallback, useEffect, useRef, useState } from "react"
import { Messages } from "../../Components/Notifications/Messages"
import FormHeader from "../PageComponents/FormHeader";
import { useLocation, useNavigate } from "react-router-dom";
import { Button, Checkbox, Form, Input, Tooltip } from "antd";
import { ArrowRightOutlined } from '@ant-design/icons';
import { useDispatch } from "react-redux";
import { changeBreadCrumb } from "../../Features/AppPage/CenterPage";
import { DropDowns } from "../../Components/Forms/DropDown";
import { ExtractDateFormate, getSession, pdfDiv } from "../../Services/Others";
import { getNonConvertedDeliveryChallans, postDeliveryToInvoice } from '../../Features/DeliveryChallan/DeliveryChallan.js';
import { Tables } from "../../Components/Tables/Table.jsx";
import Buttons from "../../Components/Forms/Buttons.jsx";
import { getPaymentOptionsData } from "../../Features/Payment/Paymentoptions/Paymentoptions.js";
import { RadioGrpButton } from "../../Components/Forms/RadioGroup.jsx";
import { FaEye, FaPrint } from "react-icons/fa";
import { DefaultModal } from "../../Components/Modal/DefaultModal.jsx";
import { MdOutlineMail } from "react-icons/md";
import { printDiv } from "../../Services/WSOthers.js";
import DeliveryChallanToInvoicePrint from "./DeliveryChallanToInvoicePrint.jsx";
import { Emailsend } from "../../Features/PurchaseOrder/PurchaseOrder.js";
import './DeliveryChallanToInvoice.scss'
import { getPrintSelectionComponentData, GlobalprintDatas } from "../../Features/ThemeChange/ThemeChange.js";
import { useSelector } from "react-redux";
import { settingDataSelector } from "../../Features/PreferenceMaster/PreferenceMaster.js";
import { printDCToInvoiceStyles } from "./PrintTemplates/printDCToInvoiceStyles.js";
import { getBranchDetail } from "../../Features/BrachLogin/BranchLogin.js";
import { PreferenceData } from "../../Features/BookingScreen/BookingData/BookingData.js";

const subDirectory = import.meta.env.BASE_URL;

const DeliveryChallanToInvoiceForm = () => {

    const [form] = Form.useForm();
    const formRef = useRef(null);
    const location = useLocation();
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const state = location?.state;
    const editstate = state?.editstate;
    const SettingDataSelector = useSelector(PreferenceData);
    const printDatas = useSelector(GlobalprintDatas);
    const AppId = getSession("AppId");
    const BranchId = getSession("BranchId");
    const CompId = getSession("CompId");
    const UserId = getSession("UserId");
    const [page, setPage] = useState(1);
    const [messageType, setMessageType] = useState(null);
    const [messageData, setMessageData] = useState(null);
    const [deliveryChallanData, setDeliveryChallanData] = useState([])
    const [selectedDeliveryChallan, setSelectedDeliveryChallan] = useState(null);
    const [selectedDeliveryChallanData, setSelectedDeliveryChallanData] = useState();
    const [paymentOptions, setPaymentOptions] = useState([]);
    const [selectedPayment, setSelectedPayment] = useState(null);
    const [emailModal, setEmailModal] = useState(false);
    const [printingData, setPrintingData] = useState([]);
    const [showShare, setShowShare] = useState(false);
    const [defaultPrintStyle, setDefaultPrintStyle] = useState(null);
    const [printTrue, setPrintTrue] = useState(false);

    console.log(paymentOptions, "paymentOptions")

    const items = [
        {
            name: 'Home',
            link: `${subDirectory}app-page/home`,
        },
        {
            name: 'Delivery Challan to Invoice',
            link: `${subDirectory}setting/delivery-challan-to-invoice/list`,
        },
    ];

    const columns = [
        {
            title: 'Sl.No',
            key: 'sno',
            align: 'center',
            render: (text, object, index) => (
                <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
            ),
        },
        {
            title: 'Product Name',
            key: 'ProdName',
            dataIndex: 'ProdName',
            width: '150px',
        },
        {
            title: 'Product Variant Name',
            key: 'ProdVariantName',
            dataIndex: 'ProdVariantName',
            width: '200px',
        },
        {
            title: 'Qty',
            key: 'Qty',
            dataIndex: 'Qty',
            align: 'center',
            width: '80px',

        },
        {
            title: 'Product Rate',
            key: 'ProductRate',
            dataIndex: 'ProductRate',
            align: 'center'
        },
        {
            title: 'Convert To Invoice',
            key: 'ConvertToInvoice',
            align: 'center',
            render: (text, record, index) => (
                <Checkbox
                    checked={record?.ConvertToInvoice}
                    onChange={(e) => handleCheckboxChange(e.target.checked, ((page - 1) * 10) + index)}
                />
            ),
        },
    ];

    useEffect(() => {
        dispatch(changeBreadCrumb({ items: items }));
        getDeliveryChallanData();
        getPaymentOptions();
        getDefaultPrintStyle();
    }, [])

    const onComplete = useCallback(() => {
        setMessageData(null);
        setMessageType(null);
    }, []);

    const getDefaultPrintStyle = async () => {
        const { data: res } = await dispatch(getPrintSelectionComponentData({ AppId, CompId, BranchId }))?.unwrap();
        const styleName = res?.data[0]?.ComponentDetails?.find((component) => component?.PrintTypeName === "DC to Invoice" && component?.SetasDefault === 'Y')?.StyleName;
        setDefaultPrintStyle(styleName)
    }

    const getPrintStyle = () => {
        const style = printDCToInvoiceStyles((defaultPrintStyle === undefined || defaultPrintStyle === null) ? 'Style 13' : defaultPrintStyle);
        return style;
    }

    const getPaymentOptions = async () => {
        const { data: res } = await dispatch(getPaymentOptionsData({ AppId, CompId, BranchId }))?.unwrap();

        const paymentData = res?.data[0];

        const filterSalesPayment = paymentData?.PaymentDetails?.filter(
            (item) => item.FlowName?.toLowerCase() === 'sales'
        );

        const filterpaycounter = filterSalesPayment?.[0]?.OptionDetails?.filter(
            (item) => item?.OptionName?.toLowerCase() === 'pay at the counter'
        );

        setPaymentOptions(filterpaycounter?.[0]?.ModeDetails);
        const selectedPaymentOption = filterpaycounter?.[0]?.ModeDetails?.find((payment) => payment?.ModeName === "Cash")?.ModeId
        setSelectedPayment(selectedPaymentOption);
        formRef?.current?.setFieldValue('PaymentOption', selectedPaymentOption);
    }

    const getDeliveryChallanData = async () => {
        const { data: response } = await dispatch(getNonConvertedDeliveryChallans({ AppId, CompId, BranchId })).unwrap();
        setDeliveryChallanData(response?.data)
    }

    const handleDeliveryChallanChange = (value) => {
        formRef?.current?.setFieldValue('DeliveryChallanNo', value);
        setSelectedDeliveryChallan(value)
        if (value !== null && value !== undefined) {
            const data = deliveryChallanData?.find((data) => data?.DCNo === value);
            setSelectedDeliveryChallanData(JSON.parse(JSON.stringify(data)))
        } else {
            setSelectedDeliveryChallanData()
        }
    }

    const handlePageChange = (current) => {
        setPage(current);
    };

    const handleCheckboxChange = (checked, rowIndex) => {
        const updatedData = { ...selectedDeliveryChallanData };
        updatedData.ProductDetails[rowIndex].ConvertToInvoice = checked;
        setSelectedDeliveryChallanData({ ...updatedData });
    };

    const handleChange = (pagination, filters, sorter) => {
        setFilteredInfo(filters);
        setSortedInfo(sorter);
    };

    const handlePrint = async () => {
        setPrintTrue(true);
        const style = getPrintStyle();
        setTimeout(() => {
            printDiv(`delivery-challan-to-invoice-print`, style);
            setPrintTrue(false);
        }, 100);
    }

    const handleEmailShare = async (record) => {
        console.log("record", printingData)
        // alert("This feature is not available yet. Please contact support for assistance.")
        if (record?.CustEmail) {
            setPrintTrue(true);
            setTimeout(async () => {
                try {
                    const style = getPrintStyle();
                    const blob = await pdfDiv('delivery-challan-to-invoice-print', style);
                    console.log(blob, 'blobblob');

                    const payload = {
                        fileBlob: blob,
                        toEmail: record?.CustEmail,
                        type: 'DeliveryChallantoInvoice',
                        messageTemplatesList: [],
                    };

                    const res = await dispatch(Emailsend(payload))?.unwrap();

                    console.log('✅ API Response:', res?.data || res);

                    setMessageData('Email sent successfully');
                    setMessageType('success');
                } catch (error) {
                    console.error('❌ Email send failed:', error);
                    setMessageData('Email failed to send');
                    setMessageType('error');
                } finally {
                    setPrintTrue(false);
                }
            }, 300);
        } else {
            setEmailModal(true);
        }
    };

    const handleSendEmailWithEnteredEmail = async (values) => {
        const record = { ...printingData[0], CustEmail: values.email };
        await handleEmailShare(record);
        setEmailModal(false);
        form.resetFields();
    };

    const onFinish = async (values) => {

        const productDtls = selectedDeliveryChallanData?.ProductDetails?.filter((data) => data?.ConvertToInvoice === true)?.map((product) => ({
            ProdId: product?.ProdId,
            InwardDtlId: product?.InwardDtlId,
            Qty: product?.Qty,
            ProductRate: product?.ProductRate,
            TotalAmount: product?.TotalAmount,
            TaxAmount: product?.TaxAmount,
            TaxId: product?.TaxId,
            GrossTotal: product?.GrossTotal,
            DCDtlId: product?.DCDtlId
        }));

        if (productDtls?.length < 1) {
            setMessageType('error')
            setMessageData('No Product Selected')
            return
        }

        const totalAmountOfProduct = productDtls?.reduce((acc, product) => (acc + product?.TotalAmount), 0);
        const totalTaxAmount = productDtls?.reduce((acc, product) => (acc + product?.TaxAmount), 0);
        const totalGrossTotal = productDtls?.reduce((acc, product) => (acc + product?.GrossTotal), 0);

        const postData = {
            AppId: selectedDeliveryChallanData?.AppId,
            CompId: selectedDeliveryChallanData?.CompId,
            BranchId: selectedDeliveryChallanData?.BranchId,
            DCNo: selectedDeliveryChallanData?.DCNo,
            CustId: selectedDeliveryChallanData?.CustId,
            CustMobile: selectedDeliveryChallanData?.CustMobile,
            TotalAmount: totalAmountOfProduct,
            TaxAmount: totalTaxAmount,
            GrandTotal: totalGrossTotal,
            VehicleNo: selectedDeliveryChallanData?.VehicleNo,
            PaymentMode: selectedPayment,
            CreatedBy: UserId,
            ProductDetails: productDtls
        }

        const { data: res } = await dispatch(postDeliveryToInvoice(postData))?.unwrap();
        const { data: branchData } = await dispatch(getBranchDetail({ BrId: BranchId }))?.unwrap();
        res.InvoiceDetails[0].AddressDetails = branchData?.data;
        if (res?.statusCode === 1) {
            setPrintingData(res?.InvoiceDetails)
            setShowShare(true)
            setMessageType('success')
            setMessageData(res?.response);
            await getDeliveryChallanData();
        } else {
            setMessageType('error')
            setMessageData(res?.response);
        }

        setSelectedDeliveryChallanData();
        setSelectedDeliveryChallan(null)
        formRef?.current?.setFieldValue('DeliveryChallanNo', null);
        console.log(res?.statusCode === 1, "valuesvalues")
    }

    return (
        <div className="pageOverAll">
            <div className="userPage">
                <div className="userPageContent">
                    <Messages
                        messageType={messageType}
                        messageData={messageData}
                        onComplete={onComplete}
                    />
                    <div className="formName dc-to-invoice-header">
                        <FormHeader title={'Delivery Challan to Invoice'} />
                        <div
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '7px',
                                padding: '6px 12px',
                                backgroundColor: '#059645',
                                borderRadius: '8px',
                                color: 'white',
                                cursor: 'pointer',
                                fontFamily: 'Poppins',
                                fontWeight: '400',
                                whiteSpace: "nowrap",
                                fontSize: "15px"
                            }}
                            onClick={() => navigate(`${subDirectory}setting/delivery-challan-to-invoice/list`)}
                        >
                            <FaEye /> <p> View DC to Invoice List</p>
                        </div>
                    </div>

                    <div className="formDiv">
                        <div className="delivery-challan-to-invoice-form">
                            <Form
                                ref={formRef}
                                initialValues={editstate}
                                className="formDivAnt"
                                onFinish={onFinish}
                            >
                                <Form.Item
                                    name={'DeliveryChallanNo'}
                                    rules={[{
                                        required: true,
                                        message: 'Please select Delivery Challan No.'
                                    }]}
                                >
                                    <DropDowns
                                        options={deliveryChallanData?.map((option) => ({
                                            label: option?.DCNo,
                                            value: option?.DCNo
                                        }))}
                                        label={<label className="required">Delivery Challan No.</label>}
                                        onChangeFunction={handleDeliveryChallanChange}
                                        isOnChange={selectedDeliveryChallan}
                                        defaultValue={selectedDeliveryChallan}
                                        valueData={selectedDeliveryChallan}
                                    />
                                </Form.Item>
                                {selectedDeliveryChallanData && <>
                                    <div className="delivery-challan-to-invoice-cust">
                                        <div>
                                            <div>Customer Mobile No:</div>
                                            <div>{selectedDeliveryChallanData?.CustMobile}</div>
                                        </div>
                                        {selectedDeliveryChallanData?.CustName && <div>
                                            <div>Customer Name:</div>
                                            <div>{selectedDeliveryChallanData?.CustName}</div>
                                        </div>}
                                        <div>
                                            <div>Delivery Challan Date:</div>
                                            <div>{ExtractDateFormate(selectedDeliveryChallanData?.DCDate)}</div>
                                        </div>
                                    </div>
                                    <div className="dc-to-invoice-product-table">
                                        <Tables
                                            data={selectedDeliveryChallanData?.ProductDetails}
                                            columns={columns}
                                            pagination={handlePageChange}
                                            onChange={handleChange}
                                        />
                                    </div>
                                    <Form.Item
                                        name={'PaymentOption'}
                                        rules={[{
                                            required: true,
                                            message: 'Please select payment option'
                                        }]}
                                        className="dc-to-invoice-payment-mode"
                                    >
                                        <RadioGrpButton
                                            content={paymentOptions?.map((payment) => ({
                                                value: payment?.ModeId,
                                                label: payment?.ModeName
                                            }))}
                                            defaultSelect={selectedPayment}
                                            Header={<label className="required">Payment Mode:</label>}
                                            onSelectFuntion={(e) => {
                                                formRef?.current?.setFieldValue('PaymentOption', e);
                                                setSelectedPayment(e)
                                            }}
                                        />
                                    </Form.Item>
                                </>}
                                <div className="submitButton">
                                    <Form.Item>
                                        <Buttons
                                            buttonText="SUBMIT"
                                            color="901D77"
                                            icon={<ArrowRightOutlined />}
                                        />
                                    </Form.Item>
                                    {showShare && (
                                        <div className="share-icons-print">
                                            <div>
                                                <Tooltip title={'Share by Email'}>
                                                    <MdOutlineMail
                                                        size={35}
                                                        color="#25D366"
                                                        style={{ cursor: 'pointer' }}
                                                        onClick={() => handleEmailShare(printingData[0])}
                                                    />
                                                </Tooltip>
                                            </div>
                                            <div>
                                                <Tooltip title={'Print'}>
                                                    <FaPrint
                                                        size={30}
                                                        color="#1292EE"
                                                        style={{ cursor: 'pointer' }}
                                                        onClick={handlePrint}

                                                    />
                                                </Tooltip>
                                            </div>
                                        </div>
                                    )}
                                </div>

                            </Form>


                        </div>
                        <DefaultModal
                            width={400}
                            open={emailModal}
                            title="User Mail"
                            handleCancel={() => setEmailModal(false)}
                            footer={false}
                            children={
                                <div>
                                    <Form
                                        form={form}
                                        layout="vertical"
                                        onFinish={handleSendEmailWithEnteredEmail}
                                    >
                                        <Form.Item
                                            label="Mail ID"
                                            name="email"
                                            rules={[
                                                { required: true, message: 'Email is required' },
                                                { type: 'email', message: 'Enter a valid email address' },
                                            ]}
                                        >
                                            <Input 
                                            autoComplete="off"
                                            placeholder="Enter your email" />
                                        </Form.Item>

                                        <Button type="primary" htmlType="submit">
                                            Submit
                                        </Button>
                                    </Form>
                                </div>
                            }
                        />
                        {(printingData?.length > 0 && printTrue) && <div
                            style={{ display: "none" }}
                            id="delivery-challan-to-invoice-print"
                        >
                            <DeliveryChallanToInvoicePrint
                                defaultStyle={defaultPrintStyle}
                                printData={printingData}
                                preference={SettingDataSelector}
                                printDatas={printDatas} />
                        </div>}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default DeliveryChallanToInvoiceForm