import React, { useEffect, useRef, useState } from 'react';
import { Divider, Table, Popconfirm, Card, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, message } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, CheckOutlined,RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words'
import { SoakStyleMappingService } from '@gtpl/shared-services/masters';
import { ColumnProps } from 'antd/lib/table';

import { Link } from "react-router-dom";
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { SoackStyleInfo, SoakStyleDto, SoakStyleRequest } from '@gtpl/shared-models/masters';
import SoakStyleForm from 'libs/pages/master/master-components/soack-style-form/src/lib/soak-style-form'

export interface SoakStyleGridProps { }

export function SoakStyleGrid(
  props: SoakStyleGridProps
) {
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const SoakService = new SoakStyleMappingService()
  const [soakStyle, setSoakStyle] = useState<SoakStyleDto[]>([]);

  const [drawerVisible, setDrawerVisible] = useState(false);
  const [initialValues,setInitialValues] = useState<any>([]);
  useEffect(() => {
    getAllSoakStyles();
  }, []);

  const getAllSoakStyles = () => {

    SoakService.getAllSoakStyles().then(res => {
      if (res.status) {
        setSoakStyle(res.data);
      } else {
        if (res.intlCode) {
          setSoakStyle([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setSoakStyle([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const UpdateSoakstyle = (data: SoakStyleRequest ) => {
    SoakService.updateSoaksStyles(data).then(res => {
      if (res.status) {

        message.success("Updated Successfully")
        setDrawerVisible(false)
        getAllSoakStyles()
      }
      else {
        message.error(res.internalMessage)
      }
    }).catch(err => {
      message.error(err.message)

    })
  }

  const activateDeactivate = (rowData: SoackStyleInfo) => {
    rowData.isActive = rowData.isActive ? false : true;
    
    SoakService.activateOrDeactivateSoakStyle(rowData).then(res => {
      if (res.status) {

        message.success(res.internalMessage)
        getAllSoakStyles()
      }
    })
  }

  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 closeDrawer = () => {
    setDrawerVisible(false);
  }

  const openFormWithData = (rowData: any) => {
    setDrawerVisible(true);
  }
  const onEdit = (rowData: any) => {
    setSoakStyle(rowData)
  }

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },



    {
      title: 'Soak Style',
      dataIndex: 'soakstyle',
      sorter: (a, b) => a.soakstyle.localeCompare(b.soakstyle),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('soakstyle')
    },



    {
      title: 'Status',
      dataIndex: 'isActive',
      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) => 
      {
        
        return record.isActive === value;
      },
      
    },   
     {
      title: `Action`,
      dataIndex: 'action',
      render: (text, rowData) => (
        <span>
          <EditOutlined className={'editSamplTypeIcon'} type="edit"
            onClick={() => {
              if (rowData.isActive) {
                setInitialValues(rowData)
                openFormWithData(rowData);
              } else {
                AlertMessages.getErrorMessage('You Cannot Edit Deactivated Soakstyle');
              }
            }}
            style={{ color: '#1890ff', fontSize: '14px' }}
          />

          <Divider type="vertical" />
          <Popconfirm
            onConfirm={() => activateDeactivate(rowData)} title={rowData.isActive ? "Are you sure to Deactivate Soakstyle" : "Are You Sure To Activate Soakstyle ?"}
    >
          <Tooltip title={rowData.isActive ? 'Deactivate' : "Activate"}>
          <Switch  size="default"
                className={ rowData.isActive ? 'toggle-activated' : 'toggle-deactivated' }
                checkedChildren={<RightSquareOutlined type="check" />}
                unCheckedChildren={<RightSquareOutlined type="close" />}
                checked={rowData.isActive}
              />
          </Tooltip>
        </Popconfirm >
        </span>
      )
    }
  ];
  const onChange = (pagination, filters, sorter, extra) => {
  }
  const OpenFormTocreateRecord = () => {
  }
  return (
    <Card title={<span style={{ color: 'white' }}>Soak Style </span>}
      style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} extra={<Link to='/soakstyle-form' ><Button className='panel_button' >Create </Button></Link>}

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

      <br></br>
      <Table
        rowKey={record => record.soakstyleId}
        columns={columnsSkelton}
        dataSource={soakStyle}
        scroll= {{x:true}}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        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'>
          <SoakStyleForm
            setDrawerVisble={setDrawerVisible}
            getSoakStyle={getAllSoakStyles}
            key={Date.now()}
            UpdateSoakstyle={UpdateSoakstyle}
            isUpdate={true}
            soakStyleData={soakStyle}
            closeForm={closeDrawer}
            initialValues={initialValues}
            />
        </Card>
      </Drawer>
    </Card>
  );
}


export default SoakStyleGrid;

