import { Button, Card, Col, DatePicker, Divider, Drawer, Form, Input, Popconfirm, Row, Switch, Tag, message } from "antd";
import React, { useEffect, useRef, useState } from "react"
import Highlighter from 'react-highlight-words';
import { SearchOutlined, CheckCircleOutlined, RightSquareOutlined, CloseCircleOutlined, UndoOutlined } from '@ant-design/icons';
import Table, { ColumnProps } from "antd/lib/table";
import { ExchangeRatesService } from "@gtpl/shared-services/masters";
import { Link } from "react-router-dom";
import { ExchangeIdReq, ExchangeRatesRequest } from "@gtpl/shared-models/masters";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";


export function ExchangeRatesGrid ()
{
  const searchInput = useRef(null);
  const [page, setPage] = React.useState(1);
  const [searchText, setSearchText] = useState(''); 
  const [searchedColumn, setSearchedColumn] = useState('');
  const exchangeService = new ExchangeRatesService
  const [ mainData, setMainData ] = useState<any[]>([])
  const [form] = Form.useForm()
  const { RangePicker } = DatePicker;

  useEffect(()=>{
    getAllExchanges()
  },[])


  const getAllExchanges = () =>{
    const req = new ExchangeIdReq()
    if (form.getFieldValue('effectiveFrom') !== undefined) {
      req.fromDate = (form.getFieldValue('effectiveFrom')[0]).format('YYYY-MM-DD')
  }
  if (form.getFieldValue('effectiveFrom') !== undefined) {
  req.toDate = (form.getFieldValue('effectiveFrom')[1]).format('YYYY-MM-DD')
  }    exchangeService.getAllExchangeRates(req).then(res=>{
      if(res.status){
        setMainData(res.data)
        message.success(res.internalMessage,2)
    }else{
        setMainData([])
        message.error(res.internalMessage,2)
    }
    }).catch(err=>{
        setMainData([]) 
        message.error(err.message,2)
    })
  }

  const activateDeactivate = (data: ExchangeRatesRequest) =>{
    data.isActive = data.isActive? false: true
    exchangeService.activateDeactivateExchange(data).then(res => {
      if(res.status){
            message.success(res.internalMessage,2)
            getAllExchanges()
        }else{
            message.error(res.internalMessage,2)
        }
    }).catch(err=>{
        message.error(err.message,2)
    })
}
const onReset = () =>{
  form.resetFields()
  getAllExchanges()
}

  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 columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      render: (text, object, index) => (page-1) * 10 +(index+1)
    },
    
    {
      title: 'Currency',
      dataIndex: 'currencyName',
      sorter: (a, b) => a.currencyName.localeCompare(b.currencyName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('currencyName')
    },
    {
      title: 'Exchange Rate',
      dataIndex: 'exchangeRate',
      sorter: (a, b) => a.exchangeRate.localeCompare(b.exchangeRate),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('exchangeRate')
    },
    {
      title: 'Effective From',
      dataIndex: 'effectiveFrom',
      sorter: (a, b) => a.effectiveFrom.localeCompare(b.effectiveFrom),
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('effectiveFrom')
    },
    {
      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: true,
        },
        {
          text: 'InActive',
          value: false,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => 
      {
        // === is not work
        return record.isActive === value;
      },
      
    },
    {
      title:`Action`,
      dataIndex: 'action',
      render: (text, rowData) => (
        <Popconfirm onConfirm={e =>{activateDeactivate(rowData);}}
            title={
              rowData.isActive
                ? 'Are you sure to Deactivate ?'
                :  'Are you sure to Activate ?'
            }
          >  
             <Switch  size="default"
                className={ rowData.isActive ? 'toggle-activated' : 'toggle-deactivated' }
                checkedChildren={<RightSquareOutlined type="check" />}
                unCheckedChildren={<RightSquareOutlined type="close" />}
                checked={rowData.isActive}
              />
            
          </Popconfirm>  
      )
    }
  
  ];

    return(
      <Card title={<span style={{color:'white'}}>Exchange Rate</span>}
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} extra={<Link to='/exchange-rate-form' ><Button className='panel_button' >Create </Button></Link>}
    
    >
     <br></br>
     <Row gutter={40} >
      <Col>
          <Card title={'Total Exchange Rates: ' + mainData.length} style={{textAlign: 'left', width: 250, height: 41,backgroundColor:'#bfbfbf'}}></Card>
          </Col>
          <Col>
           <Card title={'Active: ' + mainData.filter(el => el.isActive).length} style={{textAlign: 'left', width: 200, height: 41,backgroundColor:'#52c41a'}}></Card>
          </Col>
          <Col>
           <Card title={'In-Active: ' + mainData.filter(el => el.isActive == false).length} style={{textAlign: 'left', width: 200, height: 41,backgroundColor:'#f5222d'}}></Card>
          </Col>
          </Row>
          <br></br>
          <Form form={form} layout="vertical" onFinish={getAllExchanges}>
            <Row gutter={24}>
              <Col>
              <Form.Item name="effectiveFrom" label="Effective From">
                <RangePicker />
              </Form.Item>
              </Col>
              <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }} style={{marginTop:'2%'}}>
                    <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:'2%'}}>
                    <Form.Item>
                        <Button icon={<UndoOutlined/>} danger onClick={onReset}>Reset</Button>
                    </Form.Item>
                </Col>
            </Row>
          </Form>
          <Table
          rowKey={record => record.id}
          columns={columnsSkelton}
          dataSource={mainData}
          pagination={{
            onChange(current) {
              setPage(current);
            }
          }}
          bordered />
     </Card>
  );
}
export default ExchangeRatesGrid