import React, { useEffect, useRef, useState } from 'react';
import { Divider, Table, Popconfirm, Card,Form,DatePicker, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, Tabs, Modal, Select } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { ColumnProps, ColumnsType } from 'antd/lib/table';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { GrnService } from '@gtpl/shared-services/procurement';
import { GRNLocationPropsRequest, ItemCategoriesDto } from '@gtpl/shared-models/masters';
import { UnitRequest } from '@gtpl/shared-models/common-models';
import { Redirect } from 'react-router-dom';
import { GrnInspectionreq } from '@gtpl/shared-models/procurement-management';
import GrnInspection from './grn-inspection';
import { ItemCategoryService } from '@gtpl/shared-services/masters';
export interface GrnPendingInfoGridProps{}

export function GrnPendingInfoGrid(props:GrnPendingInfoGridProps){
  const service =new GrnService()
  const [grndata,setGrndata]=useState<any[]>([]);
  const [locationData,setLocationData]=useState<GRNLocationPropsRequest>();
  const [inspectiondata,setInspectiondata]=useState<GrnInspectionreq>()
  const [slectedgrnInspectionData, setSelectedGrnInspectionData] = useState<any>(undefined);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [drawerVisible, setDrawerVisible] = useState(false);

  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 { Option } = Select;
  const [form] = Form.useForm();
  const [itemCategories, setItemCategories] = useState<ItemCategoriesDto[]>([]);
  
  const itemCategoryService = new ItemCategoryService()
    useEffect(() =>{
        getitemsdata();
        getItemCategories()
    },[])
    // const setData = (val) => {
    //   const testdata = new GRNLocationPropsRequest(2,1,'Coromandel Cartons and Containers Private Limited',139,'Carton/METROCHEF/16-20/VREZPEELI/10*800GM',107,'CCC-510',2000,0,6,3,4,233,327,8,143,null,null,'')
    //   setLocationData(testdata)
    // }

    const setData = (rowdata) =>{
      console.log(rowdata)
      const testdata =new GRNLocationPropsRequest(rowdata.grnUnitId,rowdata.vendorId,rowdata.vendorName,rowdata.itemId,rowdata.itemName,rowdata.brandId,rowdata.invoiceNumber,rowdata.receivedQuantity,rowdata.saleOrderId,rowdata.itemCategoryId,rowdata.itemSubCategoryId,rowdata.unitPrice,rowdata.grnId,rowdata.grnItemId,rowdata.sizeId,rowdata.poId,rowdata.locationId,rowdata.physicalQuantity,null,rowdata.createdUser,rowdata.grnNo)
      setLocationData(testdata)
  console.log(rowdata)

    }

    const getItemCategories = () => {
      itemCategoryService.getActiveItemCategories().then((res) => {
        if (res.status) {
          setItemCategories(res.data);
        } else {
          setItemCategories([]);
        }
      }).catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setItemCategories([]);
      });
    }
  /**
  * used for column filter
  * @param dataIndex column data index
  */
  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);
    };
    const displayModel = (data: GrnInspectionreq) => {
      setSelectedGrnInspectionData(data);
      setIsModalVisible(true);
    };
    function handleReset(clearFilters) {
      clearFilters();
      setSearchText('');
    };
    const closeDrawer=()=>{
      setIsModalVisible(false);
      getitemsdata()

    }
    const handleCancel = () => {
      getitemsdata();
      setIsModalVisible(false);
    };
    const sampleTypeColumns:ColumnsType<any>= [
        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            responsive: ['sm'],
            render: (text, object, index) => (page - 1) * pageSize + (index + 1)
          },
        {
            title: 'Vendor',
            dataIndex:"vendorName",
            align:'left',
            sorter: (a, b) => a.vendorName.trim().localeCompare(b.vendorName.trim()),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('vendorName')
          },
        {
            title: 'Dc Number',
            dataIndex:"invoiceNumber",
            align:'left',
            sorter: (a, b) => a.invoiceNumber.length-(b.invoiceNumber.length),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('invoiceNumber')
          
          },
        {
          title: 'Item',
          dataIndex:"itemName",
          align:'left',
          sorter: (a, b) => a.itemName-b.itemName,
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('itemName')
        
        },
      {
          title: 'Grn Quantity',
          dataIndex:'receivedQuantity',
          align:'left',
          sorter: (a, b) => a.receivedQuantity - b.receivedQuantity,
          sortDirections: ['descend', 'ascend'],
      },
      {
        title: 'Location Mapped',
        dataIndex:'physicalQuantity',
        align:'left',
        sorter: (a, b) => a.physicalQuantity - b.physicalQuantity,
        sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Balance',
      dataIndex:'balance',
      align:'left',
      sorter: (a, b) => a.balance - b.balance,
//       render:(record) =>{
//         const balance=record.receivedQuantity-record.physicalQuantity
//       return balance
//         }
      }, 
      {
        title: 'Inspected Qty',
        dataIndex:'inspectedQty',
        align:'left',
        sorter: (a, b) => a.inspectedQty - b.inspectedQty,
        sortDirections: ['descend', 'ascend'],
        render:(text,record) => {
          return(
            <>
            {record.inspectedQty ? record.inspectedQty : '-'}
            </>
          )
        }
    },
    {
        title:'Allocate',
        render: (rowData) =>(
                  <span>
                <Button type="primary" shape="round" size="small" 
                   onClick={() => {
                    console.log(rowData)
                    setData(rowData)
                    // setOpen(true)
                    // setIndentnumber(rowData.indentNumber)
                    // getReceivedQuantityagainstPonumber(rowData.indentNumber)
                  }}
                    >
                    Allocate
                  </Button>
              </span>
  )
      },
      {
        title:'GRN Inspection',
        dataIndex: 'inspection',
        render: (text, rowData: any, index) => (
          <span> <Button type="primary" shape="round"  size="small"
            disabled={rowData.inspectedQty == rowData.receivedQuantity ? true : false}
            onClick={() => displayModel(rowData)}> Inspection </Button>
          </span>
        )
      },
    ];
    const getitemsdata = () =>{
        const unitReq =  new UnitRequest( Number(localStorage.getItem('unit_id'))) 

        service.grninfoforpending(unitReq).then(res =>{
          if(res.status){
            setGrndata(res.data);
          }else{
            setGrndata([]);
          }
        }).catch(err =>{
            setGrndata([]);
        })
    
      }
      const onChange=(pagination, filters, sorter, extra)=> {
        console.log('params', pagination, filters, sorter, extra);
      }

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

      return (
        <>
        {(locationData) ? <Redirect
            to={{
              pathname: "/location-mapping",
              state: locationData
            }}
          /> : null}
           <Card title={<span style={{color:'white'}}>Grn Pending Details</span>}
      style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} >
            {/* <Card style={{ overflow: 'auto', overflowY: 'hidden', backgroundColor: '#69c0ff', height: 40, margin: 1 ,textAlign:'center'}} title={<span>Grn Pending Details</span>}></Card> */}
            {/* <Form  form={form} layout={'vertical'} style={{ padding: '0px' }}>
         <Row gutter={24}>
            
            <Col xs={{ span: 24 }}
              sm={{ span: 24 }}
              md={{ span: 5 }}
              lg={{ span: 5 }}
              xl={{ span: 6 }}>
            <Form.Item label="Item Category"
                    name= "itemCategoryId"

                  >
                    <Select  showSearch placeholder="Select Item Category" allowClear filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                      {itemCategories.map(dropData => {
                        return <Option key={dropData.itemCategoryId} value={dropData.itemCategoryId}>{dropData.itemCategory}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                    
                      <Col style={{ marginTop: 30 }} span={5}>
                      <Button
                        type="primary"
                        icon={<SearchOutlined />}
                        block 
                        onClick={ getitemsdata}
                        style={{ marginRight: 4, width: 100 }}
                      >
                        Search
                      </Button>
                      <Button type="primary" htmlType="submit" onClick={onReset}>
                        Reset
                      </Button>
                    </Col>            
                 </Row>
          </Form> */}
            <Table
                rowKey={record => record.productId}
                className="components-table-nested"
                columns={sampleTypeColumns}
                dataSource={grndata}
                pagination={{
                  onChange(current ,pageSize) {
                    setPage(current);
                    setPageSize(pageSize)
                  }
                }}
                  onChange={onChange}
                  scroll={{ x: 500 }}
                  // size='small'
                  bordered
            />
              <Modal
        className='inspection'
        key={'modal' + Date.now()}
        width={'80%'}
        style={{ top: 30, alignContent: 'right' }}
        visible={isModalVisible}
        title={<React.Fragment>
        </React.Fragment>}
        onCancel={handleCancel}
        footer={[

        ]}
      >
              <GrnInspection key={Date.now()}                
                isUpdate={true}                
                closeForm={closeDrawer}
                fgInspecData={slectedgrnInspectionData} />
            </Modal>
      </Card>
        </>
      );
    
}
export default GrnPendingInfoGrid;