import React, { useEffect, useRef, useState } from "react";
import { Button, Card, Col, Divider, Drawer, Form, Input, Popconfirm, Row, Select, Space, Switch, Table, Tag, Upload } from 'antd'
import {CheckCircleOutlined,CloseCircleOutlined,RightSquareOutlined,EyeOutlined,EditOutlined,SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { Link } from "react-router-dom";
import { FileExcelFilled } from "@ant-design/icons";
import { Excel } from "antd-table-saveas-excel";
import {RmBudgetServices} from "libs/shared-services/masters/src"
export function RMBudgetGrid(){
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const service = new RmBudgetServices()
  const [data,setData] = useState([])
  const [searchText, setSearchText] = useState("");
const [searchedColumn, setSearchedColumn] = useState("");
const searchInput = useRef(null);

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

  const getInfo = () => {
      service.getAllRmBudget().then(res => {
          if(res.status){
              setData(res.data)
          }
      })
  }

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      setSearchText(selectedKeys[0]);
      setSearchedColumn(dataIndex);
    };

    const handleReset = (clearFilters) => {
      clearFilters();
      setSearchText("");
    };
  
 ;
    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
            size="small"
            style={{ width: 90 }}
            onClick={() => {
              handleReset(clearFilters);
              setSearchedColumn(dataIndex);
              confirm({ closeDropdown: true });
            }}
          >
            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,
    });


    const columns : any[] = [
        {
            title: 'S No',
            key: 'sno',
            align:"center",
            width:"60px",
            responsive: ['sm'],
            render: (text, object, index) => (page - 1) * pageSize + (index + 1) + (pageSize * (page - 1))
        },
        { 
        title: 'Month', 
        dataIndex: 'month',
        width: 100,
        sorter: (a, b) => a.year.localeCompare(b.year),
        sortDirections: ["ascend", "descend"],
        render: (text) => text ? text : "-",
        ...getColumnSearchProps('month')     },  
        {
            // title:'Destination',
            title:<div style={{textAlign:"center"}}>Year</div>,
            dataIndex:'year',
            sorter: (a, b) => a.year.localeCompare(b.year),
            sortDirections: ["ascend", "descend"],
            render: (text) => text ? text : "-",
            ...getColumnSearchProps('year') 
        },
       
       
        {
          title: 'Count',
          dataIndex: 'count',
          sorter: (a, b) => {
              const codeA = (a.count || "").toString();
              const codeB = (b.count || "").toString();
              return codeA.localeCompare(codeB);
          },
          sortDirections: ["ascend", "descend"],
          render: (text) => text ? text : "-",
          ...getColumnSearchProps('count')
      },
      {
          // title:'Buyer Address',
          title:<div style={{textAlign:"center"}}>Procurement manager</div>,
          dataIndex:'procurementManager',
          sorter: (a, b) => a.procurementManager.localeCompare(b.procurementManager),
          sortDirections: ["ascend", "descend"],
          render: (text) => text ? text : "-",
          ...getColumnSearchProps('procurementManager')       
         
      },
      {
        title:<div style={{textAlign:"center"}}>Qunatity</div>,
        dataIndex:'quantity',
        sorter: (a, b) => a.quantity.localeCompare(b.quantity),
        sortDirections: ["ascend", "descend"],
        render: (text) => text ? text : "-",
        ...getColumnSearchProps('quantity') 
    },
    ]

  let i = 1;
  let rowIndex = 1;

  const exceldata = [
  
    { title: 'Month', dataIndex: 'month',width: 100,render:(text:any,record:any) => {return record.month ? record.month : '-'} },  
    { title: 'Year', dataIndex: 'year',width: 100,render:(text:any,record:any) => {return record.year ? record.year : '-'} },
    { title: 'Count', dataIndex: 'count',width: 500,render:(text:any,record:any) => {return record.count ? record.count : '-'} },     
    { title: 'Procurement Manager', dataIndex: 'procurementManager',width: 100,render:(text:any,record:any) => {return record.procurementManager ? record.procurementManager : '-'} },
    { title: 'Qunatity', dataIndex: 'quantity',width: 100,render:(text:any,record:any) => {return record.quantity ? record.quantity : '-'} },
]

 const exportExcel = () => {
      const excel = new Excel();
      excel
        .addSheet('RM Budget Excel')
        .addColumns(exceldata)
        .addDataSource(data, { str2num: false })
        .saveAs('RM Budget List.xlsx');
    }
  return(
      <Card title='RM Budget'
       extra={<Link to='/rm-budget-excel-upload' >
      <span style={{color:'white'}} ><Button type={'primary'} >New</Button> </span>
      </Link>}
      >
          <Row justify={'end'}>
          <Button
              type="default"
              style={{ color: "green" }}
              onClick={exportExcel}
              icon={<FileExcelFilled />}
          >
              Download Excel
          </Button>
          </Row>
          <Table className="custom-table-wrapper" columns={columns} dataSource={data} size='small'
          pagination={{
              pageSize: 100, 
              onChange(current, pageSize) {
                  setPage(current);
                  setPageSize(pageSize);
              }
          }}
          />
      </Card>
  ) 
}
export default RMBudgetGrid