import { UserRequestDto, EmployeeRolesEnum } from '@gtpl/shared-models/common-models';
import { BankDetailsRequest, CertificatesDto } from '@gtpl/shared-models/masters';
import { BankDetailsService } from '@gtpl/shared-services/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Input, Button, Tag, Divider, Popconfirm, Switch, Card, Row, Table, Drawer } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import {CheckCircleOutlined,CloseCircleOutlined,RightSquareOutlined,EyeOutlined,EditOutlined,SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import BankDetailsForm from './bank-details-form';


export function BankDetailsView() {
 
    const searchInput = useRef(null);
    const [page, setPage] = React.useState(1);
    const [searchText, setSearchText] = useState(''); 
    const [searchedColumn, setSearchedColumn] = useState('');
    const columns = useState('');
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [BankData, setBankData] = useState<BankDetailsRequest[]>([]);
    const [slectedBankData, setSelectedBankData] = useState<any>(undefined);
    const [allData, setAllData] = useState<BankDetailsRequest[]>([]);
    const service=new BankDetailsService();
    useEffect(() => {
      getAll();
    }, []);
  
    /**
     * 
     */
    const getAll= () => {
      console.log(localStorage.getItem('createdUser'))
      service.getAllBankDetailsInfo().then(res => {
        if (res.status) {
          setBankData(res.data);
          setAllData(res.data);
        } else {
          setAllData([]);
          if (res.intlCode) {
              setBankData([]);
              AlertMessages.getErrorMessage(res.internalMessage);
          } else {
           AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      }).catch(err => {
        setBankData([]);
        setAllData([]);
        AlertMessages.getErrorMessage(err.message);
      })
    }
    /**
     * 
     * @param BankData 
     */
    const deleteBank = (data:BankDetailsRequest) => {
      data.isActive=data.isActive?false:true;
      service.activatedeActivate(data).then(res => { console.log(res);
        if (res.status) {
          getAll();
          AlertMessages.getSuccessMessage('Success'); 
        } else {
          if (res.intlCode) {
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
      })
    }
     
      /**
       * 
       * @param variantData 
       */
      const update = (val: BankDetailsRequest) => {
        val.updatedUser =JSON.parse( localStorage.getItem('username'))
        console.log(val) 
        service.updateBankDetails(val).then(res => { console.log(res);
          if (res.status) {
            AlertMessages.getSuccessMessage('Updated Successfully');
            getAll();
            setDrawerVisible(false);
          } else {
            if (res.intlCode) {
              AlertMessages.getErrorMessage(res.internalMessage);
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
          }
        }).catch(err => {
          AlertMessages.getErrorMessage(err.message);
        })
      }
     /**
     * 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);
    };
  
    function handleReset(clearFilters) {
      clearFilters();
      setSearchText('');
    };
  
      //drawer related
      const closeDrawer=()=>{
        setDrawerVisible(false);
      }
    
      //TO open the form for updation
      const openFormWithData=(viewData: CertificatesDto)=>{
        setDrawerVisible(true);
        setSelectedBankData(viewData);
      }
  
  
    const columnsSkelton: ColumnProps<any>[] = [
      {
        title: 'S No',
        key: 'sno',
        width: '70px',
        // hideInSearch: true,
        // hideInForm: true,
        responsive: ['sm'],
        render: (text, object, index) => (page-1) * 10 +(index+1)
      },
  
      {
        title: 'Bank Name',
        dataIndex: 'bankName',
   
        sorter: (a, b) => a.bankName.localeCompare(b.bankName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('bankName')
      },
      {
        title: 'Branch Name',
        dataIndex: 'branchName',
   
        sorter: (a, b) => a.branchName.localeCompare(b.branchName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('branchName')
      },
      {
        title: 'Account No',
        dataIndex: 'bankAcc',
        sorter: (a, b) => a.bankAcc.localeCompare(b.bankAcc),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('bankAcc')
      },
      {
        title: 'IFSC Code',
        dataIndex: 'ifscCode',
        sorter: (a, b) => a.ifscCode.localeCompare(b.ifscCode),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('ifscCode')
      },
      {
        title: 'Swift Code',
        dataIndex: 'swiftCode',
   
        sorter: (a, b) => a.swiftCode.localeCompare(b.swiftCode),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('swiftCode')
      },
      {
        title: 'Bank Address',
        dataIndex: 'bankAddress',
   
        sorter: (a, b) => a.bankAddress.localeCompare(b.bankAddress),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('bankAddress')
      },
      {
        title: 'Company',
        dataIndex: 'company',
        // filters: [
        //   {
        //     text: 'Active',
        //     value: true,
        //   },
        //   {
        //     text: 'InActive',
        //     value: false,
        //   },
        // ],
        // filterMultiple: false,
        // onFilter: (value, record) => 
        // {
        //   // === is not work
        //   return record.company === value;
        // },
      },
      {
        title: 'Status',
        dataIndex: 'isActive',
        // hideInSearch: true,
        // hideInForm: true,
        render: (isActive, rowData) => (
          <>
            {rowData.isActive?<Tag icon={<CheckCircleOutlined />} color="#87d068">Active</Tag>:<Tag icon={<CloseCircleOutlined />} color="#f50">In Active</Tag>}
          </>
        ),
        filters: [
          {
            text: 'Active',
            value: true,
          },
          {
            text: 'InActive',
            value: false,
          },
        ],
        filterMultiple: false,
        onFilter: (value, record) => 
        {
          // === is not work
          return record.isActive === value;
        },
      },
      {
        title:`Action`,
        dataIndex: 'action',
        // hideInSearch: true,
        // hideInForm: true,
        render: (text, rowData) => (
          <span>         
              <EditOutlined  className={'editSamplTypeIcon'}  type="edit" 
                onClick={() => {
                  if (rowData.isActive) {
                    openFormWithData(rowData);
                  } else {
                    AlertMessages.getErrorMessage('You Cannot Edit Deactivated Bank');
                  }
                }}
                style={{ color: '#1890ff', fontSize: '14px' }}
              />
            
            <Divider type="vertical" />
              <Popconfirm onConfirm={e =>{deleteBank(rowData);}}
              title={
                rowData.isActive
                  ? 'Are you sure to Deactivate Bank ?'
                  :  'Are you sure to Activate Bank ?'
              }
            >
              <Switch  size="default"
                  className={ rowData.isActive ? 'toggle-activated' : 'toggle-deactivated' }
                  checkedChildren={<RightSquareOutlined type="check" />}
                  unCheckedChildren={<RightSquareOutlined type="close" />}
                  checked={rowData.isActive}
                />
              
            </Popconfirm>
          </span>
        )
      }
    ];
  
    /**
     * 
     * @param pagination 
     * @param filters 
     * @param sorter 
     * @param extra 
     */
    const onChange=(pagination, filters, sorter, extra)=> {
      console.log('params', pagination, filters, sorter, extra);
    }
  
    const getBoolean = (text:string) => {
      switch(text){ 
        case "true":
          return true;
        case "false":
          return false; 
      }
    }
    return (
      <>
      <Card title={<span style={{color:'white'}}>Bank</span>}
      style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} extra={<Link to='/bank-details-form' ><span style={{color:'white'}} >{(JSON.parse(localStorage.getItem('role'))===EmployeeRolesEnum.SUPER_ADMIN)?'':<Button className='panel_button' >Create </Button>} </span></Link>}   >
       <br></br>
       <Row gutter={40} style={{ marginLeft: '1%' }}>
            <Card title={'Total Banks: ' + BankData.length} style={{textAlign: 'left', width: 230, height: 41,backgroundColor:'#bfbfbf'}}></Card>   
            <Card title={'Active: ' + BankData.filter(el => el.isActive).length} style={{textAlign: 'left', width: 200, height: 41,backgroundColor:'#52c41a',marginLeft:'1%'}}></Card>
            <Card title={'In-Active: ' + BankData.filter(el => el.isActive == false).length} style={{textAlign: 'left', width: 200, height: 41,backgroundColor:'#f5222d',marginLeft:'1%'}}></Card>       
            </Row>
            <br></br><br/>
            {/* <ConfigProvider locale={enUSIntl}>
              <ProTable
                columns={columnsSkelton}
                rowKey={record => record.BankId}
                request={(params, sorter, filter) => {
                  return Promise.resolve({
                    data: BankData,
                    success: true,
                  });
                }}
                scroll = {{x:true}}
                dataSource = {BankData}
                dateFormatter = 'string'
                search = {false}
                // onSubmit = {(params) => {
                //   if(Object.keys(params).length){
                //     const filteredData = BankData.filter(record => record.isActive === getBoolean(params.isActive));
                //     setBankData(filteredData);
                //   }
                // }}
                // onReset = {()=>{
                //   setBankData(allData);
                  
                // }}
                pagination={{
                  onChange(current) {
                    setPage(current);
                  }
                }}
                onChange={onChange}
              />
            </ConfigProvider> */}
        <Card >
        
          <Table
            rowKey={record => record.BankId}
            columns={columnsSkelton}
            dataSource={BankData}
            pagination={{
              onChange(current) {
                setPage(current);
              }
            }}
            
            scroll = {{x:true}}
            onChange={onChange}
            size='small'
            bordered />
          </Card>
          <Drawer bodyStyle={{ paddingBottom: 80 }} title='Update' width={window.innerWidth > 768 ? '60%' : '85%'}
              onClose={closeDrawer} visible={drawerVisible} closable={true}>
              <Card headStyle={{ textAlign: 'center', fontWeight: 500, fontSize: 16 }} size='small'>
                <BankDetailsForm key={Date.now()}
                  updateform={update}
                  isUpdate={true}
                  bankData={slectedBankData}
                  closeForm={closeDrawer} />
              </Card>
            </Drawer>
       </Card>
      </>
    );
  
}

export default BankDetailsView;
