import React, { useEffect, useRef, useState } from 'react';


import { Button, Card, Switch, Popconfirm, Divider, Table, Drawer, Form, Input, Col, Row, Tag, Select, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { UndoOutlined } from "@ant-design/icons";
import { Link } from 'react-router-dom';
import Highlighter from 'react-highlight-words';
import { RightSquareOutlined, EditOutlined, CloseCircleOutlined, CheckCircleOutlined, SearchOutlined } from '@ant-design/icons';
import { AssetLocationService } from "../../../../../../shared-services/asset-management/src/lib/asset-location";
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { AssetLocationDtoDefault, AssetsLocationDto } from "../../../../../../shared-models/asset-management/src/lib/asset-location/asset-location.dto";
import { AssetLocationResponse } from "../../../../../../shared-models/asset-management/src/lib/asset-location/asset-location-active-inactive";
import { locationForm } from '../../../dc-form/src/lib/pages-asset-management-asset-management-components-dc-form';
import { LocationDto } from '@gtpl/shared-models/masters';
import { LocationByPlant } from 'libs/shared-models/asset-management/src/lib/asset-location/location-by-plant.dto';

// import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import { from } from 'rxjs';
import { UnitcodeService } from '@gtpl/shared-services/masters';
import { AssetCheckListDto, CheckListActiveDeactiveDto } from '@gtpl/shared-models/asset-management';
import CheckListForm from './asset-checklist-form';
import { AssetCheckListService } from 'libs/shared-services/asset-management/src/lib/asset-check-list';
/* eslint-disable-next-line */
export interface checkListGridProps { }

export function CheckListGrid(
  props: checkListGridProps
) {

  const [drawerVisible, setDrawerVisible] = useState(false);
  const [page, setPage] = useState<number>(1);
  // const [checklistData, setCertificationData] = useState<CertificationDto[]>([]);
  const { Option } = Select;
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [slectedChecklistData, setSelectedChecklistData] = useState<any>(undefined);
  const [searchedColumn, setSearchedColumn] = useState('');
  const [checklistData, setChecklistData] = useState<AssetCheckListDto[]>([])
  const [selectedLocationData, setSelectedLocationData] = useState<any>([])
  const [selectedReasonData, setSelectedReasonData] = useState<any>(undefined);
  const [form] = Form.useForm()
  const plantsService = new UnitcodeService();
  const [unitData, setunitData] = useState<any[]>([]);
  const service = new AssetCheckListService();
  const [selectedunit, setUnit] = useState<number>(0)
  const [plantName, setPlantName] = useState<any>([]);
  const role = JSON.parse(localStorage.getItem('role'))


  useEffect(() => {
    getAllChecklist();
  }, [])

  const actionHandler = (data) => {
    if (data.isActive == true) {
      data.isActive = false
    } else {
      data.isActive = true
    }
    console.log(data, '---------data')
    // activateDeactivateLocation(data);
  }

  const getAllChecklist= () => {
    service.getAllChecklist().then(res => {
      if (res.status) {
        setChecklistData(res.data);
      } else {
        if (res.intlCode) {
          setChecklistData([]);
            AlertMessages.getErrorMessage(res.internalMessage);
        } else {
         AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setChecklistData([]);
    })
  }

  const active = (rowData: any) => {
    rowData.isActive = rowData.isActive ? true : false;
    const req = new CheckListActiveDeactiveDto(
      rowData.checkListId,
      rowData.isActive
    );
    service.activateOrDeactivateCheckList(req).then((res) => {
      if (res.status) {
        message.success(res.internalMessage);
        getAllChecklist();
      }
    });
  };

  const deleteChecklist = (Data: AssetCheckListDto) => {
    Data.isActive = Data.isActive ? false : true;
    service.activateorDeactivateLicense(Data).then(res => {
      console.log(res);
      if (res.status) {
        getAllChecklist();
        AlertMessages.getSuccessMessage('Success');
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }



  const updateChecklist = (Data: AssetCheckListDto) => {
    console.log(Data)
    service.updateCheckListGrid(Data).then(res => {
      console.log(res);

      if (res.status) {
        console.log(res)
        AlertMessages.getSuccessMessage('Updated Successfully');
        getAllChecklist();
        setDrawerVisible(false);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  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 openFormWithData=(viewData: AssetCheckListDto)=>{
    setDrawerVisible(true);
    setSelectedChecklistData(viewData);
  }

  const closeDrawer = () => {
    setDrawerVisible(false);
    form.resetFields();
  }

  const getAllPlants = () => {
    plantsService.getAllPlants().then(res => {
      if (res.status) {
        setPlantName(res.data)
      } else {
        AlertMessages.getErrorMessage(res.internalMessage)
      }
    })
  }



  const columns: ColumnsType<any> = [
    {
      title: "S.No",
      key: "sno",
      responsive: ["sm"],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },

    {
      title: 'Check List',
      dataIndex: 'checkListName',
      sorter: (a, b) => a.checkListName?.localeCompare(b.checkListName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('checkListName'),
    },
    {
      title: 'Asset Category',
      dataIndex: 'assetCategory',
      sorter: (a, b) => a.assetCategory?.localeCompare(b.assetCategory),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('assetCategory'),
    },
    {
      title: 'Status',
      dataIndex: 'isActive',
      align: 'center',
      render: (isActive, rowData) => (
        <>
          {isActive ? <Tag icon={<CheckCircleOutlined />} color="#87d068">Active</Tag> : <Tag icon={<CloseCircleOutlined />} color="#f50">In Active</Tag>}
        </>
      ),
      filters: [
        {
          text: 'Active',
          value: 1,
        },
        {
          text: 'InActive',
          value: 0,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => {
        console.log(value, '-------value')
        console.log(record.isActive, '----isactive')
        // === is not work
        return record.isActive === value;
      },

    },

    {
      title: 'Action',
      dataIndex: 'action',

      render: (text, rowData) => (

        <span>

          <EditOutlined className={'editSamplTypeIcon'} type="edit"
            onClick={() => {
              if (rowData.isActive) {
                openFormWithData(rowData);
              } else {
                AlertMessages.getErrorMessage('You Cannot Edit Deactivated Location');
              }
            }}
            style={{ color: '#1890ff', fontSize: '14px' }}
          />

          <Divider type="vertical" />
          <Popconfirm onConfirm={e => {
            active(rowData)
          }}
            title={
              rowData.isActive
                ? 'Are you sure to Deactivate Item ?'
                : 'Are you sure to Activate Item ?'
            }
          >
            <Switch size="default"
              className={rowData.isActive ? 'toggle-activated' : 'toggle-deactivated'}
              checkedChildren={<RightSquareOutlined type="check" />}
              unCheckedChildren={<RightSquareOutlined type="close" />}
              checked={rowData.isActive}
            />

          </Popconfirm>
        </span>
      )
    }

  ];


  const handleUnit = (value) => {
    setUnit(value);
    // getAllAssetLocation()
  }
  const onChange=(pagination, filters, sorter, extra)=> {
    console.log('params', pagination, filters, sorter, extra);
  }

  return (
    <Card title={<span style={{ color: 'white' }}>Check List</span>}
      style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} extra={<Link to='/asset-checklist-form' ><Button className='panel_button' >Create </Button></Link>}>  <br></br>
      <Form form={form}>
        <Row gutter={40}>
        

          {/* <Col  style={{marginTop:'2%'}}>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              // size="small"
              block
              onClick={() => searchHandler()}
              // style={{ marginRight: 2, width: 100 }}
            >
              Search
            </Button>
          </Col> */}
          {/* <Col  style={{marginTop:'2%'}}>
            <Button
              icon={<UndoOutlined />}
              onClick={resetHandler}
            >
              Reset
            </Button>
          </Col> */}
        </Row>
      </Form>

      <br />
      <Row gutter={40}>
        <Col>
          <Card title={'Total Locations: ' + checklistData.length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#bfbfbf' }}></Card>
        </Col>
        <Col>
          <Card title={'Active: ' + checklistData.filter(el => el.isActive).length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#52c41a' }}></Card>
        </Col>
        <Col>
          <Card title={'In-Active: ' + checklistData.filter(el => el.isActive == false).length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#f5222d' }}></Card>
        </Col>
      </Row>


      <br></br>< br />


      <Table columns={columns}
        rowKey={record => record.checkListId}
       dataSource={checklistData}
       pagination={{
        onChange(current) {
          setPage(current);
        }
      }}
      scroll = {{x:true}}
      onChange={onChange}
      bordered  />
      <Drawer bodyStyle={{ paddingBottom: 80 }} title='Update' width={window.innerWidth > 768 ? '50%' : '85%'}
        onClose={closeDrawer} visible={drawerVisible} closable={true}>
        
        <Card headStyle={{ textAlign: 'center', fontWeight: 500, fontSize: 16 }} size='small'>
          <CheckListForm
            setDrawerVisible={setDrawerVisible}
            getAllChecklist={getAllChecklist}
            key={Date.now()}
            updateCheckList={updateChecklist}
            isUpdate={true}
            checkListData={slectedChecklistData}
            closeForm={closeDrawer} />
        </Card>
      </Drawer>
    </Card>
  );
}


export default CheckListGrid;
