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 {  FgPriceListRequest, FgPriceListResponseModel, FixedComponentsRateChartRequest } from "@gtpl/shared-models/masters";
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 {  FixedComponentsRateChartService } from "@gtpl/shared-services/masters";
import { FgDamagesResponseModel } from "@gtpl/shared-models/warehouse-management";

export function FixedComponentsRateChartGrid(){
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const service = new FixedComponentsRateChartService()
  const [data,setData] = useState<FixedComponentsRateChartRequest[]>([])
  const [searchText, setSearchText] = useState("");
const [searchedColumn, setSearchedColumn] = useState("");
const searchInput = useRef(null);

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

  const getInfo = () => {
      service.getAllFixedComponentsRateChartInfo().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:'Destination',
          title:<div style={{textAlign:"center"}}>Electricity cost</div>,
          dataIndex:'ElectricityCost',
          sorter: (a, b) => a.ElectricityCost.localeCompare(b.ElectricityCost),
          sortDirections: ["ascend", "descend"],
          render: (text) => text ? text : "-",
          ...getColumnSearchProps('ElectricityCost') 
      },
      {
        title: ' Fuel cost',
        dataIndex: 'FuelCost',
        sorter: (a, b) => {
            const codeA = (a.FuelCost || "").toString();
            const codeB = (b.FuelCost || "").toString();
            return codeA.localeCompare(codeB);
        },
        sortDirections: ["ascend", "descend"],
        render: (text) => text ? text : "-",
        ...getColumnSearchProps('FuelCost')
    },
    {
        // title:'Buyer Address',
        title:<div style={{textAlign:"center"}}>Consumables</div>,
        dataIndex:'consumables',
        sorter: (a, b) => a.consumables.localeCompare(b.consumables),
        sortDirections: ["ascend", "descend"],
        render: (text) => text ? text : "-",
        ...getColumnSearchProps('consumables')       
       
    },
    {
      title:<div style={{textAlign:"center"}}>QC Cost</div>,
      dataIndex:'QcCost',
      sorter: (a, b) => a.QcCost.localeCompare(b.QcCost),
      sortDirections: ["ascend", "descend"],
      render: (text) => text ? text : "-",
      ...getColumnSearchProps('QcCost') 
  },
  {
    title:<div style={{textAlign:"center"}}>Repair and Maintenance</div>,
    dataIndex:'RepairAndMaintenance',
    sorter: (a, b) => a.RepairAndMaintenance.localeCompare(b.RepairAndMaintenance),
    sortDirections: ["ascend", "descend"],
    render: (text) => text ? text : "-",
    ...getColumnSearchProps('RepairAndMaintenance') 
},
{
  title:<div style={{textAlign:"center"}}> Employee Cost</div>,
  dataIndex:'EmployeeCost',
  sorter: (a, b) => a.EmployeeCost.localeCompare(b.EmployeeCost),
  sortDirections: ["ascend", "descend"],
  render: (text) => text ? text : "-",
  ...getColumnSearchProps('EmployeeCost') 
},
{
  title:<div style={{textAlign:"center"}}>Finance cost</div>,
  dataIndex:'FinanceCost',
  sorter: (a, b) => a.FinanceCost.localeCompare(b.FinanceCost),
  sortDirections: ["ascend", "descend"],
  render: (text) => text ? text : "-",
  ...getColumnSearchProps('FinanceCost') 
},
{
  title:<div style={{textAlign:"center"}}> Asset Depreciation Cost</div>,
  dataIndex:'AssetDepreciationCost',
  sorter: (a, b) => a.AssetDepreciationCost.localeCompare(b.AssetDepreciationCost),
  sortDirections: ["ascend", "descend"],
  render: (text) => text ? text : "-",
  ...getColumnSearchProps('AssetDepreciationCost') 
},
  ]

  let i = 1;
  let rowIndex = 1;
  const exceldata = [
      { title: 'S No', dataIndex: 'sNo', render: (text, object, index) => { 
          if(index == data.length) { 
            return null;
          } else { 
            return index+1
          } 
        },
        width: 60, 
       
      }, 
      { title: 'Product', dataIndex: 'product',width: 100,render:(text:any,record:any) => {return record.product ? record.product : '-'} },  
      { title: 'Pack Style', dataIndex: 'packStyle',width: 100,render:(text:any,record:any) => {return record.packStyle ? record.packStyle : '-'} },
      { title: 'Category', dataIndex: 'category',width: 500,render:(text:any,record:any) => {return record.category ? record.category : '-'} },     
      { title: 'Price ', dataIndex: 'price',width: 100,render:(text:any,record:any) => {return record.price ? record.price : '-'} },
      

  ]




  const exportExcel = () => {
      const excel = new Excel();
      excel
        .addSheet('FG Price List Excel')
        .addColumns(exceldata)
        .addDataSource(data, { str2num: false })
        .saveAs('FG Price List.xlsx');
    }
  return(
      <Card title={<span style={{color:'white'}}>FG Price List</span>}
       extra={<Link to='/Fixed-components-rate-chart-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 FixedComponentsRateChartGrid