import React, { useEffect, useRef } from 'react';
import { useAtom } from 'jotai';

// Shared
import { TableColumn } from '../../shared/interface';
import {
  visibleColumnsAtom,
  initialVisibleColumns,
  useToggleColumn,
} from '../../store/store';
import {
  StyledFilterData,
  StyledFilterDataCover,
  StyledFilterOptions,
  StyledSvgCover,
} from './TableFilterStyle';

// Componets
import CheckBoxWrapper from '../checkbox-wrapper/CheckBoxWrapper';
import BulkFilterIcon from '../../../../assets/icons/BulkFilterIcon';

// Interface & Types
interface TableFilterProps {
  tableData: TableColumn[];
}

const StyledTableFilter: React.FC<TableFilterProps> = ({ tableData }) => {
  // States
  const [isDropdownOpen, setIsDropdownOpen] = useToggleColumn();
  const [visibleColumns, setVisibleColumns] = useAtom(visibleColumnsAtom);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Hooks
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [setIsDropdownOpen]);

  useEffect(() => {
    const storedColumns = localStorage.getItem('visibleColumnsOrder');
    if (storedColumns) {
      setVisibleColumns(JSON.parse(storedColumns));
    } else {
      setVisibleColumns(initialVisibleColumns(tableData));
    }
  }, [tableData, setVisibleColumns]);

  useEffect(() => {
    localStorage.setItem('visibleColumnsOrder', JSON.stringify(visibleColumns));
  }, [visibleColumns]);

  // Functions
  const handleColumnVisibilityChange = (key: string) => {
    setVisibleColumns((prevState: any) =>
      prevState.includes(key)
        ? prevState.filter((col: any) => col !== key)
        : [...prevState, key]
    );
  };

  const toggleMenu = () => {
    setIsDropdownOpen((prevState: any) => !prevState);
  };

  return (
    <StyledFilterDataCover>
      <StyledFilterData onClick={toggleMenu}>
        <StyledSvgCover>
          <BulkFilterIcon />
        </StyledSvgCover>
      </StyledFilterData>

      {isDropdownOpen && (
        <div ref={dropdownRef}>
          <StyledFilterOptions>
            <CheckBoxWrapper
              columns={tableData}
              visibleColumns={visibleColumns}
              handleColumnVisibilityChange={handleColumnVisibilityChange}
            />
          </StyledFilterOptions>
        </div>
      )}
    </StyledFilterDataCover>
  );
};

export default StyledTableFilter;
