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, PackingMaterialPricesRequest } from "@gtpl/shared-models/masters";

import { ColumnProps } from "antd/lib/table";
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 { FgPriceListService, PackingMaterialPriceService } from "@gtpl/shared-services/masters";
import moment from "moment";

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

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

  const getInfo = () => {
      service.getAllPackingMaterialPricesInfo().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"}}>Packing Date</div>,
        dataIndex:'updatedAt',
        sorter: (a, b) => a.updatedAt.localeCompare(b.updatedAt),
        sortDirections: ["ascend", "descend"],
        render: (value, record) => {
          return moment(record.updatedAt).format('DD-MM-YYYY');
      },
    },
   
      {
          // title:'Destination',
          title:<div style={{textAlign:"center"}}>Product</div>,
          dataIndex:'product',
          sorter: (a, b) => a.product.localeCompare(b.product),
          sortDirections: ["ascend", "descend"],
          render: (text) => text ? text : "-",
          ...getColumnSearchProps('product') 
      },
     
     
      {
        title: 'Packing Style',
        dataIndex: 'packStyle',
        sorter: (a, b) => {
            const codeA = (a.packStyle || "").toString();
            const codeB = (b.packStyle || "").toString();
            return codeA.localeCompare(codeB);
        },
        sortDirections: ["ascend", "descend"],
        render: (text) => text ? text : "-",
        ...getColumnSearchProps('packStyle')
    },
    // {
    //     // title:'Buyer Address',
    //     title:<div style={{textAlign:"center"}}>Category</div>,
    //     dataIndex:'category',
    //     sorter: (a, b) => a.category.localeCompare(b.category),
    //     sortDirections: ["ascend", "descend"],
    //     render: (text) => text ? text : "-",
    //     ...getColumnSearchProps('category')       
       
    // },
    {
      title:<div style={{textAlign:"center"}}>Price</div>,
      align:'right',
      dataIndex:'price',
  },
  ]

  let i = 1;
  let rowIndex = 1;
  const exceldata = [
      { title: 'SNo', 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: 'PackStyle', 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('Packing Material Prices Excel')
        .addColumns(exceldata)
        .addDataSource(data, { str2num: false })
        .saveAs('Packing Material Prices.xlsx');
    }
  return(
      <Card title={<span style={{color:'white'}}>Packing Material Prices</span>}  
      size='small'
        style={{color:'white',textAlign:'center'}} 
        headStyle={{ backgroundColor: "#69c0ff", border: 0 }}
       extra={<Link to='/packing-material-prices-excel-upload' >
      <span style={{color:'white'}} ><Button className="panel_button" >New</Button> </span>
      </Link>}
      >
          <Row justify={'end'}>
          <Button
              type="default"
              style={{ color: "green",padding:5 }}
              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 PackingMaterialPricesGrid