import { useEffect } from "react";
import { useParams } from "react-router-dom";
import {
  Box,
  Button,
  Typography,
  Tooltip,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import CustomCheckbox from "@ui_kit/CustomCheckbox";
import CustomTextField from "@ui_kit/CustomTextField";
import { useDebouncedCallback } from "use-debounce";

import { questionStore, updateQuestionsList } from "@root/questions";

import InfoIcon from "../../../assets/icons/InfoIcon";
import FormatIcon2 from "../../../assets/icons/questionsPage/FormatIcon2";
import FormatIcon1 from "../../../assets/icons/questionsPage/FormatIcon1";
import ProportionsIcon11 from "../../../assets/icons/questionsPage/ProportionsIcon11";
import ProportionsIcon21 from "../../../assets/icons/questionsPage/ProportionsIcon21";
import ProportionsIcon12 from "../../../assets/icons/questionsPage/ProportionsIcon12";

interface Props {
  Icon: React.ElementType;
  isActive?: boolean;
  onClick: () => void;
}

type SettingOpytionsPictProps = {
  totalIndex: number;
};

const PROPORTIONS = [
  { value: "1:1", icon: ProportionsIcon11 },
  { value: "2:1", icon: ProportionsIcon21 },
  { value: "1:2", icon: ProportionsIcon12 },
];

export function SelectIconButton({ Icon, isActive = false, onClick }: Props) {
  const theme = useTheme();

  return (
    <Button
      onClick={onClick}
      variant="outlined"
      startIcon={
        <Icon
          color={
            isActive
              ? theme.palette.navbarbg.main
              : theme.palette.brightPurple.main
          }
        />
      }
      sx={{
        backgroundColor: isActive ? theme.palette.brightPurple.main : "#eee4fc",
        borderRadius: 0,
        border: "none",
        color: isActive
          ? theme.palette.brightPurple.main
          : theme.palette.grey2.main,
        p: "7px",
        width: "auto",
        minWidth: 0,
        "& .MuiButton-startIcon": {
          mr: 0,
          ml: 0,
        },
        "&:hover": {
          border: "none",
          borderColor: isActive
            ? theme.palette.brightPurple.main
            : theme.palette.grey2.main,
        },
      }}
    />
  );
}

export default function SettingOpytionsPict({
  totalIndex,
}: SettingOpytionsPictProps) {
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const debounced = useDebouncedCallback((value) => {
    let clonContent = listQuestions[quizId][totalIndex].content;
    clonContent.innerName = value;
    updateQuestionsList(quizId, totalIndex, {
      content: clonContent,
    });
  }, 1000);

  useEffect(() => {
    if (!listQuestions[quizId][totalIndex].content.xy) {
      updateProportions("1:1");
    }
  }, []);

  const updateProportions = (proportions: string) => {
    const clonContent = listQuestions[quizId][totalIndex].content;
    clonContent.xy = proportions;
    updateQuestionsList(quizId, totalIndex, { content: clonContent });
  };

  return (
    <>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          flexDirection: isTablet ? "column" : null,
          marginRight: isMobile ? "0px" : "30px",
        }}
      >
        <Box sx={{ pt: "20px", pb: "20px", pl: "20px" }}>
          <Typography sx={{ marginBottom: "15px" }}>Пропорции</Typography>
          <Box
            sx={{
              display: "flex",
              gap: "10px",
              marginBottom: "20px",
            }}
          >
            {PROPORTIONS.map(({ value, icon }, index) => (
              <SelectIconButton
                key={index}
                onClick={() => updateProportions(value)}
                isActive={
                  listQuestions[quizId][totalIndex].content.xy === value
                }
                Icon={icon}
              />
            ))}
          </Box>

          <Typography sx={{ marginBottom: "15px" }}>
            Настройки ответов
          </Typography>

          <CustomCheckbox
            sx={{ display: "block", mr: isMobile ? "0px" : "16px" }}
            label={"Можно несколько"}
            checked={listQuestions[quizId][totalIndex].content.multi}
            handleChange={({ target }) =>
              updateQuestionsList(quizId, totalIndex, {
                content: {
                  ...listQuestions[quizId][totalIndex].content,
                  multi: target.checked,
                },
              })
            }
          />
          <CustomCheckbox
            sx={{ display: "block", mr: isMobile ? "0px" : "16px" }}
            label={"Большие картинки"}
            checked={listQuestions[quizId][totalIndex].content.largeCheck}
            handleChange={({ target }) =>
              updateQuestionsList(quizId, totalIndex, {
                content: {
                  ...listQuestions[quizId][totalIndex].content,
                  largeCheck: target.checked,
                },
              })
            }
          />
          <CustomCheckbox
            sx={{ display: "block", mr: isMobile ? "0px" : "16px" }}
            label={'Вариант "свой ответ"'}
            checked={listQuestions[quizId][totalIndex].content.own}
            handleChange={({ target }) =>
              updateQuestionsList(quizId, totalIndex, {
                content: {
                  ...listQuestions[quizId][totalIndex].content,
                  own: target.checked,
                },
              })
            }
          />
        </Box>
        <Box sx={{ padding: "20px", minWidth: isMobile ? "100%" : "350px" }}>
          <Typography sx={{ marginBottom: "15px" }}>Форма</Typography>
          <Box
            sx={{
              display: "flex",
              gap: "10px",
              marginBottom: "20px",
            }}
          >
            <SelectIconButton
              onClick={() =>
                updateQuestionsList(quizId, totalIndex, {
                  content: {
                    ...listQuestions[quizId][totalIndex].content,
                    format: "carousel",
                  },
                })
              }
              isActive={
                listQuestions[quizId][totalIndex].content.format === "carousel"
              }
              Icon={FormatIcon2}
            />
            <SelectIconButton
              onClick={() =>
                updateQuestionsList(quizId, totalIndex, {
                  content: {
                    ...listQuestions[quizId][totalIndex].content,
                    format: "masonry",
                  },
                })
              }
              isActive={
                listQuestions[quizId][totalIndex].content.format === "masonry"
              }
              Icon={FormatIcon1}
            />
          </Box>
          <Typography sx={{ marginBottom: "15px" }}>
            Настройки вопросов
          </Typography>
          <CustomCheckbox
            label={"Необязательный вопрос"}
            checked={listQuestions[quizId][totalIndex].content.required}
            handleChange={({ target }) =>
              updateQuestionsList(quizId, totalIndex, {
                content: {
                  ...listQuestions[quizId][totalIndex].content,
                  required: target.checked,
                },
              })
            }
          />
          <Box sx={{ width: isMobile ? "90%" : "auto", display: "flex", alignItems: "center" }}>
            <CustomCheckbox
              label={"Внутреннее название вопроса"}
              checked={listQuestions[quizId][totalIndex].content.innerNameCheck}
              handleChange={({ target }) =>
                updateQuestionsList(quizId, totalIndex, {
                  content: {
                    ...listQuestions[quizId][totalIndex].content,
                    innerNameCheck: target.checked,
                    innerName: "",
                  },
                })
              }
            />
            <Tooltip
              title="Будет отображаться как заголовок вопроса в приходящих заявках."
              placement="top"
            >
              <Box>
                <InfoIcon />
              </Box>
            </Tooltip>
          </Box>
          {listQuestions[quizId][totalIndex].content.innerNameCheck && (
            <CustomTextField
              placeholder={"Внутреннее описание вопроса"}
              text={listQuestions[quizId][totalIndex].content.innerName}
              onChange={({ target }) => debounced(target.value)}
            />
          )}
        </Box>
      </Box>
    </>
  );
}
