import { GrnInspectionreq, grnReportreq } from "@gtpl/shared-models/procurement-management";
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Table } from "antd"
import { ColumnsType } from "antd/lib/table";
import React, { useState, useRef, useEffect } from "react";
import Highlighter from 'react-highlight-words';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined,UndoOutlined,DownloadOutlined } from '@ant-design/icons';
import { GrnService } from "@gtpl/shared-services/procurement";
import moment from "moment";
import form from "antd/lib/form";
import { Excel } from 'antd-table-saveas-excel';

export function GrnInspectionReport () {

    
  const [page, setPage] = React.useState(1);
  const [pageSize, setPageSize] = useState<number>(null);
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState(''); 
  const [searchedColumn, setSearchedColumn] = useState('');
  const [data, setData] = useState([]);
  const [poNum, setPoNum] = useState([]);
  const [excelData, setExcelData] = useState([]);
  const { RangePicker } = DatePicker;
  const [form] = Form.useForm();

// const data = [
//     {
//         "grn": "GRN/24/0002",
//         "inspectionData": [
//             {
//                 "reciedQty": "4000.000",
//                 "pass": "2000",
//                 "passWithCondition": "500",
//                 "fail": "1500",
//                 "grnItemId": 1
//             },
//             {
//                 "reciedQty": "400.000",
//                 "pass": "200",
//                 "passWithCondition": "200",

//                 "grnItemId": 2
//             }

//         ],
//         "invoice": "INV-0003",
//         "poNum": "PO23/VD-01/0003",
//         "grnDate": "2024-03-04T18:30:00.000Z"
//     }
// ]
  const service  = new GrnService()
  useEffect(() => {
     getData();
    getAll()
  }, [])
  const getAll = () =>{
service.getGrnReportPoNum ().then((res)=>{
    if(res.status){
        setPoNum(res.data)
    }
    
})
service.getGrnReportExcel ().then((res)=>{
  if(res.status){
      setExcelData(res.data)
  }
  
})
  }
  const getData = () =>{
    const req = new grnReportreq()
    if(form.getFieldValue('po_number') !== undefined){
        req.PoId=form.getFieldValue('po_number')
  
      }
      if (form.getFieldValue('grnDate') !== undefined) {
        req.startDate = (form.getFieldValue('grnDate')[0]).format('YYYY-MM-DD')
      }
      if (form.getFieldValue('grnDate') !== undefined) {
      req.endDate = (form.getFieldValue('grnDate')[1]).format('YYYY-MM-DD')
      }
      if (form.getFieldValue('inv_no') !== undefined) {
        req.invoiceNo=form.getFieldValue('inv_no')
        }else{
          setData([])
        }
service.getGrnReportData (req).then((res)=>{
    if(res.status){
        setData(res.data)
    }else{
      setData([])
    }
})
  }
    const getColumnSearchProps = (dataIndex: string) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
          <div style={{ padding: 8 }}>
            <Input
              ref={searchInput}
              placeholder={`Search ${dataIndex}`}
              value={selectedKeys[0]}
              onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
              style={{ width: 188, marginBottom: 8, display: 'block' }}
            />
            <Button
              type="primary"
              onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
              icon={<SearchOutlined />}
              size="small"
              style={{ width: 90, marginRight: 8 }}
            >
              Search
            </Button>
            <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
              Reset
            </Button>
          </div>
        ),
        filterIcon: filtered => (
          <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
        ),
        onFilter: (value, record) =>
          record[dataIndex]
            ? record[dataIndex]
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase())
            : false,
        onFilterDropdownVisibleChange: visible => {
          if (visible) { setTimeout(() => searchInput.current.select()); }
        },
        render: text =>
          text ? (
            searchedColumn === dataIndex ? (
              <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[searchText]}
                autoEscape
                textToHighlight={text.toString()}
              />
            ) : text
          )
            : null
    
      });
      /**
        * 
        * @param selectedKeys 
        * @param confirm 
        * @param dataIndex 
        */
        function handleSearch(selectedKeys, confirm, dataIndex) {
          confirm();
          setSearchText(selectedKeys[0]);
          setSearchedColumn(dataIndex);
        };
        function handleReset(clearFilters) {
            clearFilters();
            setSearchText('');
          };
          const onFinish = () => {
            getData()
            };
          
            const onReset = () => {
              form.resetFields();
              getData();
            };
          const columns:any= [
            {
                title: 'S No',
                key: 'sno',
                width: '70px',
                responsive: ['sm'],
                render: (text, object, index) => (page - 1) * pageSize + (index + 1)
              },
            {
                title: 'GRN Number',
                dataIndex:"grn",
                align:'left',
                sorter: (a, b) => a.grn.localeCompare(b.grn),
                sortDirections: ['descend', 'ascend'],
                ...getColumnSearchProps('grn')
              },
            {
                title: 'PO Number',
                dataIndex:"poNum",
                align:'left',
                sorter: (a, b) => a.poNum.localeCompare(b.poNum),
                sortDirections: ['descend', 'ascend'],
                // ...getColumnSearchProps('poNum')
              
              },
            {
              title: 'Invoice Number',
              dataIndex:"invoice",
              align:'left', 
              sorter: (a, b) => a.invoice.localeCompare(b.invoice),
              sortDirections: ['descend', 'ascend'],
              // ...getColumnSearchProps('invoice')
            
            },
            {
              title: 'GRN Date',
              dataIndex:"grnDate",
              render: (value) => {
                  return moment(value).format('DD-MM-YYYY')
              }
            },
            {
                title: <div style={{ textAlign: 'center' }}>SO Number</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                // width: 120,
                render: (e) => {
                  const value = e.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {item.soNum || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{value}</div>;
                },
              },
              {
                title: <div style={{ textAlign: 'center' }}>item</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                // width: 120,
                render: (e) => {
                  const value = e.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {item.itemName || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{value}</div>;
                },
              },
              {
                title: <div style={{ textAlign: 'center' }}>Received Quantity</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                 width: '150px',
                render: (rmItems) => {
                  const rmItemCodes = rmItems.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== rmItems.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {Number(item.reciedQty).toLocaleString() || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{rmItemCodes}</div>;
                },
              }, 
              {
                title: <div style={{ textAlign: 'center' }}>PASS</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                width: 120,
                render: (e) => {
                  const value = e.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {Number(item.pass).toLocaleString() || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{value}</div>;
                },
              },
              {
                title: <div style={{ textAlign: 'center' }}>PASS WITH CONDITION</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                width: 120,
                render: (e) => {
                  const value = e.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {Number(item.passWithCondition).toLocaleString() || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{value}</div>;
                },
              },
              {
                title: <div style={{ textAlign: 'center' }}>FAIL</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                width: 120,
                render: (e) => {
                  const value = e.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {Number(item.fail).toLocaleString() || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{value}</div>;
                },
              },
              {
                title: <div style={{ textAlign: 'center' }}>Inspection Date</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                width: 120,
                render: (e) => {
                  const value = e.map((item, index) => (
                    <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                      {moment(item.insDate).format('DD-MM-YYYY') || '-'}
                    </div>
                  ));
                  return <div style={{ display: 'flex', flexDirection: 'column' }}>{value}</div>;
                },
              },
              {
                title: <div style={{ textAlign: 'center' }}>Lead time</div>,
                dataIndex: "inspectionData",
                key: "inspectionData",
                align: 'center',
                width: 120,
                fixed:'right',
                render: (e, rec) => {
                  let todate;
                  let date;
                  let diff;
              
                  const value = e.map((item, index) => {
                    todate = moment(moment(rec.grnDate).format('YYYY-MM-DD'));
                    date = moment(moment(item.insDate).format('YYYY-MM-DD'));
                    diff = (todate - date) / 864e5;
              
                    if (diff < 0) {
                      return (
                        <div style={{ backgroundColor: 'red', display: 'flex', flexDirection: 'column' }}>
                          {rec.grnDate ? diff : '-'}
                        </div>
                      );
                    } else if (diff > 0) {
                      return (
                        <div style={{ backgroundColor: 'yellow', display: 'flex', flexDirection: 'column' }}>
                          {rec.grnDate ? diff : '-'}
                        </div>
                      );
                    } else {
                      return (
                        <div style={{ backgroundColor: 'green', display: 'flex', flexDirection: 'column' }}>
                          {rec.grnDate ? diff : '-'}
                        </div>
                      );
                    }
                  });
              
                  // Return the result of the mapping operation
                  return value;
                }
              }
              
              
                    // <div key={index} style={{ padding: '5px', borderBottom: index !== e.length - 1 ? '1px solid #e8e8e8' : 'none' }}>
                    //   {moment(item.insDate).format('DD-MM-YYYY') || '-'}
                    // </div>
                  // ))
                  
          
  // {
  //     title: "Aging",
  //     dataIndex: "age",
  //     render:(text,record,index) => {        
  //         const todate = moment(moment(record.grnDate).format('YYYY-MM-DD'));
  //        const  date = moment(moment(record.grnDate).format('YYYY-MM-DD')); 
  //         diff = (todate - date) / 864e5;
  //         if(diff < 0) {
  //           diff = -diff;
  //         }
  //       return(
  //         <>
  //         {record.transactionDate ?  diff : '-'}
  //         </>
  //       )
        
  //     }
  //   },
//             // title: <div style={{ textAlign: 'center' }}>Inspection Wise Quantity</div>,
//     dataIndex: 'inspectionData',
//     width:"10%",
//     children :statusColumns,
//     key:'size',
//   },
    
        ];
        const excelColumns:any=[
            {
              title: 'S No',
              key: 'sno',
              
              render: (text, object, index) => (page - 1) * 10 + (index + 1),
              onCell: (record: any) => ({
                rowSpan: record.rowSpan,
              }),
            },
              {
                  title:"Po No",
                  dataIndex:"po_number",
              },
            
              
            {
              title: "GRN Number",
              dataIndex: "grn_no",
              },
            
              {
                  title:"SO Num",
                  dataIndex:"soNum",
                   },
              
                    {
                title:"Invoice Number",
                 dataIndex:"inv_no",
                },
              {
                title:"GRN Date",
              
                dataIndex: "grn_date",
                render: (value) => {
                  return moment(value).format('DD-MM-YYYY')
              }
                },
            {
              title:"Inspection Date",
              dataIndex:"inspectionDate",
          
          
              render: (_, record) => {
                return record.inspectionDate
                  ? moment(record.inspectionDate).format("YYYY-MM-DD")
                  : "-";
              },
          },
          {
            title:"Inspection Pass Qty",
            dataIndex:"PASS",
           
            
          },
          {
          title:"Inspection Pass with condition Qty",
          dataIndex:"PASS_WITH_CONDITION",
          
          },
          {
          title:"Inspection Fail Qty",
          dataIndex:"FAIL",
          
          },
          
          {
          title:"Recieved Quantity",
          dataIndex:"received_quantity",
          
          
          },
          // {
          //   title: 'Lead time',
          //   key: 'grn_date',
          //   render(text, record) {
          //     const obj: any = {
          //       children: (<div style={{ textAlign: 'right' }}>{Math.floor((new Date(moment(record.grn_date).format('YYYY/MM/DD')).getTime() - new Date(moment(record.inspectionDate).format('YYYY/MM/DD')).getTime()) / (1000 * 60 * 60 * 24)) + 1}</div>),
          //       props: {
          //         style: {
          //           background: Math.floor((new Date(moment(record.grn_date).format('YYYY/MM/DD')).getTime() - new Date(moment(record.inspectionDate).format('YYYY/MM/DD')).getTime()) / (1000 * 60 * 60 * 24)) + 1 >= 0 ? "#38f438" : '#f4646c',
          //           color: Math.floor((new Date(moment(record.grn_date).format('YYYY/MM/DD')).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)) + 1 >= 0 ? "black" : 'white'
          //         }
          //       },
          //     };
          //     return obj;
          //   }
          // },
          
              
          ]
          const exportExcel = () => {
            const excel = new Excel();
            excel
              .addSheet('GRN-inspection-report')
              .addColumns(excelColumns)
              .addDataSource(excelData, { str2num: true })
              .saveAs('GRN-inspection.xlsx');
          }
return(
    <Card  title={<span>GRN Inspection Report</span>} style={{textAlign:'center'}} headStyle={{ backgroundColor: '#69c0ff',color:"white", border: 0 }}
    extra={
      <div>
        <Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{marginRight:30}}>
          GET EXCEL
        </Button>
        {/* <Button icon={<FilePdfOutlined  />} onClick={() => { handleExportPDF(); }}>
          Download PDF
        </Button> */}
      </div>
    }>
         <Form form={form} 
        onFinish={onFinish}
        layout="vertical"
        >
        <Row gutter={24}>
        <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Form.Item name="inv_no" label="Invoice No">
              <Select
                showSearch
                placeholder="Select Invoice No"
                optionFilterProp="children"
                allowClear
              >
                {poNum.map((qc: any) => (
                  <Select.Option key={qc.inv_no} value={qc.inv_no}>
                    {qc.inv_no}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>   
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Form.Item name="po_number" label=" PO No">
              <Select
                showSearch
                placeholder="Select PO No"
                optionFilterProp="children"
                allowClear
              >
                {poNum.map((qc: any) => (
                  <Select.Option key={qc.po_id} value={qc.po_id}>
                    {qc.po_number}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>   
          </Col>
         <Col span={6}>
            <Form.Item label="GRN Date" name="grnDate">
              <RangePicker />
            </Form.Item>
          </Col>
       
          <Col xs={12} sm={6} md={4} lg={3} xl={2} style={{marginTop:29}}>
            <Form.Item>
              <Button
                htmlType='submit'
                type="primary"
                style={{marginRight: "15px" }}>
                Get Report
              </Button>
            </Form.Item>
          </Col>
          <Col xs={12} sm={6} md={4} lg={3} xl={2} style={{marginTop:29}}>
            <Form.Item>
              <Button
                // danger
                // icon={<UndoOutlined />}
                type="primary"
                onClick={onReset}
                // style={{ width: "100%" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
          </Row>
          </Form>
        <Table columns={columns} dataSource={data} scroll={{ x: 'max-content',y:'max-concent' }}
                    size='small'
                    pagination={{pageSize:100}}
                    bordered/>
    </Card>
)
}
export default GrnInspectionReport