
import { Button, Card, Col, DatePicker, Form, Input, Modal, Row, Select, Table, TableProps, Tag } from 'antd';
import { ColumnProps } from 'antd/es/table';
import { ProdlogService } from 'libs/shared-services/production/src/lib/prod-log.service';
import React, { useEffect, useRef, useState } from 'react';
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { OperationTypeEnum } from 'libs/shared-models/common-models/src/lib/enum/operation-type.enum';
import { JobReportingInfoReq } from '@gtpl/shared-models/production-management';
import moment from 'moment';
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import Link from 'antd/lib/typography/Link';
import { LotDetailView } from '@gtpl/pages/production-management/production-management-components/lot-detail-view';
import { GlobalVariableValues, PassOrFail } from '@gtpl/shared-models/common-models';
import { Excel } from "antd-table-saveas-excel";



const { Option } = Select;
const { Item: FormItem } = Form;

export const ReportingInfo = () => {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const service = new ProdlogService();
  const [data, setData] = useState<any[]>([]);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [lotINo, setLotINo] = useState('lotNumber');
  const [year,setYear]=useState<any>()

  const [form] = Form.useForm();
  const [selectedRange, setSelectedRange] = useState('days');
  const [lotNumbers, setLotNumbers] = useState<any[]>([]);
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  

  const initialDateRange = [moment().subtract(7, 'days'), moment()];


  useEffect(() => {
    form.setFieldsValue({
      dateRange: initialDateRange
    });
    getInfo({
      dateRange: initialDateRange
    });
    fetchLotNumbers();
  }, []);

  const fetchLotNumbers = async () => {
    try {
      const res = await service.getLotNumberDetails();
      if (res.status) {
        setLotNumbers(res.data);
      } else {
        AlertMessages.getErrorMessage(res.internalMessage);
      }
    } catch (err) {
      AlertMessages.getErrorMessage(err.message);
    }
  };

  const getInfo = (values: any = {}) => {
    const req = new JobReportingInfoReq()
    if(form.getFieldValue('lotNumber') != undefined){
      req.lotNumber = form.getFieldValue('lotNumber')
    }
    if(form.getFieldValue('operation') != undefined){
      req.operation = form.getFieldValue('operation') 
    }
    if(form.getFieldValue('status') != undefined){
      req.status = form.getFieldValue('status') 
    }
    if (form.getFieldValue('dateRange') != undefined) {
      req.fromDate = form.getFieldValue('dateRange')[0].format('YYYY-MM-DD');
      req.toDate = form.getFieldValue('dateRange')[1].format('YYYY-MM-DD');
    }
    // if (values.lotNumber) {
    //   req.lotNumber = values.lotNumber;
    // }
    // if (values.operation) {
    //   req.operation = values.operation;
    // }
    
    service.getAllReportingInfo(req).then((res) => {
      if (res.status) {
        setData(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setData([]);
      }
    })
    .catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setData([]);
    });
    
  };

  const goToLotDetailView = (lotNumber: string,year:number) => {
    setLotINo(lotNumber);
    setYear(year)
    console.log("lotNo", lotNumber);
    setIsModalVisible(true)
}
const handleCancel = () => {
  setIsModalVisible(false);
};

  const onReset = () => {
    form.resetFields();
    getInfo({
      dateRange: initialDateRange
    });
  };
  const onFinish = (values: any) => {
    getInfo(values);
  };
  const { RangePicker, MonthPicker } = DatePicker;

  // const handleDateRangeChange = (value) => {
  //   setSelectedRange(value);
  //   form.resetFields(['dateRange']);
  // };

  const renderDatePicker = () => {
    if (selectedRange === 'days') {
      return <RangePicker />;
    } else if (selectedRange === 'months') {
      return <RangePicker picker="month" />;
    } else if (selectedRange === 'years') {
      return <RangePicker picker="year" />;
    }
  };

  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

  });

  function handleSearch(selectedKeys, confirm, dataIndex) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };

    const handleExport = (e: any) => {
    e.preventDefault();

    const currentDate = new Date()
        .toISOString()
        .slice(0, 10)
        .split("-")
        .join("/");

    let rowIndex = 1;
    let exportingColumns: any[] = []
    exportingColumns.push(
        {
            title: "S.No",
            width: 50,
            render: (text, object, index) => {
                if (index == data.length) {
                    return null;
                } else {
                    return rowIndex++;
                }
            }
        },
         
        {
      title: 'Job Number',
      dataIndex: 'jobNumber',
      render:(text)=> text ? text : '-',
    },
    {
      title: 'Previous Operation',
      dataIndex: 'prevOperation',
            render:(text)=> text ? text : '-',
    },
    {
      title: 'Lot Number',
      dataIndex: 'lotNumber',
       render:(text)=> text ? text : '-',
    
    },
    {
      title: 'Operation',
      dataIndex: 'operation',
       render:(text)=> text ? text : '-',

    },
    {
      title: 'Grade',
      dataIndex: 'plannedGrade',
      render:(text)=> text ? text : '-',
    },
    {
      title: 'Input Grade',
      dataIndex: 'inputGrade',
      render:(text)=> text ? text : '-',

    },
    {
      title: 'Output Grade',
      dataIndex: 'outputGrade',
       render:(text)=> text ? text : '-',

    },
    {
      title: 'Input Quantity',
      dataIndex: 'inputQuantity',
      render: (text) => text != null ? Number(text) : '',
    },
    {
      title: 'Output Quality',
      dataIndex: 'outputQuantity',
      render: (text) => text != null ? Number(text) : ''
    },
    {
      title: 'Product',
      dataIndex: 'product',
      render:(text)=> text ? text : '-',
      


    },
    {
      title: 'Is RRP',
      dataIndex: 'isRRP',
      render: (value) => (value === 1 ? 'YES' : 'NO'),
    },
    {
      title: 'Rejection From',
      dataIndex: 'rejectionFrom',
      render: (text) => text != null ? Number(text) : '-'
    },
    {
      title: 'Workstation Type',
      dataIndex: 'workstationType',
      render:(text)=> text ? text : '-',

    },
    {
      title: 'Shift',
      dataIndex: 'shift',
      filters: [
        { text: 'Shift A', value: 'Shift A' },
        { text: 'Shift B', value: 'Shift B' },
        { text: 'Shift C', value: 'Shift C' },
        { text: 'General', value: 'General' }

        ],
    },
    {
      title: 'Year',
      dataIndex: 'year',
      render:(text)=> text ? text : '-',

    },
        
    );





    const excel = new Excel();
    excel.addSheet("Reporting Info");
    excel.addColumns(exportingColumns);
    excel.addDataSource(data);
    excel.saveAs(`Reporting Info-${currentDate}.xlsx`);
};

 const columns: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sNo',
      responsive: ['sm'],
      render: (text, object, index) =>
        (page - 1) * pageSize + (index + 1) + pageSize * (page - 1),
    },
    {
      title: 'Job Number',
      dataIndex: 'jobNumber',
      ...getColumnSearchProps('jobNumber'),
      render:(text)=> text ? text : '-',
      sorter: (a, b) => a.jobNumber?.localeCompare(b.jobNumber),
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Previous Operation',
      dataIndex: 'prevOperation',
      ...getColumnSearchProps('prevOperation'),
            render:(text)=> text ? text : '-',
      sorter: (a, b) => a.prevOperation?.localeCompare(b.prevOperation),
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Lot Number',
      dataIndex: 'lotNumber',
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('lotNumber'),
      sorter: (a, b) => a.lotNumber?.localeCompare(b.lotNumber),
      render: (value, record) =>
        <Link onClick={e => goToLotDetailView(record.lotNumber,record.year)} >{record.lotNumber}-{record.year} </Link>
    },
    {
      title: 'Operation',
      dataIndex: 'operation',
      ...getColumnSearchProps('operation'),
        sorter: (a, b) => a.operation?.localeCompare(b.operation),
      sortDirections: ['descend', 'ascend'],
       render:(text)=> text ? text : '-',

    },
    {
      title: 'Grade',
      dataIndex: 'plannedGrade',
      render:(text)=> text ? text : '-',
    },
    {
      title: 'Input Grade',
      dataIndex: 'inputGrade',
      render:(text)=> text ? text : '-',
       sorter: (a, b) => a.inputGrade - b.inputGrade,
      sortDirections: ['descend', 'ascend'],

    },
    {
      title: 'Output Grade',
      dataIndex: 'outputGrade',
       render:(text)=> text ? text : '-',
      sorter: (a, b) => a.outputGrade?.localeCompare(b.outputGrade),
      sortDirections: ['descend', 'ascend'],

    },
    {
      title: 'Input Quantity',
      dataIndex: 'inputQuantity',
      render: (text) => text != null ? Number(text) : '',
        sorter: (a, b) => a.inputQuantity?.localeCompare(b.inputQuantity),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('inputQuantity')
    },
    {
      title: 'Output Quality',
      dataIndex: 'outputQuantity',
      render: (text) => text != null ? Number(text) : ''
    },
    {
      title: 'Product',
      dataIndex: 'product',
     sorter: (a, b) => a.product?.localeCompare(b.product),
      sortDirections: ['descend', 'ascend'],
      render:(text)=> text ? text : '-',
      ...getColumnSearchProps('product')
      


    },
    {
      title: 'Is RRP',
      dataIndex: 'isRRP',
      render: (value) => (value === 1 ? 'YES' : 'NO'),
    },
    {
      title: 'Rejection From',
      dataIndex: 'rejectionFrom',
      render: (text) => text != null ? Number(text) : '-'
    },
    {
      title: 'Workstation Type',
      dataIndex: 'workstationType',
      ...getColumnSearchProps('workstationType'),
            render:(text)=> text ? text : '-',

    },
    {
      title: 'Shift',
      dataIndex: 'shift',
      filters: [
        { text: 'Shift A', value: 'Shift A' },
        { text: 'Shift B', value: 'Shift B' },
        { text: 'Shift C', value: 'Shift C' },
        { text: 'General', value: 'General' }

        ],

        filterMultiple: false,
    
        onFilter: (value, record) => 
        {
          return record.shift === value;
        },
    },
    {
      title: 'Year',
      dataIndex: 'year',
      ...getColumnSearchProps('year'),
            render:(text)=> text ? text : '-',
      sorter: (a, b) => a.year - b.year,
      sortDirections: ['descend', 'ascend'],

    },
  ];

  return (
    <Card
    title={

        <span style={{ color: "white" }}>Reporting Info</span>
    }
    style={{ textAlign: "center" }}
    headStyle={{ backgroundColor: "#69c0ff", border: 0 }}
    extra={
      <Row>
        {data.length > 0 ? <Button
        onClick={handleExport}
        icon={<DownloadOutlined />}>Get Excel</Button> : null}
        <br/>
       
        <Tag color='red' style={{width:'60px',fontSize:'20px',padding:'5px'}}>
          Fail
        </Tag>
      </Row>
    }
  >
      <Form form={form} layout="vertical" onFinish={onFinish}>
        <Row gutter={24}>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 4 }}>
            <FormItem name='lotNumber' label='Lot Number'
            //  rules={[{ required: true }]}
             >
              <Select placeholder='Select Job Number' allowClear showSearch optionFilterProp='children'>
                {lotNumbers.map((lot) => (
                  <Option key={lot.yearBatch} value={lot.yearBatch}>
                    {lot.yearBatch}
                  </Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <FormItem name='operation' label='Operation' 
            // rules={[{ required: true }]}
            >
              <Select placeholder='Select operation' allowClear >
                  {[
        ...Object.values(OperationTypeEnum).map((operation) => (
          <Option key={operation} value={operation}>
            {operation}
          </Option>
        )),
        <Option key='NON-SOAKED' value='NON-SOAKED'>
          NON-SOAKED
        </Option>
      ]}
              </Select>
            </FormItem>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
            <FormItem name='dateRange' label='Date Range' >
            {renderDatePicker()}
            </FormItem>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
          <Form.Item 
  label="Status" 
  name="status" 
>
  <Select 
    placeholder="Select Status" 
    allowClear
  >
    <Option value={PassOrFail.PASS}>PASS</Option>
    <Option value={PassOrFail.FAIL}>FAIL</Option>
  </Select>
</Form.Item>

          </Col>

          
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 3 }} style={{ marginTop:'29px' }}>
            <Form.Item>
              <Button type="primary" htmlType="submit" >
                Submit
              </Button>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 1 }} style={{ marginTop:'29px' }}>
            <Form.Item>
              <Button type="primary" htmlType="reset" onClick={onReset}>
                Reset
              </Button>
            </Form.Item>
          </Col>

        </Row>
      </Form>
      
      <Table
        className="custom-table-wrapper"
        columns={columns}
        dataSource={data}
        size="small"
       
        // rowKey= 'jobNumber'
        onRow={(record) => ({
          style: {
            backgroundColor: record.result === "FAIL" ? "rgba(255, 0, 0, 0.2)" : "transparent",
          },
        })}
        // onChange={onChange}
      />
       <Modal
                className='print-docket-modal'
                key={'modal' + Date.now()}
                width={'80%'}
                style={{ top: 30, alignContent: 'right' }}
                visible={isModalVisible}
                title={<React.Fragment>
                </React.Fragment>}
                onCancel={handleCancel}
                footer={[

                ]}
            >

                <LotDetailView lotNumber={lotINo} year={year}/>
            </Modal>
    </Card>
  );
};

export default ReportingInfo;
