import { FC, useEffect, useMemo, useRef, useState } from "react";

import WorkSpace from "./WorkSpace";
import { NavigationPanel } from "./NavigationPanel";
import {
  Box,
  Modal,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";

import {
  DEFAULTCROPRULES,
  type CropModalProps,
  type EditedImage,
  type ScreenStepsTypes
} from "@/model/CropModal/CropModal";

const PriorityOfSteps = ["desktop", "tablet", "mobile", "small"];

export type EditedImagesChangeType = (changed: (old: EditedImage) => Partial<EditedImage>) => void;

export const CropModal: FC<CropModalProps> = ({
  open,
  editedImages,
  workSpaceTypes,
  originalImageUrl,

  setEditedImages,
  onSaveImageClick,
  closeCropModal,
  onDeleteClick,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(786));

  const [currentStep, setCurrentStep] = useState<number>(0);

  const currentStepName: ScreenStepsTypes = useMemo(() => {
    const mainSteps = Object.keys(workSpaceTypes);
    const POS = PriorityOfSteps.filter(POS => mainSteps.find(e => POS === e))
    return POS[currentStep] as ScreenStepsTypes
  }, [currentStep])
  const nextStepName: ScreenStepsTypes = useMemo(() => {
    const mainSteps = Object.keys(workSpaceTypes);
    const POS = PriorityOfSteps.filter(POS => mainSteps.find(e => POS === e))
    return POS[currentStep+1] as ScreenStepsTypes
  }, [currentStep])

  const editedImagesChange: EditedImagesChangeType = (changed) => {
    setEditedImages(old => {
      const newData = { ...old };
      newData[currentStepName] = { ...old[currentStepName], ...changed(old[currentStepName]) };
      return newData;
    })
  }

  const resetImage = () => {
    editedImagesChange(() => ({
      url: originalImageUrl,
      newRules: DEFAULTCROPRULES,
    }))
  }

  return (
    <Modal
      open={open}
      onClose={closeCropModal}
    >
      <Box
        sx={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          bgcolor: "background.paper",
          boxShadow: 24,
          borderRadius: "12px",
          width: isMobile ? "343px" : "620px",
          height: isMobile ? "80vh" : undefined,
          display: isMobile ? "flex" : undefined,
          flexDirection: isMobile ? "column" : undefined,
          justifyContent: isMobile ? "flex-start" : undefined,
          overflow: isMobile ? "auto" : undefined,
        }}
      >
        <Typography sx={{
          // height: isMobile ? "91px" : "70px",
          backgroundColor: "#F2F3F7",
          padding: isMobile ? "25px 20px 24px 20px" : "25px 43px 24px 20px",
          borderRadius: "8px 8px 0px 0px",
          color: "#9A9AAF",
          fontSize: "18px",
          lineHeight: "21.33px"
        }}>
          Настройте вариант отображения картинки на разных девайсах
        </Typography>
        <WorkSpace
          //Информация о изменяемой сейчас картинке
          editedImage={editedImages[currentStepName]}
          //По каким правилам меняем
          cropAspectRatio={workSpaceTypes[currentStepName].ratio}
          currentStep={currentStep}
          currentStepName={currentStepName}

          editedImagesChange={editedImagesChange}
          onDeleteClick={onDeleteClick}
        />
        <NavigationPanel
        nextStepName={nextStepName}
          currentStep={currentStep}
          setCurrentStep={setCurrentStep}
          totalSteps={Object.keys(workSpaceTypes).length}
          onSaveImageClick={onSaveImageClick}
          resetImage={resetImage}
        />

      </Box>
    </Modal>
  );
};
