import { PurchaseProductDetailedReqDto, PurchaseProductFilterReq } from '@gtpl/shared-models/finance';
import { PurchasesProductService } from '@gtpl/shared-services/finance';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col,  Form, Modal, Row, Select, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import {EyeOutlined} from '@ant-design/icons'
import { Link } from 'react-router-dom';
import { ColumnProps } from 'antd/lib/table';


const PurchaseView = () => {

    const purchaseService = new PurchasesProductService()
    const [purchaseViewData, setPurchaseViewData] = useState([])
    const [vendorNames,setVendorNames]=useState([])
    const [invoiceNumber,setInvoiceNumber]=useState([])
    const [unitCodes,setUnitCodes]=useState([])

    const {Option}=Select;
    const [form] = Form.useForm();
    const [modalOpen,setModalOpen] = useState<boolean>(false)
    const [purchaseProductDetailedView, setPurchaseProductDetailedView] = useState<any>();
    const role = JSON.parse(localStorage.getItem('role'))
    const [page,setPage] = useState<number>(1) 


useEffect(()=>{
    getPackStyles();
    getAllVendorNames();
    getAllInvoiceNumbers();
    getAllUnits();
},[])

const getAllVendorNames = (req?:any) => {
    purchaseService.getAllVendorNamesForView(req).then((res) => {
        if (res.status) {
            setVendorNames(res.data)
        }
    })
}

const getAllInvoiceNumbers = (req?:any) => {
    purchaseService.getAllInvoiceNumber(req).then((res) => {
        if (res.status) {
            setInvoiceNumber(res.data)
        }
    })
}

const getAllUnits = () => {
    purchaseService.getAllUnits().then((res) => {
        if (res.status) {
            setUnitCodes(res.data)
        }
    })
}

    const getPackStyles = () => {
        const req = new PurchaseProductFilterReq()
        if (form.getFieldValue('vendorName') !== undefined) {
            req.vendorName = form.getFieldValue('vendorName')
          }
          if (form.getFieldValue('invoiceNum') !== undefined) {
            req.invoiceNum = form.getFieldValue('invoiceNum')
          }
          if (form.getFieldValue('unitId') !== undefined) {
            req.unitId = form.getFieldValue('unitId')
          }

          const loggedInRole = JSON.parse(localStorage.getItem('role'));
          const loggedInUnitId = Number(localStorage.getItem('unit_id'));
      
          if (loggedInRole !== 'SUPERADMIN') {
            req.unitId = loggedInUnitId // Convert number to string
        }
        purchaseService.getViewForAllProducts(req).then((res) => {
            if (res.status) {
                setPurchaseViewData(res.data)
            }else {
                setPurchaseViewData([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    }

    const onReset = () => {
        form.resetFields();
        getPackStyles();
      };

      const Columns2: ColumnProps<any>[]=[
         {
            title: 'S No',
            key: 'sno',
            width: '70px',
            responsive: ['sm'],
            render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },
        {
            title: "Product",
            dataIndex: "productName"
        },
        {
            title: "Pack Style",
            dataIndex: "packingStyleName"
        },
        {
            title: "Lot Number",
            dataIndex: "lotNumber"
        },
        {
            title: "Unit Price",
            dataIndex: "unitPrice"
        },
        {
            title: "Cases",
            dataIndex: "cases"
        },
        {
            title: "Tax%",
            dataIndex: "taxPercentage",
            render: (text: number) => `${text}%`,
        },
        {
            title: "Case Weight",
            dataIndex: "caseWeight"
        },
        {
            title: "Net Weight",
            dataIndex: "netWeight"
        },
        {
            title: "Amount",
            dataIndex: "totalAmount",
        },
    ]

    const Columns: ColumnProps<any>[] = [
         {
            title: 'S No',
            key: 'sno',
            width: '70px',
            responsive: ['sm'],
            render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },
       
        {
            title: "Vendor",
            dataIndex: "vendorName"
        },
        {
            title: "Unit",
            dataIndex: "unitName"
        },
        
        {
            title: "Invoice Number",
            dataIndex: "invoiceNum"
        },
        {
            title: "Company",
            dataIndex: "company"
        },
        {
            title: "Action",
            render:(text,record) => {
                return(
                    <span>                      
                        <Button onClick={() => detailViewHandler(record)}><EyeOutlined/></Button>
                    </span>
                )
            }
            }

    ];

    const detailViewHandler = (rowData) => {
        // setItemsInfo(rowData.)
        getDetailedViewForPurchase(rowData.purchase_id)
        setModalOpen(true)
    }

    const getDetailedViewForPurchase = (purchaseId) => {
        // const req=new SoFormSdfPrintDto()
        purchaseService.getDetailedViewForProductPurchase(new PurchaseProductDetailedReqDto(purchaseId)).then((res) => {
          if (res.status) {
            setPurchaseProductDetailedView(res.data);
          }
        });
      };

  return (
    <div>
        <Card title={<span style={{ color: 'white' }} >Product Purchase View</span>}
            style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
            extra={
                <Link to="/purchase-product-form">
                    <Button 
                        type="primary" 
                        style={{ background: "white", color: "#3C085C" }}
                    >
                        Create
                    </Button>
                </Link>
            }>
            <Form layout='vertical' form={form} onFinish={getPackStyles}>
                <Row gutter={24}>
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item name="vendorName" label="Vendor" >
                            <Select
                                allowClear
                                showSearch
                                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Vendor"

                            >
                                {vendorNames.map(dropData => {
                                    return <Option value={dropData.vendorId}>{dropData.vendorName}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item name="invoiceNum" label="Invoice Number" >
                            <Select
                             allowClear
                             showSearch
                             optionFilterProp="children"
             filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                placeholder="Select Invoice Number"
                                

                            >
                                {invoiceNumber.map(dropData => {
                                    return <Option value={dropData.purchaseId}>{dropData.invoiceNum}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item name="unitId" label="Unit"
                        //  rules={[{ required: true, message: 'Missing Unit' }]}
                         >
                            <Select
                                placeholder="Select Unit"
                                allowClear
                                disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}
                                defaultValue={role == 'SUPERADMIN' ? 'all' : Number(localStorage.getItem('unit_id'))}
                            >
                                {unitCodes.map(dropData => {
                                    return <Option value={dropData.unitCodeId}>{dropData.unitName}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={12} sm={6} md={4} lg={3} xl={3} style={{paddingTop:"25px"}}>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ background: "green", width: "100%" }}
              >
                Search
              </Button>
            </Form.Item>
          </Col>
          <Col xs={12} sm={6} md={4} lg={3} xl={3} style={{paddingTop:"25px"}}>
            <Form.Item>
              <Button
                danger
                // icon={<UndoOutlined />}
                onClick={onReset}
                style={{ width: "100%" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
                </Row>
            </Form>
            <Table columns={Columns} dataSource={purchaseViewData}/>
            <Modal visible={modalOpen} onCancel={() => setModalOpen(false)} width={'80%'} footer={[]}>
                <Table columns={Columns2} dataSource={purchaseProductDetailedView} pagination={false}/>
            </Modal>
        </Card>
    </div>
  )
}

export default PurchaseView