import React, {useState, useEffect, useRef} from 'react';
import {Table, Select} from 'antd';
import './index.less';

export interface TableSelectProps {
  value?: any;
  onChange?: (value: any) => void;
  onSelect?: (value: any) => void;
  onSearch?: (value: any) => void;
  columns?: any[];
  dataSource?: any[];
  options: {
    LABEL: string;
    value: string;
  };
  type?: 'radio' | 'checkbox';
  disabled: boolean,
  searchFromApi: boolean
}

const TableSelect: React.FC<TableSelectProps> = (props) => {
  const {onSearch,onChange, onSelect, columns, dataSource = [], options, type = 'radio', value, disabled, searchFromApi = false} = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([]);
  const [selectValue, setSelectValue] = useState<any>(null);
  const [selectOpen, setSelectOPen] = useState<boolean>(false);
  const [searchVal, setSearchVal] = useState<any>('');
  const [filterData, setFilterData] = useState<any[]>(dataSource);
  const selectRef = useRef();
  useEffect(() => {
    if (!searchFromApi) {
      if (searchVal) {
        const list = dataSource?.filter((x) => x[options.LABEL].indexOf(searchVal) > -1);
        setFilterData(list);
      } else {
        setFilterData(dataSource);
      }
    }
  }, [searchVal, dataSource]);
  useEffect(() => {
    if (searchFromApi) {
      setFilterData(dataSource);
    }
  }, [dataSource])
  useEffect(() => {
    if (searchFromApi) {
      if (onSearch) {
        onSearch(searchVal)
      }
    }
  }, [searchVal])
  useEffect(() => {
    if (value) {
      setSelectValue(value);
      setSelectedRowKeys([value]);
      if (onChange) { 
        onChange(value)
      }
    } else {
      setSelectValue('');
      setSelectedRowKeys([]);
    }
  }, [value]);
  const {Option} = Select;
  return (
      <>
        <Select
            // @ts-ignore
            ref={selectRef}
            disabled={disabled}
            showSearch
            allowClear
            onClear={() => {
              setSelectValue('')
              if (onChange) { 
                onChange('')
              }
              setSelectedRowKeys([])
            }}
            onFocus={() => {
              setSelectOPen(true);
            }}
            onBlur={() => {
              setSelectOPen(false);
            }}
            onSearch={(val) => {
              setSearchVal(val);
            }}
            listHeight={400}
            value={selectValue}
            open={selectOpen}
            dropdownClassName="antdTableSelectDropdown"
            dropdownRender={(menu) => (
                <div onMouseDown={e => {
                  e.preventDefault()
                }}>
                  <div style={{display: 'none'}}>{menu}</div>
                  <Table
                      size="small"
                      columns={columns}
                      rowKey={(r: any) => r[options.value]}
                      rowSelection={{
                        type,
                        onChange: (selKeys: any) => {
                          setSelectedRowKeys(selKeys);
                        },
                        selectedRowKeys,
                        columnWidth: '30px',
                      }}
                      pagination={{
                        pageSize: 50,
                        showLessItems: true,
                        showSizeChanger: false,
                        hideOnSinglePage: true,
                      }}
                      scroll={{y: 350}}
                      onRow={(record: any) => {
                        return {
                          onClick: () => {
                            console.log('click')
                            const key = record[options.value];
                            if (type === 'checkbox') {
                              const set = new Set(selectedRowKeys);
                              if (set.has(key)) {
                                set.delete(key);
                              } else {
                                set.add(key);
                              }
                              setSelectedRowKeys([...set]);
                            } else {
                              setSelectedRowKeys([key]);
                              setSelectValue(key);
                              if (onSelect) {
                                onSelect(key);
                              }
                              if (onChange) { 
                                onChange(key)
                              }
                              // @ts-ignore
                              selectRef.current.blur()
                            }
                          },
                        };
                      }}
                      dataSource={filterData}
                  />
                </div>
            )}
        >
          {dataSource?.map((item) => (
              <Option key={item[options.value]} value={item[options.value]}>
                {item[options.LABEL]}
              </Option>
          ))}
        </Select>
      </>
  );
};

export default TableSelect;
