import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { Panel } from './SettingPanel.style';
import { Divider, IconButton, Stack, Tooltip } from '@mui/material';

import { GroupByObject } from './GroupByObject/GroupByObject';
import { ColorPickerButton } from './ColorPicker/ColorPickerButton';
import {
  AddLine,
  FormulaSettingPanel,
  Minus,
  Pin,
  Plus,
  Program,
  Project,
  RemoveLine,
  Search,
} from '../../common/icons/icons';
import CollapsibleTree from '../../common/CollapsibleTree';
import ZoomSlider from './ZoomSlider';
import SearchComponent from '../../common/SearchComponent';
import { ExportDefaultButton } from '../../common/Buttons/ButtonsActions';
import { exportSheet, exportSheetProject } from '../../../utils/exportFile';
import { FORM_TYPE_OPTIONS } from '../../../constants/constants';

const SettingPanel = ({
  selectedColumnId,
  columnPinning,
  table,
  columns,
  onPinColumn,
  onUnpinColumn,
  onToggleColumnVisibility,
  columnVisibility,
  onChangeSizeMult,
  onGlobalFilterChange,
  sizeMult,
  onChangeShowColumnFilters,
  onAddRow,
  onAddProgram,
  onAddProject,
  onDeleteRow,
  isLoadingData,
  formId,
  sheetName,
  direction,
  year,
  isProject,
  formType,
}) => {
  const [isPinned, setIsPinned] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [selectedColumnIds, setSelectedColumnIds] = useState();
  const [showColumnFilters, setShowColumnFilters] = useState(false);

  useEffect(() => {
    if (!selectedColumnId) {
      setIsPinned(false);
      return;
    }
    const pinningColumn = columnPinning?.left || table.getState().columnPinning.left || [];
    const pinned = pinningColumn.includes(selectedColumnId);
    setIsPinned(pinned);
  }, [selectedColumnId, columnPinning, table]);

  useEffect(() => {
    setSelectedColumnIds(
      Object.keys(columnVisibility).filter((key) => !columnVisibility[key]),
    );
  }, [columnVisibility]);

  //TO DO: сделать
  const { addColorForCells,} = {};

  const handleChangeShowColumnFilters = () => {
    const show = table.getState().showColumnFilters;
    setShowColumnFilters(!show);
    onChangeShowColumnFilters(!show);
  };

  const handleExport = async () => {
    if (isExporting) return;
    if (isProject) {
      if (!formId || !sheetName || !year) return;
      setIsExporting(true);
      await exportSheetProject(formId, sheetName, year);
      setIsExporting(false);
      return;
    }

    if (!formId || !sheetName) return;
    setIsExporting(true);
    await exportSheet(formId, sheetName, direction);
    setIsExporting(false);
  };

  return (
    <>
      <Panel data-pin-panel>
        <Stack direction="row" sx={{ gap: '1.25rem' }}>
          <GroupByObject title="Отображение">
            {/* <ColorPickerButton onColorApply={addColorForCells} /> */}

            <Tooltip title="Закрепить область">
              <IconButton
                variant="outlined"
                data-active={isPinned}
                disabled={!selectedColumnId}
                onMouseDown={(e) => e.stopPropagation()}
                onClick={() => {
                  if (!selectedColumnId) {
                    console.warn('[ColumnPin] клик Pin: selectedColumnId пустой');
                    return;
                  }
                  isPinned
                    ? onUnpinColumn?.(selectedColumnId)
                    : onPinColumn?.(selectedColumnId);
                }}
              >
                <Pin />
              </IconButton>
            </Tooltip>
          </GroupByObject>

          {!isProject &&
            <>
              <Divider orientation="vertical" flexItem />
              <GroupByObject title="Строки">
                <Tooltip title="Добавить строку">
                  <IconButton onClick={onAddRow} variant="outlined">
                    <Plus />
                    <AddLine />
                  </IconButton>
                </Tooltip>

                <Tooltip title="Удалить строку">
                  <IconButton onClick={onDeleteRow} variant="outlined">
                    <Minus />
                    <RemoveLine />
                  </IconButton>
                </Tooltip>
                {/* проверяем на 4 форму */}
                {formType == FORM_TYPE_OPTIONS[3] && <>

                  <Tooltip title="Добавить программу">
                    <IconButton onClick={onAddProgram} variant="outlined">
                      <Plus />
                      <Program />
                    </IconButton>
                  </Tooltip>

                  <Tooltip title="Добавить проект">
                    <IconButton onClick={onAddProject} variant="outlined">
                      <Plus />
                      <Project />
                    </IconButton>
                  </Tooltip>
                </>}
              </GroupByObject>
            </>
          }
          <Divider orientation="vertical" flexItem />
          <GroupByObject title="Столбцы">
            {columns ? (
              <CollapsibleTree
                columnTree={columns}
                onSelectNode={onToggleColumnVisibility}
                selectedIds={selectedColumnIds}
              />
            ) : (
              ''
            )}
          </GroupByObject>
          <Divider orientation="vertical" flexItem />
          <ZoomSlider onChange={onChangeSizeMult} curScale={sizeMult} />
          <Divider orientation="vertical" flexItem />
          <GroupByObject title="Поиск">
            <SearchComponent onChange={onGlobalFilterChange} height="2.5rem" />
            <Tooltip title="Поиск по колонкам">
              <IconButton
                variant="outlined"
                color="success"
                data-active={showColumnFilters}
                onClick={handleChangeShowColumnFilters}
              >
                <Search />
              </IconButton>
            </Tooltip>
          </GroupByObject>

          <Divider orientation="vertical" flexItem />

          <GroupByObject title="Экспорт">
            <ExportDefaultButton
              onClick={handleExport}
              disabled={!formId || !sheetName || isExporting}
              text={isExporting ? 'Экспорт...' : 'Экспорт'}
            />
          </GroupByObject>
        </Stack>
      </Panel>
    </>
  );
};

export default SettingPanel;
