import { EnquiryLifecycleStatusEnum, OrderTypeEnum } from "@gtpl/shared-models/enquiry-management"
import { Button, Card, Col, Descriptions, Form, Row, Select, Tabs } from "antd"
import { EnquiriesService } from "libs/shared-services/enquiry-management/src/lib/enquiries-service"
import React, { useEffect, useState } from "react"
import CostSheetFormat from "./cost-sheet-format"
import {FormOutlined, FileDoneOutlined, FileTextOutlined} from '@ant-design/icons'
import { EmployeeRolesEnum } from "@gtpl/shared-models/common-models"
import { useLocation, useParams } from "react-router-dom"

const {Option} = Select
const { TabPane } = Tabs;

// export interface EnquiryCostSheetGenerationProps{
//     enquiryId : number
//     operation: string
// }

export const getCssFromComponent = (fromDoc, toDoc) => {
    Array.from(fromDoc.styleSheets).forEach((styleSheet: any) => {
      if (styleSheet.cssRules) {
        // true for inline styles
        const newStyleElement = toDoc.createElement("style");
        Array.from(styleSheet.cssRules).forEach((cssRule: any) => {
          newStyleElement.appendChild(toDoc.createTextNode(cssRule.cssText));
        });
        toDoc.head.appendChild(newStyleElement);
      }
    });
  };

