import { FC, useState } from "react";
import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
import { ItemsSelectionView } from "../Questions/ItemsSelectionView/ItemsSelectionView";
import { TagsDetailsView } from "./TagsDetailsView/TagsDetailsView";
import { MinifiedData, QuestionKeys, SelectedTags, TagKeys, TagQuestionHC } from "../types";
import { DataConstrictor } from "../Components/DataConstrictor";
import { ModalTitle } from "../ModalTitle";
import { StepButtonsBlock } from "../StepButtonsBlock";
import { resetAmoTagsFields } from "../useAmoIntegration";

type Props = {
  tagsItems: MinifiedData[] | [];
  selectedTags: SelectedTags;
  handleAddTag: (scope: QuestionKeys | TagKeys, id: string, type: "question" | "tag") => void;
  openDelete: (data: TagQuestionHC) => void;
  handlePrevStep: () => void;
  handleNextStep: () => void;
  titleProps: {
    step: number;
    title: string;
    desc: string;
    toSettings: () => void;
  }
  onScroll: () => void;

};

export const AmoTags: FC<Props> = ({
  tagsItems,
  selectedTags,
  handleAddTag,
  openDelete,
  handlePrevStep,
  handleNextStep,
  onScroll,
  titleProps,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(600));
  const [sortedTagsItems, setSortedTagsItems] = useState<MinifiedData[] | []>(tagsItems);

  const [isSelection, setIsSelection] = useState<boolean>(false);
  const [activeScope, setActiveScope] = useState<TagKeys | null>(null);
  const [selectedTag, setSelectedTag] = useState<string | null>(null);

  const handleAdd = () => {
    if (activeScope === null || selectedTag === null) return;
    setActiveScope(null);
    handleAddTag(activeScope, selectedTag, "tag");
  };
  const handleDelete = (id: string, scope: TagKeys) => {
    openDelete({
      id,
      scope,
      type: "tag",
    });
  };
  const startConstrictor = (substr: string) => {
    const a = tagsItems.filter((mData) => mData.title.toLowerCase().startsWith(substr.toLowerCase()))
    setSortedTagsItems(a);
  }

  const [blockButton, setBlockButton] = useState(false)

  return (
    <>
      <Box
        sx={{
          height: "calc( 100% - 70px )",
          overflow: "auto"
        }}
      >
        <ModalTitle
          {...titleProps}
        />
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            flexGrow: 1,
          }}
        >
          {isSelection && activeScope !== null ? (
            // Здесь выбираем элемент в табличку
            <>
              <Button
                disabled={blockButton}
                onClick={() => {
                  setBlockButton(true)
                  setTimeout(() => setBlockButton(false), 20000)
                  resetAmoTagsFields()
                }}
                sx={{
                  width: !isMobile ? "250px" : "auto",
                  borderRadius: "50px",
                  p: "8px 20px",
                  mr: "10px",
                  fontSize: "16px",
                  border: "#7E2AEA",
                  bgcolor: "#7E2AEA1A",
                  color: "#7E2AEA",
                }}
              >Обновить теги и сущности</Button>
              <DataConstrictor
                isError={sortedTagsItems.length === 0}
                constrictor={startConstrictor}
              />
              <ItemsSelectionView
                items={sortedTagsItems}
                selectedItemId={selectedTag}
                setSelectedItem={setSelectedTag}
                handleScroll={onScroll}
                activeScope={activeScope}
              />
            </>
          ) : (
            // Табличка
            <TagsDetailsView
              items={tagsItems}
              setActiveScope={setActiveScope}
              selectedTags={selectedTags}
              setIsSelection={setIsSelection}
              deleteHC={handleDelete}
            />
          )}
        </Box>
      </Box>
      <Box
        sx={{
          alignSelf: "end",
        }}
      >

        {
          isSelection && activeScope !== null ?
            <StepButtonsBlock
              onLargeBtnClick={() => {
                handleAdd();
                setActiveScope(null);
                setIsSelection(false);
              }}
              largeBtnText={"Добавить"}
              onSmallBtnClick={() => {
                setActiveScope(null);
                setIsSelection(false);
              }}
              smallBtnText={"Отменить"}
            />
            :
            <StepButtonsBlock
              onSmallBtnClick={handlePrevStep}
              onLargeBtnClick={handleNextStep}
            />
        }
      </Box>
    </>
  );
};
