import React, { useCallback, useEffect, useState } from 'react';
import './CustomerPurchaseConfirm.scss';
import axios from 'axios';
import { ArrowRightOutlined, DeleteFilled, CheckCircleOutlined } from '@ant-design/icons';
import { Table } from "antd";

const url_string = window.location.href;
const url = new URL(url_string);
const codesParam = url.searchParams.get('code');

import { sessionStore } from '../../../Services/Others';
import Loader from '../../../Components/Loader/Loader';
import { useDispatch } from 'react-redux';
import { CustomerPurchase, getPurchaseLowStock } from '../../../Features/ConfigMasterPage/ConfigMasterPage';
import { Messages } from '../../../Components/Notifications/Messages';
import PurchasePDFPrint from './PurchasePDFPrint';
import { Buttons } from '../../../../ownLib/my-ui-lib';

function CustomerPurchaseConfirm() {
    const apiUrlToken = import.meta.env.ENV_API_URL_TOKEN;
    const dispatch = useDispatch();

    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [products, setProducts] = useState([]);
    const [message, setMessage] = useState({ type: null, data: null });
    const [orderSuccess, setOrderSuccess] = useState(false);
    const [details, setDetails] = useState({
        AppId: "",
        CompId: "",
        BranchId: ""
    });

    const handleOrderSuccess = () => {
        setOrderSuccess(true);
    };

    console.log(products, 'hsbdjhsdjvbsdj');
    useEffect(() => {
        if (!codesParam) {
            setLoading(true);
            return;
        }
        initializeSession();
        getPurchaseData();
    }, []);

    const getPurchaseData = async () => {
        try {
            const response = await dispatch(getPurchaseLowStock(codesParam)).unwrap();
            const list = response?.data?.data;
            setDetails({
                AppId: list?.[0]?.AppId,
                CompId: list?.[0]?.CompId,
                BranchId: list?.[0]?.BranchId
            });
            setProducts(list);
            setLoading(false);
            if (list?.[0]?.LinkStatus === "N") {
                setOrderSuccess(true)
            }

        } catch (error) {
            setLoading(false);
            console.error("❌ Error getting purchase data:", error);
        }
    };

    const initializeSession = async () => {
        try {
            await addSession();
            setLoading(false);
        } catch (error) {
            console.error('❌ Error initializing session:', error);
            setLoading(false);
        }
    };

    const addSession = async () => {
        if (!sessionStorage.getItem('auth')) {
            try {
                const data = { username: '1000000001', password: '1234' };
                const response = await axios.post(`${apiUrlToken}/jwtTokenGenerator`, data, {
                    headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
                });

                const { token } = response?.data;

                if (token) {
                    sessionStorage.setItem('auth', token);
                    sessionStore('LoginType', 'Kiosk');
                }
            } catch (error) {
                console.error('❌ Error adding session:', error);
            }
        }
    };

    const handleRequiredQtyChange = (ProdId, value) => {
        // allow only digits
        if (!/^\d*$/.test(value)) return;

        setProducts((prev) =>
            prev.map((p) =>
                p.ProdId === ProdId ? { ...p, OrderQty: value } : p
            )
        );
    };

    const handleDeleteProduct = (record) => {
        setProducts((prev) => prev?.filter((p) => p.ProdId !== record.ProdId));
    };

    const filteredProducts = products?.filter(p =>
        p.ProdName?.toLowerCase()?.includes(searchTerm?.toLowerCase())
    );

    // const purchasePost = async () => {
    //     if (!products || products.length === 0) return;

    //     const groupedBySupplier = products.reduce((acc, p) => {
    //         const suppId = p.SupplierDetails?.[0]?.SuppId;
    //         if (!acc[suppId]) acc[suppId] = [];
    //         acc[suppId].push(p);
    //         return acc;
    //     }, {});

    //     const payloadArray = Object.values(groupedBySupplier).map(group => {
    //         const firstProduct = group[0];
    //         return {
    //             CompId: firstProduct.CompId,
    //             BranchId: firstProduct.BranchId,
    //             AppId: firstProduct.AppId,
    //             SuppId: firstProduct.SupplierDetails?.[0]?.SuppId,
    //             Remarks: "",
    //             LocationType: firstProduct.SupplierDetails?.[0]?.Type,
    //             CreatedBy: '',
    //             OrderDetails: group.map(p => ({
    //                 ProdId: p.ProdId,
    //                 OrderQty: Number(p.OrderQty || 0),
    //                 ProdVariantName: p.ProdVariantName || ""
    //             }))
    //         };
    //     });

    //     try {
    //         const response = await dispatch(CustomerPurchase(payloadArray)).unwrap();
    //         if (response?.status === 200) {
    //             setOrderId(response?.data?.[0]?.OrderId);
    //             setMessage({ type: 'success', data: "Purchase Order Added Successfully" });
    //             setOrderSuccess(true); 
    //         } else {
    //             setMessage({ type: 'error', data: "Error submitting order" });
    //         }
    //     } catch (error) {
    //         setMessage({ type: 'error', data: error });
    //     }
    // };

    const onComplete = useCallback(() => {
        setMessage({ type: null, data: null });
    }, []);

    const ProductdataColumns = [
        {
            title: 'SI NO',
            dataIndex: 'index',
            key: 'index',
            align: "center",
            render: (_, __, index) => index + 1
        },
        {
            title: 'Product Name',
            dataIndex: 'ProdName',
            key: 'ProdName'
        },
        {
            title: 'Current Qty',
            dataIndex: 'BalanceQty',
            key: 'BalanceQty',
            align: "center",
        },
        {
            title: 'Required Qty',
            dataIndex: 'OrderQty',
            key: 'OrderQty',
            align: "center",
            render: (_, record) => (
                <input
                    type="text"
                    value={record.OrderQty || ""}
                    onChange={(e) =>
                        handleRequiredQtyChange(record.ProdId, e.target.value)
                    }
                    className="CustomerPurchaseConfirm-requiredInput"
                />
            )
        },
        {
            title: 'Action',
            key: 'Action',
            width: '80px',
            align: 'center',
            render: (_, record) => (
                <DeleteFilled
                    style={{ color: '#FF4D4F', cursor: "pointer" }}
                    onClick={() => handleDeleteProduct(record)}
                />
            ),
        },
    ];

    if (loading) {
        return <Loader />;
    }

    return (
        <div className="CustomerPurchaseConfirm-container">
            <Messages
                messageType={message.type}
                messageData={message.data}
                onComplete={onComplete}
            />

            <div className="CustomerPurchaseConfirm-card">
                {orderSuccess ? (
                    <div className="CustomerPurchaseConfirm-success" style={{ textAlign: 'center', marginTop: '50px' }}>
                        <CheckCircleOutlined style={{ fontSize: '60px', color: 'green', marginBottom: '20px' }} />
                        <h2>Order Placed Successfully!</h2>
                        <p>Your purchase order has been submitted.</p>
                    </div>
                ) : (
                    <>
                        {/* <h1 className="CustomerPurchaseConfirm-title">{products?.[0]?.CompName}</h1> */}
                        <h1 className="CustomerPurchaseConfirm-title">Low Stock Products</h1>

                        <div className="supplier-container">
                            <p className="supplier-title">Supplier Details</p>

                            {/* <div className="supplier-row">
                                <span className="supplier-label">Supplier ID</span>
                                <span className="supplier-value">{products?.[0]?.SupplierDetails?.[0]?.SuppId}</span>
                            </div> */}

                            <div className="supplier-row">
                                <span className="supplier-label">Supplier Name</span>
                                <span className="supplier-value">{products?.[0]?.SupplierDetails?.[0]?.SuppName}</span>
                            </div>
                            {products?.[0]?.SupplierDetails?.[0]?.SuppMobile && <div className="supplier-row">
                                <span className="supplier-label">Supplier Mobile</span>
                                <span className="supplier-value">{products?.[0]?.SupplierDetails?.[0]?.SuppMobile}</span>
                            </div>}
                            {products?.[0]?.SupplierDetails?.[0]?.SuppEmail && <div className="supplier-row">
                                <span className="supplier-label">Email</span>
                                <span className="supplier-value">{products?.[0]?.SupplierDetails?.[0]?.SuppEmail}</span>
                            </div>}

                            <div className="supplier-row">
                                <span className="supplier-label">Address</span>
                                <span className="supplier-value">
                                    {products?.[0]?.SupplierDetails?.[0]?.Address1},
                                    {products?.[0]?.SupplierDetails?.[0]?.Address2},
                                    {products?.[0]?.SupplierDetails?.[0]?.City},
                                    {products?.[0]?.SupplierDetails?.[0]?.Dist},
                                    {products?.[0]?.SupplierDetails?.[0]?.State} -
                                    {products?.[0]?.SupplierDetails?.[0]?.Zip}
                                </span>
                            </div>
                        </div>

                        <div className="CustomerPurchaseConfirm-filters">
                            <input
                                type="text"
                                placeholder="Search Product..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="CustomerPurchaseConfirm-search"
                            />
                        </div>

                        {/* TABLE */}
                        <Table
                            rowKey="UniqueId"
                            dataSource={filteredProducts}
                            columns={ProductdataColumns}
                            pagination={{
                                pageSize: 10,
                                onChange: (page) => console.log("Page:", page)
                            }}
                        />

                        {/* Submit */}
                        <div className="CustomerPurchaseConfirm-button">
                            <PurchasePDFPrint
                                appId={details?.AppId}
                                compId={details?.CompId}
                                branchId={details?.BranchId}
                                products={products}
                                codesParam={codesParam}
                                onOrderSuccess={handleOrderSuccess}
                            />
                        </div>
                    </>
                )}
            </div>
        </div>
    );
}

export default CustomerPurchaseConfirm;
