
import React, { useContext, useEffect, useRef, useState } from 'react';
import { ColumnProps } from 'antd/lib/table';
import { SearchOutlined, UndoOutlined, FileExcelFilled } from '@ant-design/icons';
import { Row, Col, Table,Input, Button, Card, Form,message, Select } from 'antd';
import { Link } from 'react-router-dom';
import {Excel} from 'antd-table-saveas-excel'
import Highlighter from 'react-highlight-words';
import moment from 'moment';
import { DeheadingFilterReq, DeheadingPeelingRequest, PeelingRateBasedEnum } from '@gtpl/shared-models/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { DeheadingPeelingService } from '@gtpl/shared-services/masters';

/* eslint-disable-next-line */
export interface DeheadingPeelingProps { }

export function DeheadingPeelingGrid(
  props: DeheadingPeelingProps
) {
  const {Option} = Select
  const [form] = Form.useForm()
  const [page, setPage] = React.useState(1);
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [rmPriceListData, setRmPriceListData] = useState<DeheadingPeelingRequest[]>([]);
  const services = new DeheadingPeelingService();
  const [data,setData] = useState<any[]>([])
  const [ foodData,setFoodData ] = useState<any[]>([])
  const [ valueAdd1Data, setValueAdd1Data ] = useState<any[]>([])
  const [ valueAdd2Data, setValueAdd2Data ] = useState<any[]>([])


  useEffect(() => {
    // getInfo();
    getAllData()
    getFoodTypes()
    getValueAdd1()
    getValueAdd2()
  }, []);

  const getFoodTypes=()=>{
    services.getFoodTypes().then((res)=>{
      setFoodData(res.data)
    })
  }

  const getValueAdd1=()=>{
    services.getValueAdd1().then((res)=>{
      setValueAdd1Data(res.data)
    })
  }

  const getValueAdd2=()=>{
    services.getValueAdd2().then((res)=>{
      setValueAdd2Data(res.data)
    })
  }



  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

  });

