import React, { useEffect, useRef, useState } from 'react';
import Table, { ColumnProps } from "antd/lib/table";
import { Button, Card, Form, Input, Popconfirm, Select, Switch, Tag, message } from "antd";
import { SearchOutlined, CheckCircleOutlined, RightSquareOutlined, CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';

import { GlobalPriceChartService } from "@gtpl/shared-services/masters";
import { GlobalPriceChartRequest, GlobalPriceType, TypeEnum } from '@gtpl/shared-models/masters';


/* eslint-disable-next-line */
export interface GlobalPriceChartProps {}

export function GlobalPriceChartGrid(
  props: GlobalPriceChartProps
) {

  const searchInput = useRef(null);
  const [form] = Form.useForm();
  const [page, setPage] = React.useState(1);
  const [searchText, setSearchText] = useState(''); 
  const [searchedColumn, setSearchedColumn] = useState('');
  const [ mainData, setMainData ] = useState<any[]>([])
  const [editingKey, setEditingKey] = useState('');
  const [editedData, setEditedData] = useState<any>({});
  const [ addRow, setAddRow ] = useState(false)
  const { Option } = Select;

  const globalPriceService = new GlobalPriceChartService()

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


  const getAllPriceCharts = () =>{
    globalPriceService.getAllPriceCharts().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 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 edit = (record: any) => {
    if (editedData.component === '' || editedData.price === '' || editedData.type === '') {
      const errorMessage = `${editedData.component === '' ? editedData.price === ''?'Component' : 'Price':'Type'} field is required.`;
      message.error(errorMessage, 2);
    } else {
      setEditingKey(record.id);
      setEditedData(record);
    }
  };
  
  const cancel = () => {if (!editedData.component && !editedData.price) {
    const newData = mainData.filter(item => item.id !== editingKey);
    setMainData(newData);
  }
    setEditingKey('');
    setEditedData({});
  };

  const saveData = (record)=>{
    if (editedData.component === '' || editedData.price === ''|| editedData.type === '') {
      const errorMessage = `${editedData.component === '' ? editedData.price === ''?'Component' : 'Price':'Type'} field is required.`;
      message.error(errorMessage, 2);
    } else {
      const updatedData = { ...record, ...editedData };
      const req = new GlobalPriceChartRequest(updatedData.id, updatedData.component, updatedData.price, updatedData.type);
      globalPriceService.updatePriceCharts(req).then((res)=>{
        if(res.status){
          message.success(res.internalMessage, 2);
          getAllPriceCharts()
          setEditingKey('');
          setEditedData({});
        } else {
          message.error(res.internalMessage, 2);
        }
      });
    }
  };
  
  
  const isEditing = (record: any) => record.id === editingKey;

  const columnsSkelton: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      render: (text, object, index) => (page-1) * 10 +(index+1)
    },
    {
      title: 'Component',
      dataIndex: 'component',
      sorter: (a, b) => a.component.localeCompare(b.component),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('component'),
      render: (text: string, record: any) => {
        if (addRow && record.id === mainData[mainData.length - 1].id) { // Render input only for newly added row
          return (
            <Input
              value={editedData.component}
              onChange={(e) => setEditedData({ ...editedData, component: e.target.value })}
            />
          );
        } else {
          return text; // Render text for other cases
        }
      }
    },
    {
      title: 'Price',
      dataIndex: 'price',
      sorter: (a, b) => a.price.localeCompare(b.price),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('price'),
      render: (text: string, record: any) => {
        if (isEditing(record)) {
          return (
            <Input
              value={editedData.price}
              onChange={(e) => setEditedData({ ...editedData, price: e.target.value })}
            />
          );
        }
        return text;
      }
    },
    {
      title: 'Type',
      dataIndex: 'type',
      sorter: (a, b) => a.type-b.type,
      sortDirections: ["ascend", "descend"],
      render: (text: string, record: any) => {
        if (isEditing(record)) {
            return (
              <Select 
              value={editedData.type} 
              placeholder='Type'
              showSearch
              allowClear
              onChange={(value) => {
                // console.log("Selected type:", value); // Log the selected value
                setEditedData({ ...editedData, type: value }); // Update editedData state
              }}
            >{Object.values(GlobalPriceType).map((i) => {
                return (
                  <Option key={i} value={i}>
                    {i}
                  </Option>
                );
              })}
            </Select>
          );
        }
        return text;
      }
    },
    {
      title: 'Action',
      dataIndex: 'action',
      align:'center',
      render: (_: any, record: any) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button
              type="primary"
              icon={<CheckCircleOutlined />}
              onClick={() => saveData(record)}
              style={{ marginRight: 8 }}
            >
              Save
            </Button>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <Button icon={<CloseCircleOutlined />} type="default">Cancel</Button>
            </Popconfirm>
          </span>
        ) : (
          <Button
            disabled={editingKey !== ''}
            type="default"
            icon={<RightSquareOutlined />}
            onClick={() => edit(record)}
          >
            Edit
          </Button>
        );
      },
    },
  ];
  
  return (
    <Card title={<span style={{color:'white'}}>Global Price Chart</span>}
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}>
      <Table
          rowKey={record => record.id}
          columns={columnsSkelton}
          dataSource={mainData}
          pagination={{
            pageSize:50,
            onChange(current) {
              setPage(current);
            }
          }}
          bordered />
          <Button
            type="primary"
            style={{ marginBottom: 16 }}
            onClick={() => {
              const newData = {
                id: Date.now(),
                component: '',
                price: '',
              };
              setMainData([...mainData, newData]);
              edit(newData);
              setAddRow(true)
            }}
          >
            <PlusOutlined /> Add Row
          </Button>
    </Card>
  )
}

export default GlobalPriceChartGrid;
