import { useState, useEffect } from 'react';
import { ModalSetting } from '../common/Modal/ModalSetting';
import {
  ModalContainer,
  ModalContent,
  EditContainer,
} from '../common/Modal/ModalStyled';
import { useStages } from '../../hooks/useStages';
import { useTaskStages } from '../../hooks/useTaskStages';
import { AddStagesModal } from './AddStagesModal';
import { DeleteStageModal } from './DeleteStageModal';
import { WhitePlus } from '../common/icons/icons';
import {
  Box,
  Button,
  CircularProgress,
  IconButton,
  Stack,
  Typography,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { StagesTable } from './StagesTable/StagesTable';
import { PrimaryButton } from '../common/Buttons/Buttons';

export const SettingModal = ({
  isOpen = true,
  onClose,
  formId,
  taskId,
  mode = 'form', // 'form' | 'task'
  formTypeCode = '',
  sheets,
}) => {
  const taskStages = useTaskStages(taskId);

  const {
    deleteStage,
    stagesInfo,
    getStages,
    createStage,
    updateStage,
    isSaving,
  } = taskStages;

  const isTaskMode = mode === 'task';
  const entityId = taskId;

  useEffect(() => {
    if (isOpen && entityId) {
      getStages();
    }
  }, [isOpen, entityId, getStages]);

  const [isAddEditModalOpen, setIsAddEditModalOpen] = useState(false);
  const [stageForEdit, setStageForEdit] = useState(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [stageToDelete, setStageToDelete] = useState(null);
  const [sheetOptions, setSheetOptions] = useState([]);

  const handleAddStage = () => {
    setStageForEdit(null);
    setIsAddEditModalOpen(true);
  };

  const handleDeleteStage = (stage) => {
    setStageToDelete(stage);
    setIsDeleteModalOpen(true);
  };

  const handleConfirmDelete = (stage) => {
    deleteStage(stage);
  };

  const handleEditStage = (stage) => {
    setStageForEdit(stage);
    setIsAddEditModalOpen(true);
  };
  const transformToSheetOptions = (data) => {
    // TO DO пока не добавили direction для этапов

    // const sheetMap = new Map();

    // data.forEach(item => {
    //   const key = item.direction ? `${item.sheet}_${item.direction}` : item.sheet;

    //   if (!sheetMap.has(key)) {
    //     sheetMap.set(key, {
    //       sheet: item.sheet,
    //       direction: item.direction,
    //       names: []
    //     });
    //   }

    //   const entry = sheetMap.get(key);
    //   if (!entry.names.includes(item.name)) {
    //     entry.names.push(item.name);
    //   }
    // });

    // const sheetOptions = [];

    // sheetMap.forEach((value) => {
    //   let label = value.names.join(' / ');

    //   if (value.direction) {
    //     label += ` (${value.direction})`;
    //   }

    //   sheetOptions.push({
    //     value: value.direction ? `${value.sheet}_${value.direction}` : value.sheet,
    //     label: label,
    //     sheet: value.sheet,
    //     direction: value.direction
    //   });
    // });

    // return sheetOptions;

    const sheetOptions = [];
    data.forEach((value) => {
      if (sheetOptions.find(s => s.sheet == value.sheet)) {
        return;
      }

      sheetOptions.push({
        value: value.sheet,
        label: value.name,
        sheet: value.sheet,
        direction: value.direction,
      })
    })

    return sheetOptions;
  };

  useEffect(() => {
    if (!sheets || sheets.length === 0) return;
    setSheetOptions(transformToSheetOptions(sheets))
  }, [sheets])

  if (!isOpen) {
    return null;
  }

  return (
    <>
      <ModalSetting
        isOpen={isOpen}
        onClose={onClose}
        children={
          <ModalContainer>
            <ModalContent>
              <Stack
                direction="row"
                sx={{ width: '100%', justifyContent: 'flex-end' }}
              >
                <IconButton size="small" onClick={onClose}>
                  <CloseIcon />
                </IconButton>
              </Stack>

              <EditContainer>
                <Stack
                  direction="row"
                  sx={{ width: '100%', justifyContent: 'space-between' }}
                >
                  <Typography fontWeight="bold">Этапы</Typography>

                  <PrimaryButton
                    onClick={handleAddStage}
                    startIcon={<WhitePlus />}
                  >
                    Добавить этап
                  </PrimaryButton>

                </Stack>

                {stagesInfo.isLoading ? (
                  <Box
                    sx={{
                      display: 'flex',
                      justifyContent: 'center',
                      py: 4,
                    }}
                  >
                    <CircularProgress />
                  </Box>
                ) : (
                  <StagesTable
                    stages={stagesInfo.stages || []}
                    onEdit={handleEditStage}
                    onDelete={!isTaskMode ? handleDeleteStage : undefined}
                  />
                )}
                <AddStagesModal
                  isOpen={isAddEditModalOpen}
                  onClose={() => {
                    setIsAddEditModalOpen(false);
                  }}
                  stage={stageForEdit}
                  createStage={createStage}
                  updateStage={updateStage}
                  isTaskMode={isTaskMode}
                  isSaving={isSaving}
                  sheetOptions={sheetOptions}
                  formType={formTypeCode}
                />
                {!isTaskMode && (
                  <DeleteStageModal
                    isOpen={isDeleteModalOpen}
                    onClose={() => {
                      setIsDeleteModalOpen(false);
                      setStageToDelete(null);
                    }}
                    onConfirm={handleConfirmDelete}
                    stage={stageToDelete}
                  />
                )}
              </EditContainer>
            </ModalContent>
          </ModalContainer>
        }
      ></ModalSetting>
    </>
  );
};
