import React, { FC, useEffect, useState } from 'react';
import { Table, Input, notification, Button } from 'antd';

// import TableSearch from '../Components/TableSearch';
import { Tabs } from 'antd';

// import MyTable from './MyTable';
import styles from "./sellerPriceList.module.scss"
import *as CommonAPI from "../../../pages/api/common";
import { baseUrl } from '../../../constants/urls';
import { useRouter } from 'next/router';
import {
    SearchOutlined
} from "@ant-design/icons";
import { isEmpty } from 'lodash';
import * as XLSX from 'xlsx';
import cx from "classnames"
const tableHeadingStyles = ['#FF5733', '#33FF57', '#5733FF', '#FFFF33'];







const SellerPricingList: FC<any> = ({ backOption, rfqData, loginRes }) => {
    const [filteredData, setFilteredData] = useState();
    const [activeTab, setActiveTab] = useState('1');
    const { TabPane } = Tabs;
    const [tableData, setTableData] = useState<any>([]);
    const rfqSellers = ["L1", "L2", "L3"];
    const isSelectedRfqs: any = [];
    const [particularSeller, setParticularSeller] = useState<any>([]);
    const router = useRouter();
    const [selectedPrice, setSelectedPrice] = useState(null);
    const [selectedOptions, setSelectedOptions] = useState<{ [rfqItemId: string]: string }>({});
    const [sellerSellecedOptions,setSellerSellecedOptions] = useState<{ [rfqItemId: string]: string }>({});



    useEffect(() => {

        CommonAPI.getRequestWithToken(`${baseUrl}/api/customer/rfq-responses/${rfqData.id}?token=true`, loginRes?.token).then((res) => {


            const dataSource: any = Object?.keys(res?.data?.responses).map(key => res?.data?.responses[key]);

            // for (const [sellerId, seller] of dataSource.entries()) {
           
            //     console.log(`Seller ID: ${sellerId}, Seller: ${seller}`);
            // }

            const array_val: any = Object?.keys(res?.data?.responses).map(key => res?.data?.responses[key]);
            const val1 = array_val.findIndex((res: any) => ((res)));
            // console.log(val1, "val1")
            const array_val1 = array_val?.[val1]?.map((item: any) => item.seller_code);
            //  console.log(array_val1, "array_val1")
            for (let index = 0; index < dataSource.length; index++) {
                
                const ele = dataSource[index];
                for (let i = 0; i < ele.length; i++) {
                  
                    if(ele[i].selected_seller == ele[i]?.seller_id){
                        
                        setSelectedOptions((prevSelectedOptions) => ({
                            ...prevSelectedOptions,
                            [ele[i].rfq_item_id]: ele[i].id,
                        }));
                        setSellerSellecedOptions((prevSelectedOptions) => ({
                            ...prevSelectedOptions,
                            [ele[i].rfq_item_id]: ele[i].id,
                        }))
                    }
                    
                }
               
                
                
            }
            setParticularSeller(array_val1)

            setTableData(dataSource);

        })

    }, [activeTab]);

    const handleRadioChange = (rfqItemId: string, sellerId: string) => {
        setSelectedOptions((prevSelectedOptions) => ({
            ...prevSelectedOptions,
            [rfqItemId]: sellerId,
        }));
    };

    const handleRadioChangeSeller = (rfqItemId: string, sellerId: string) => {
        setSellerSellecedOptions((prevSelectedOptions) => ({
            ...prevSelectedOptions,
            [rfqItemId]: sellerId,
        }));
    };


    const selectedSellerPrice = () => {
        if (!isEmpty(sellerSellecedOptions)) {
            const val = Object.values(sellerSellecedOptions);
            const payload={
                rfq_ids:val
            }

            CommonAPI.postRequestWithToken(`${baseUrl}/api/customer/select-rfq-response?token=true`,payload,loginRes?.token).then((res) => {

                notification.success({ message: "Successfully Confirm The Prices" });
                backOption();
                    router.push({
                        pathname: '/customerDashboard/customerDashboard',
                        query: { val: "RFQ List" }

                    })
            });
            return;
            // setSelectedPrice(data.id);
            val.forEach(element => {


                CommonAPI.getRequestWithToken(`${baseUrl}/api/customer/select-rfq-response/${element}?token=true`, loginRes?.token).then((res) => {
                    console.log(res, "res");
                    notification.success({ message: "Selected Price Successfully Submited" });

                    backOption();
                    router.push({
                        pathname: '/customerDashboard/customerDashboard',
                        query: { val: "RFQ List" }

                    })
                })
            });

        } else {
            notification.error({ message: "Please Select Seller Price" });
        }
    }


    const selectedSeller = () => {
        if (!isEmpty(selectedOptions)) {
            const val = Object.values(selectedOptions);
            const payload={
                rfq_ids:val
            }

            CommonAPI.postRequestWithToken(`${baseUrl}/api/customer/select-rfq-response?token=true`,payload,loginRes?.token).then((res) => {
                notification.success({ message: "Successfully Confirm The Prices" });
                backOption();
                    router.push({
                        pathname: '/customerDashboard/customerDashboard',
                        query: { val: "RFQ List" }

                    })
            });
            return;
            // setSelectedPrice(data.id);
            val.forEach(element => {


                CommonAPI.getRequestWithToken(`${baseUrl}/api/customer/select-rfq-response/${element}?token=true`, loginRes?.token).then((res) => {
                    console.log(res, "res");
                    notification.success({ message: "Selected Price Successfully Submited" });

                    backOption();
                    router.push({
                        pathname: '/customerDashboard/customerDashboard',
                        query: { val: "RFQ List" }

                    })
                })
            });

        } else {
            notification.error({ message: "Please Select Least Price" });
        }
    }



    const exportToXLSX = () => {

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet([
            ["", "", "", "L1", "", "", "L2", "", "", "L3", "", ""],
            ['RFQ Item Id', 'Item Name', 'Qty', 'Seller', 'Brand', 'Rate per unit', 'Seller', 'Brand', 'Rate per unit', 'Seller', 'Brand', 'Rate per unit'],
            ...tableData.map((responses: any) => [
                responses[0].rfq_item_id,
                responses[0].name,
                responses[0].quantity,
                ...responses.flatMap((seller: any) => [
                    seller.seller_code,
                    seller.brand,
                    parseFloat(seller.best_price).toFixed(2),
                ]),
            ]),
        ]);
        ws['!merges'] = [
            { s: { r: 0, c: 4 }, e: { r: 0, c: 5 } },

        ]
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        const name_date = new Date().toString().slice(4, 15).replace(/ /g, "_");
        XLSX.writeFile(wb, `L1L2L3Prices_${name_date}.xlsx`);
    };

    const exportToXLSXSeller = () => {

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet([
            ["", "", "", particularSeller?.[0], "", "", particularSeller?.[1], "", "", particularSeller?.[1], "", ""],
            ['RFQ Item Id', 'Item Name', 'Qty', 'Seller', 'Brand', 'Rate per unit', 'Seller', 'Brand', 'Rate per unit', 'Seller', 'Brand', 'Rate per unit'],
            ...tableData.map((responses: any) => [
                responses[0].rfq_item_id,
                responses[0].name,
                responses[0].quantity,
                ...responses.flatMap((seller: any) => [
                    seller.seller_code,
                    seller.brand,
                    parseFloat(seller.best_price).toFixed(2),
                ]),
            ]),
        ]);
        ws['!merges'] = [
            { s: { r: 0, c: 4 }, e: { r: 0, c: 5 } },

        ]
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        const name_date = new Date().toString().slice(4, 15).replace(/ /g, "_");
        XLSX.writeFile(wb, `SelllerPrices_${name_date}.xlsx`);
    };



    

    return (
        <div className={styles.container}>
            <div style={{ padding: '20px', textAlign: 'left', display: 'flex', flexDirection: 'column' }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: '10px', justifyContent: 'space-between' }}>
                    {/* <TableSearch onSearch={handleSearch} /> */}
                    <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ marginLeft: '20px' }}>
                        <TabPane tab="Seller Wise" key="1" />
                        <TabPane tab="L1 ,L2 ,L3 Wise" key="2" />
                    </Tabs>
                    <Button type={"primary"} ghost onClick={backOption}>Back</Button>
                </div>
                <div>
                    {activeTab === '1' && (


                        <div style={{ padding: '5px', backgroundColor: '#f8f9fb' }}>
                            <div className='ant-row my-6'>
                                <div className={"ant-col ant-col-sm-24 ant-col-xl-8"}>
                                    <Input
                                        //   value={value}
                                        placeholder="Search"
                                        style={{ width: 200 }}
                                        allowClear={true}
                                        suffix={<SearchOutlined />}
                                        size={"middle"}

                                    />

<div>
                                    {/* <Button type="primary" onClick={exportToXLSX} style={{ marginRight: "8px" }}>Export List </Button> */}
                                   

                                </div>
                                </div>
                                <div className={"ant-col ant-col-sm-24 ant-col-xl-8"}>
                                    {/* <div className='flex'>
                                        {rfqSellers.map((seller, index) => (
                                            <div key={index} className='flex ml-1'>
                                                <div  className={seller == "L1" ? "l1" : seller == "L2" ? "l2" : "l3"} style={{ width: "30px", height: "30px" }}/>
                                                <th key={index} colSpan={3} style={{ fontSize: "24px" }}>
                                                    {seller}
                                                </th>
                                            </div>
                                        ))}
                                    </div> */}
                                </div>
                                <div className={"ant-col ant-col-sm-24 ant-col-xl-8"}>
                                    <Button type="primary" onClick={exportToXLSXSeller} style={{ marginRight: "8px" }}>Export List </Button>
                                    <Button type="primary" onClick={selectedSellerPrice}>Confirm and Save Price </Button>
                                </div>
                            </div>


                             <table className={cx("table",styles.table_P2)}>
                                <tbody>
                                    <tr>
                                        <th rowSpan={2} className="m100">RFQ Item Id</th>
                                        <th rowSpan={2} className="m100">Item Name</th>
                                        <th rowSpan={2} className="m100">Qty</th>
                                        {particularSeller?.map((seller: any, index: any) => (
                                            <th key={index} colSpan={3} className={index+1 ==1?"l1":index+1==2?"l2":"l3"} style={{textAlign:"center"}} >
                                                <span>{seller}</span>
                                            </th>
                                        ))}

                                        {/* <th colSpan={4} className="l2">
                                            <span>L2</span>
                                        </th>
                                        <th colSpan={4} className="l3">
                                            <span>L3</span>
                                        </th> */}
                                    </tr>
                                    <tr>
                                        {rfqSellers.map((_, index) => (
                                            <React.Fragment key={index}>
                                                
                                                <th className={cx("m100",index == 0 ? "l1" : index == 1 ? "l2" : "l3")}>Seller</th>
                                                <th className={cx("m100",index == 0 ? "l1" : index == 1 ? "l2" : "l3")}>Brand</th>
                                                <th className={cx("m100",index == 0 ? "l1" : index == 1 ? "l2" : "l3")}>Rate per unit</th>

                                            </React.Fragment>
                                        ))}
                                    </tr>



                                    {tableData.map((responses: any, index: any) => {


                                        return (
                                            <tr key={index} style={{padding:"0.5em 0"}}>
                                                <td className="fixed-width m100" style={{lineHeight:2.2}}>
                                                    <a

                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                    >
                                                        {responses[0].rfq_item_id}
                                                    </a>
                                                </td>
                                                {/* Render other columns */}
                                                <td className="fixed-width m100" style={{lineHeight:2.2}}>{responses[0].name}</td>
                                                <td className="fixed-width m100" style={{lineHeight:2.2}}>{responses[0].quantity}</td>
                                                {responses.map((seller: any, sellerId: any) => {


                                                    return (
                                                        <React.Fragment key={sellerId} >
                                                            <>


                                                                {/* Use conditional rendering to check if sellerResponse exists */}


                                                                {/* Render columns */}


                                                                <>
                                                                   
                                                                    <td className="fixed-width m100" style={{lineHeight:2.2}}>
                                                                    <input
                                                                        type="radio"
                                                                        value={seller.id}
                                                                        checked={sellerSellecedOptions[responses[0].rfq_item_id] == seller.id}
                                                                        onChange={() => handleRadioChangeSeller(responses[0].rfq_item_id, seller.id)}
                                                                    />
                                                                    {seller.seller_code}</td>
                                                                    <td id={`response_${seller.id}`} style={{ cursor: 'pointer',lineHeight:2.2 }} className="fixed-width m100">
                                                                        {seller.brand}
                                                                    </td>
                                                                    <td className="fixed-width m100" style={{lineHeight:2.2}}>
                                                                        {parseFloat(seller?.best_price).toFixed(2)}
                                                                    </td>
                                                                </>





                                                            </>
                                                        </React.Fragment>
                                                    )
                                                })}
                                            </tr>
                                        )
                                    })}
                                </tbody>
                            </table>
                        </div>


                    )}
                    {activeTab === '2' && (


                        <div style={{ padding: '5px', backgroundColor: '#f8f9fb', paddingTop: "16px" }}>
                            <div className='flex justify-between mb-4'>
                                <Input
                                    //   value={value}
                                    placeholder="Search"
                                    style={{ width: 200 }}
                                    allowClear={true}
                                    suffix={<SearchOutlined />}
                                    size={"middle"}

                                />
                                <div>
                                    <Button type="primary" onClick={exportToXLSX} style={{ marginRight: "8px" }}>Export List </Button>
                                    <Button type="primary" onClick={selectedSeller}>Confirm and Save Price </Button>

                                </div>
                            </div>

                            <table className={cx("table",styles.table_P2)}>
                                <tbody>
                                    <tr>
                                        <th rowSpan={2}>RFQ Item Id</th>
                                        <th rowSpan={2}>Item Name</th>
                                        <th rowSpan={2}>Qty</th>
                                        <th colSpan={3} className="l1" style={{textAlign:"center"}}>
                                            <span>L1</span>
                                        </th>
                                        <th colSpan={3} className="l2" style={{textAlign:"center"}}>
                                            <span>L2</span>
                                        </th>
                                        <th colSpan={3} className="l3" style={{textAlign:"center"}}>
                                            <span>L3</span>
                                        </th>
                                    </tr>
                                    <tr>
                                        {rfqSellers.map((_, index) => (
                                            <React.Fragment key={index}>
                                               
                                                <th className={cx("m100",index == 0 ? "l1" : index == 1 ? "l2" : "l3")}>Seller</th>
                                                <th className={cx("m100",index == 0 ? "l1" : index == 1 ? "l2" : "l3")}>Brand</th>
                                                <th className={cx("m100",index == 0 ? "l1" : index == 1 ? "l2" : "l3")}>Rate per unit</th>

                                            </React.Fragment>
                                        ))}
                                    </tr>



                                    {tableData.map((responses: any, index: any) => {

                                        return (
                                            <tr key={index}>
                                                <td className="fixed-width m100">
                                                    <a

                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                    >
                                                        {responses[0].rfq_item_id}
                                                    </a>
                                                </td>
                                                {/* Render other columns */}
                                                <td className="fixed-width m100">{responses[0].name}</td>
                                                <td className="fixed-width m100">{responses[0].quantity}</td>
                                                {responses.map((seller: any, sellerId: any) => {


                                                    return (
                                                        <React.Fragment key={sellerId} >
                                                            <>


                                                                {/* Use conditional rendering to check if sellerResponse exists */}


                                                                {/* Render columns */}


                                                                <>
                                                                    
                                                                    <td className="fixed-width m100"><input
                                                                        type="radio"
                                                                        value={seller.id}
                                                                        checked={selectedOptions[responses[0].rfq_item_id] == seller.id}
                                                                        onChange={() => handleRadioChange(responses[0].rfq_item_id, seller.id)}
                                                                    />{seller.seller_code}</td>
                                                                    <td id={`response_${seller.id}`} style={{ cursor: 'pointer' }} className="fixed-width m100">
                                                                        {seller.brand}
                                                                    </td>
                                                                    <td className="fixed-width m100">
                                                                        {parseFloat(seller?.best_price).toFixed(2)}
                                                                    </td>
                                                                </>





                                                            </>
                                                        </React.Fragment>
                                                    )
                                                })}
                                            </tr>
                                        )
                                    })}
                                </tbody>
                            </table>
                        </div>


                    )}
                </div>
            </div>
        </div>
    );
};

export default SellerPricingList;