export const EnquiryCostSheetGeneration = () => {

    const enquiryService = new EnquiriesService()
    const [enquiryNumbers,setEnquiryNumbers] = useState<any[]>([])
    const [enquiryId,setEnquiryId] = useState<number>()
    const logInUser = JSON.parse(localStorage.getItem('role'))
    const [freezeStatus,setFreezeStatus] = useState<boolean>(false)
    const [form] = Form.useForm()
    const [tabDisplay,setTabDisplay] = useState<boolean>(false)
    const [buyertabDisplay,setbuyerTabDisplay] = useState<boolean>(false)
    const {id} = useParams<any>()
    const {operation} = useParams<any>()



    useEffect(() => {
        // getEnquiryNumbers()
        setEnquiryId(id)
        setTabDisplay(true)
        if(operation == 'view'){
            setFreezeStatus(true)
        }else{
            setFreezeStatus(false)
        }
    },[])

    const getEnquiryNumbers = () => {
        enquiryService.getCostSheetEnquiryNumberDropdown().then(res => {
            if(res.status){
                setEnquiryNumbers(res.data)
            }
        })
    }

    const onEnquiryNumberChange =(val,obj) => {
        if(obj?.freezeStatus == 1){
            setFreezeStatus(true)
        }else{
            setFreezeStatus(false)
        }
    }

    // const onGenerate = (val) => {
    //     setEnquiryId(val.enquiryId)
    //     setTabDisplay(true)
    // }

    const resetHandler= () =>{
        form.resetFields()
    }

    const tabDispalyHandler = (val) => {
        setTabDisplay(val)
    }

    const buyerTabDisplay = (val) => {
        console.log(val,'------------------')
        setbuyerTabDisplay(val)
    }

const onPrint = () => {
    const invoiceContent = document.getElementById("print");
    if (invoiceContent) {
        const infoHeading = document.querySelector(".header .ant-collapse-header") as HTMLElement;
        let originalInfoText = '';
        if (infoHeading) {
            originalInfoText = infoHeading.innerText; 
            infoHeading.innerText = "Customer Info"; 
            infoHeading.style.textAlign = "start";
            infoHeading.style.fontWeight = "normal";
        }

        const tables = invoiceContent.getElementsByTagName("table");
        Array.from(tables).forEach((table) => {
            const columns = table.getElementsByTagName("th").length;

            if (columns === 1) {
                table.style.gridTemplateColumns = '1fr 1fr';
            } else if (columns > 1) {
                const colWidth = `repeat(${columns}, 1fr)`;
                table.style.gridTemplateColumns = colWidth;
            }
        });

        let devContent = invoiceContent.innerHTML;

        const printContent = `
            <h3 style="text-align: center;">${devContent}</h3>
        `;

        const printWindow = window.open("", "PRINT", "height=900,width=1600");

        printWindow.document.write(`
            <html>
                <head>
                    <style>
                        @media print {
                            @page {
                                size: A4 portrait;
                                margin: 10mm; 
                            }
                            body {
                                margin: 0;
                                width: 100%;
                                height: auto;
                                font-family: Arial, sans-serif;
                            }
                            .addoverFlow {
                                overflow-y: visible !important; 
                                max-height: none !important;
                            }
                            .ant-row, .ant-col, .ant-collapse, .ant-collapse-item, 
                            .ant-descriptions {
                                padding: 0 !important;
                                margin: 0 !important; 
                            }
                            .ant-descriptions {
                                display: flex;
                                flex-wrap: wrap;
                                margin-top: 15px; 
                            }
                            .ant-descriptions-item {
                                width: calc(25%);
                                margin-top: 10px;
                            }
                            .ant-descriptions-item-label {
                                font-weight: bold;
                                font-size: 16px;
                            }
                            .ant-descriptions-item-content {
                                font-size: 16px;
                            }
                            .ant-descriptions-item-content::before {
                                content: ": "; 
                            } 
                            .header-title {
                                text-align: center;
                                margin: 10px 0; 
                            }
                            .countpage {
                                page-break-before: always; 
                                width: 50%;
                            }
                            .table-column {
                                border-collapse: collapse;
                                font-size: 13px; 
                            }
                            .table-column th,
                            .table-column td{
                                border: 1px solid black; 
                                font-size: 13px;
                                text-align:right;
                                
                            }
                            .table-column th:first-child,
                            .table-column td:first-child {
                                width: 80%;
                                text-align:left !important;
                            }
                            .table-column th:not(:first-child),
                            .table-column td:not(:first-child) {
                                width: calc(80% / (100% - 1));
                            }
                            .bordertable {
                                border: 1px solid black;
                                border-collapse: collapse; 
                                width: 100%; 
                            }
                            .bordertable th,
                            .bordertable td {
                                border: 1px solid black; 
                                padding: 3px;
                            }
                            .align-left{
                                text-align:left !important;
                            }
                        }
                    </style>
                </head>
                <body>
                    ${printContent}
                </body>
            </html>
        `);
        printWindow.document.close();

        setTimeout(() => {
            printWindow.print();
            printWindow.close();

            if (infoHeading) {
                infoHeading.innerText = originalInfoText;
            }
        }, 500);
    }
};


    return(
        <>
        <style>
            {`
            .ant-tabs-nav-wrap{
                margin-top : -12px
            }
            `}
        </style>
        
        <Card title={<span style={{color:'white'}}>Cost Sheet & Approval</span>} style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} size='small' extra={freezeStatus ? (
            <Row justify="end">
            <Button onClick={onPrint}>Print</Button>
             </Row>
        ) : (<></>)}>
            {/* <Form onFinish={onGenerate} form={form}>
                <Row gutter={24}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 8}}>
                    <Form.Item name='enquiryId' label='Enquiry Number'>
                        <Select showSearch allowClear optionFilterProp="children" placeholder='Select Enquiry Number' onChange={onEnquiryNumberChange}>
                            {enquiryNumbers.map(e => {
                                return(
                                    <Option key={e.enquiryId} value={e.enquiryId} freezeStatus={e.freezeStatus}>{e.enquiryNumber}-{e.freezeStatus == 1 ? 'Freezed' : 'UnFreezed'}</Option>
                                )
                            })}
                        </Select>
                    </Form.Item>
                    </Col>
                    {
                        freezeStatus ? (         
                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                            <Form.Item>
                                <Button type='primary' htmlType="submit">Get Cost Sheet</Button>
                            </Form.Item>
                        </Col>
                        ) : (
                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                <Form.Item>
                                    <Button type='primary' htmlType="submit">Generate</Button>
                                </Form.Item>
                            </Col>
                        )
                    }
                </Row>
            </Form> */}
            { tabDisplay? (
                    <Tabs centered size="small">
                    <TabPane key={'1'} tab={<span><FormOutlined />{freezeStatus ? 'Cost Sheet' : 'Quote Price'}</span>}>
                        {enquiryId ? (<CostSheetFormat enquiryId = {enquiryId} tabName='quotePriceUpdate' resetFields={resetHandler} tabDisplay={tabDispalyHandler} freezeStatus={freezeStatus} buyerPriceDisplay={buyerTabDisplay} operation={operation} compId={'print'}/>):(<></>)}
                    </TabPane>
                    {
                        freezeStatus == false ? (<> {
                            !buyertabDisplay ? (<>
                            <TabPane key={'2'} tab={<span><FileTextOutlined/>Buyer Price</span>}>
                        {enquiryId ? (<CostSheetFormat enquiryId = {enquiryId} tabName='buyerPriceUpdate' resetFields={resetHandler} tabDisplay={tabDispalyHandler} freezeStatus={freezeStatus} buyerPriceDisplay={buyerTabDisplay} operation={null} compId={'print'}/>):(<></>)}
                    </TabPane>
                            </>) : (<></>)
                        }
{/*                          
                    {
                        logInUser == EmployeeRolesEnum.ADMIN ? (
                              <TabPane key={'3'} tab={<span><FileDoneOutlined/>Cost Sheet Approval</span>}>
                        {enquiryId ? (<CostSheetFormat enquiryId = {enquiryId} tabName='approval' resetFields={resetHandler} tabDisplay={tabDispalyHandler} freezeStatus={freezeStatus} buyerPriceDisplay={buyerTabDisplay} operation={null} compId={'print'}/>):(<></>)}
                    </TabPane>
    
                        ) : (<></>)
                    } */}
                    {(logInUser === EmployeeRolesEnum.ADMIN || logInUser === EmployeeRolesEnum.SUPER_ADMIN || logInUser === EmployeeRolesEnum.ENQUIRY_PERSON) && (
                                <TabPane
                                    key="3"
                                    tab={
                                    <span>
                                        <FileDoneOutlined />
                                        Cost Sheet Approval
                                    </span>
                                    }
                                >
                                    {enquiryId && (
                                    <CostSheetFormat
                                        enquiryId={enquiryId}
                                        tabName="approval"
                                        resetFields={resetHandler}
                                        tabDisplay={tabDispalyHandler}
                                        freezeStatus={freezeStatus}
                                        buyerPriceDisplay={buyerTabDisplay}
                                        operation={null}
                                        compId="print"
                                    />
                                    )}
                                </TabPane>
                                )}

                        </>) : (<></>)
                    }
                   
                  
                </Tabs>
                ) : (<></>)
            }
           
            
        </Card>
        </>
    )

}

export default EnquiryCostSheetGeneration