//  const getInfo=()=>{
//   services.getDeheadingPeelingInfo().then(res=>{
//     if(res.status){
//       setData(res.data)
//     }
//   })
//  }

 const getAllData=()=>{
  const req =  new DeheadingFilterReq(form.getFieldValue('foodTypeId'),form.getFieldValue('valueAdd1'),form.getFieldValue('valueAdd2Id'),form.getFieldValue('basedOn'))
  services.getAllPeelingInfo(req).then(res=>{
    if(res.status){
      setData(res.data)
      message.success(res.internalMessage,1)
    }else{
      setData([])
      message.error(res.internalMessage,2)
    }
  })
 }

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

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

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'Date',
      dataIndex: 'date',
      // responsive: ['lg'],
      sorter: (a, b) => a.date?.localeCompare(b.date),
      ...getColumnSearchProps('date'),
      render: (text) => moment(text).format('YYYY-MM-DD') || '-'
    },
    {
        title: 'Scope of Work',
        dataIndex: 'scopeOfWork',
        // responsive: ['lg'],
        sorter: (a, b) => a.scopeOfWork?.localeCompare(b.scopeOfWork),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('scopeOfWork'),
        render: (text: string) => text || '-'
    },
    {
      title: 'Grade',
      dataIndex: 'grade',
      // responsive: ['lg'],
      sorter: (a, b) => a.grade?.localeCompare(b.grade),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('grade'),
      render: (text: string) => text || '-'
    },
    {
      title: 'Food Type',
      dataIndex: 'foodType',
      // responsive: ['lg'],
      sorter: (a, b) => a.foodType?.localeCompare(b.foodType),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('foodType'),
      render: (text: string) => text || '-'
    },
    {
      title: 'Value Addition 1',
      dataIndex: 'valueAdd1',
      // responsive: ['lg'],
      sorter: (a, b) => a.valueAdd1?.localeCompare(b.valueAdd1),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('valueAdd1'),
      render: (text: string) => text || '-'
    },
    {
      title: 'Value Addition 2',
      dataIndex: 'valueAdd2',
      // responsive: ['lg'],
      sorter: (a, b) => a.valueAdd2?.localeCompare(b.valueAdd2),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('valueAdd2'),
      render: (text: string) => text || '-'
    },
    {
      title: 'Value Addition 3',
      dataIndex: 'valueAdd3',
      // responsive: ['lg'],
      sorter: (a, b) => a.valueAdd3?.localeCompare(b.valueAdd3),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('valueAdd2'),
      render: (text: string) => text || '-'
    },
    {
      title: 'Rate/kg',
      dataIndex: 'ratePerKg',
      // responsive: ['lg'],
      align:"right",
      sorter: (a, b) => parseFloat(a.ratePerKg) - parseFloat(b.ratePerKg),
      ...getColumnSearchProps('ratePerKg'),
      render: (text: string) => text || '-'
    },
    {
      title: 'Based On',
      dataIndex: 'basedOn',
      align:"right",
      ...getColumnSearchProps('basedOn'),
      render: (text: string) => text || '-'
      
    },
    {
      title: 'RRP Price',
      dataIndex: 'isRRP',
      align: "right",
      ...getColumnSearchProps('isRRP'),
      render: (text: number) => (text === 1 ? 'Yes' : 'No')
    }
    
 
  ];
  const exceldata = [
    { title: 'S No', dataIndex: 'sNo', render: (text, object, index) => { 
        if(index == data.length) { 
          return null;
        } else { 
          return index+1
        } 
      },
      width: 60, 
    },
    { title: 'Date', dataIndex: 'date',width: 100,render:(text:any,record:any) => {return record.date ? moment(record.date).format('YYYY-MM-DD') : '-'} },
    { title: 'SCOPE OF WORK', dataIndex: 'scopeOfWork',width: 500,render:(text:any,record:any) => {return record.scopeOfWork ? record.scopeOfWork : '-'} },     
    { title: 'GRADE', dataIndex: 'grade',width: 100,render:(text:any,record:any) => {return record.grade ? record.grade : '-'} },
    { title: 'FOOD TYPE', dataIndex: 'foodType',width: 100,render:(text:any,record:any) => {return record.foodType ? record.foodType : '-'} },
    { title: 'VALUE ADDITION 1', dataIndex: 'valueAdd1',width: 100,render:(text:any,record:any) => {return record.valueAdd1 ? record.valueAdd1 : '-'} },
    { title: 'VALUE ADDITION 2', dataIndex: 'valueAdd2',width: 100,render:(text:any,record:any) => {return record.valueAdd2 ? record.valueAdd2 : '-'} },
    { title: 'VALUE ADDITION 3', dataIndex: 'valueAdd3',width: 100,render:(text:any,record:any) => {return record.valueAdd3 ? record.valueAdd3 : '-'} },
    { title: 'RATE PER KG', dataIndex: 'ratePerKg',width: 100,render:(text:any,record:any) => {return record.ratePerKg ? record.ratePerKg : '-'} },
    {title:'Based On',dataIndex:'basedOn',width: 100,render:(text:any,record:any) => {return record.basedOn ? record.basedOn : '-'}}


  ]
  const onChange = (pagination, filters, sorter, extra) => {
    console.log('params', pagination, filters, sorter, extra);
  }

  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('Peeling Rates Excel')
      .addColumns(exceldata)
      .addDataSource(data, { str2num: false })
      .saveAs('Peeling Rates.xlsx');
  }

  const onReset = () =>{
    form.resetFields()
    getAllData()
}

  
  return (
    <Card title={<span style={{ color: 'white' }}>Peeling Rates</span>}
      style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} 
      extra={<Link to="/deheading-peeling-form"  ><Button className='panel_button' >Upload File</Button></Link>} >
      <br></br>
        <Form form={form} layout="vertical" onFinish={getAllData}>
        <Row gutter={24}>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item name='foodTypeId' label='Food Type'>
              <Select showSearch allowClear optionFilterProp="children" placeholder='Select Food Type'>
                {foodData.map(e => {
                  return(
                  <Option key={e.foodTypeId} value={e.foodTypeId}>{e.foodType}</Option>
                  )
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item name='valueAdd1' label='Value Addition One'>
              <Select showSearch allowClear optionFilterProp="children" placeholder='Select Value addition1'>
                {valueAdd1Data.map(e => {
                  return(
                  <Option key={e.valueAdd1Id} value={e.valueAdd1Id}>{e.valueAdd1}</Option>
                  )
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item name='valueAdd2Id' label='Value Addition Two'>
              <Select showSearch allowClear optionFilterProp="children" placeholder='Select Value Addition2'>
                {valueAdd2Data.map(e => {
                  return(
                  <Option key={e.valueAdd2Id} value={e.valueAdd2Id}>{e.valueAdd2}</Option>
                  )
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item name='basedOn' label='Based On'>
              <Select showSearch allowClear optionFilterProp="children" placeholder='Select Based On'>
                {
                  Object.values(PeelingRateBasedEnum).map(e => {
                    return(
                      <Option key={e} value={e}>{e}</Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }} style={{marginTop:'30px'}}>
            <Form.Item>
              <Button icon={<SearchOutlined/>} type='primary' htmlType="submit" >Search</Button>
            </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }} style={{marginTop:'30px'}}>
              <Form.Item>
                <Button icon={<UndoOutlined/>} danger onClick={onReset}>Reset</Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <div style={{ textAlign: 'right', margin:'-56px 0 10px 0' }}>
          <Button
            type="default"
            style={{ color: 'green' }}
            onClick={exportExcel}
            icon={<FileExcelFilled />}
          >
            Download Excel
          </Button>
        </div>
        <Table
        // rowKey={record => record.rmPriceListId}
        columns={columnsSkelton}
        dataSource={data}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        onChange={onChange}
        // scroll={{ x: true }}
        bordered />
      
    </Card>
  );
}

export default DeheadingPeelingGrid;


