import { FC, useEffect, useMemo, useState } from "react";
import { ItemsSelectionView } from "./ItemsSelectionView/ItemsSelectionView";
import { ItemDetailsView } from "./ItemDetailsView/ItemDetailsView";
import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
import { MinifiedData, QuestionKeys, SelectedQuestions, TagKeys, TagQuestionHC } from "../types";
import { EntitiesQuestions } from "./EntitiesQuestions";
import { diffArr } from "..";
import { DataConstrictor } from "../Components/DataConstrictor";
import { ModalTitle } from "../ModalTitle";
import { StepButtonsBlock } from "../StepButtonsBlock";
import { resetAmoTagsFields } from "../useAmoIntegration";

type Props = {
  selectedCurrentFields: MinifiedData[] | [];
  questionsItems: MinifiedData[] | [];
  fieldsItems: MinifiedData[] | [];
  selectedQuestions: SelectedQuestions;
  handleAddQuestion: (scope: QuestionKeys | TagKeys, id: string, type: "question" | "tag") => void;
  openDelete: (data: TagQuestionHC) => void;
  handlePrevStep: () => void;
  handleNextStep: () => void;
  FieldsAllowedFC: MinifiedData[]
  setSelectedCurrentFields: (value: MinifiedData[]) => void;
  titleProps: {
    step: number;
    title: string;
    toSettings: () => void;
  }
  onScroll: () => void;
};
export type QuestionPair = {
  question: string,
  field: string
}
const FCTranslate = {
  "name": "имя",
  "email": "почта",
  "phone": "телефон",
  "text": "номер",
  "address": "адрес",
}
export const AmoQuestions: FC<Props> = ({
  selectedCurrentFields,
  questionsItems,
  fieldsItems,
  selectedQuestions = [],
  handleAddQuestion,
  handlePrevStep,
  handleNextStep,
  openDelete,
  FieldsAllowedFC,
  setSelectedCurrentFields,
  onScroll,
  titleProps,
}) => {
  if (!selectedQuestions.hasOwnProperty('Contact')) {
    selectedQuestions.Contact = []
  }
  if (!selectedQuestions.hasOwnProperty('Customer')) {
    selectedQuestions.Customer = []
  }
  if (!selectedQuestions.hasOwnProperty('Company')) {
    selectedQuestions.Company = []
  }
  if (!selectedQuestions.hasOwnProperty('Lead')) {
    selectedQuestions.Lead = []
  }
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(600));
  const [isSelection, setIsSelection] = useState<boolean>(false);
  const [activeScope, setActiveScope] = useState<QuestionKeys | null>(null);
  const [selectedQuestion, setSelectedQuestion] = useState<string | null>(null);
  const [selectedField, setSelectedField] = useState<string | null>(null);

  const [isCurrentFields, setIsCurrentFields] = useState(true);

  const handleAddNewField = () => {
    if (activeScope === null || selectedQuestion === null) return;
    setActiveScope(null);
    handleAddQuestion(activeScope, selectedQuestion, "question");
  };
  const handleAddCurrentField = () => {
    if (activeScope === null || selectedField === null || selectedQuestion === null ||
      selectedCurrentFields.some(e => (e.id === selectedQuestion) && e.entity === activeScope)
    ) return;
    setActiveScope(null);
    //Убедимся что такой ФК не добавлялось
    const newArray = selectedCurrentFields
    let index = -1
    selectedCurrentFields.forEach((e, i) => {
      if (e.subTitle === selectedQuestion) index = i
    })
    if (index !== -1) newArray.splice(index, 1);
    newArray.push({
      id: selectedQuestion,
      title: questionsItems.find(e => e.id === selectedQuestion)?.title || FCTranslate[selectedQuestion],
      entity: activeScope,
      amoId: selectedField,
    })
    setSelectedCurrentFields(newArray);
  };

  const handleAdd = () => {
    if (isCurrentFields) {
      handleAddCurrentField()
    } else {
      handleAddNewField()
    }
  }

  const handleDelete = (id: string, scope: QuestionKeys) => {
    openDelete({
      id,
      scope,
      type: "question",
    });
  };
  const SCFworld = (() => {
    const obj = {
      Lead: [],
      Company: [],
      Customer: [],
      Contact: []
    }
    selectedCurrentFields.forEach((e) => {
      if (!obj[e.entity]?.includes(e.id)) {
        obj[e.entity].push(e)
      }
    })
    return obj
  })()

  const [sortedFieldsAllowedFC, setSortedFieldsAllowedFC] = useState<MinifiedData[]>(FieldsAllowedFC);
  const [sortedFieldsItems, setSortedFieldsItems] = useState<MinifiedData[]>(fieldsItems);
  const [sortedquestionsItems, setSortedquestionsItems] = useState<MinifiedData[]>(questionsItems);

  const startConstrictor = (substr: string) => {
    const a = FieldsAllowedFC.filter((mData) => mData.title.toLowerCase().startsWith(substr.toLowerCase()))
    const b = fieldsItems.filter((mData) => mData.title.toLowerCase().startsWith(substr.toLowerCase()))
    const c = questionsItems.filter((mData) => mData.title.toLowerCase().startsWith(substr.toLowerCase()))
    setSortedFieldsAllowedFC(a);
    setSortedFieldsItems(b);
    setSortedquestionsItems(c);
  }

  useEffect(() => {
    setSortedFieldsAllowedFC(FieldsAllowedFC);
    setSortedFieldsItems(fieldsItems);
    setSortedquestionsItems(questionsItems);
  }, [activeScope])
  const [blockButton, setBlockButton] = useState(false)

  return (
    <>
      <Box
        sx={{
          height: "calc( 100% - 70px )",
          overflow: "auto"
        }}
      >
        <ModalTitle
          {...titleProps}
          desc={isSelection && activeScope !== null ? "На этом этапе вы можете соотнести ваше ранее созданное поле с вопросом из квиза или добавить новое поле" : "На этом этапе вы можете добавить в поля соответствующие вопросы"}
        />
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            height: "100%",
            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={false}
                constrictor={startConstrictor}
              />
              <EntitiesQuestions
                FieldsAllowedFC={sortedFieldsAllowedFC}
                fieldsItems={sortedFieldsItems}
                items={(sortedquestionsItems.length === 0) ? [] : diffArr(sortedquestionsItems, selectedQuestions[activeScope])}
                selectedItemId={selectedQuestion}
                setSelectedQuestion={setSelectedQuestion}
                selectedField={selectedField}
                selectedCurrentFields={selectedCurrentFields}
                setSelectedField={setSelectedField}
                activeScope={activeScope}
                setIsCurrentFields={setIsCurrentFields}
                isCurrentFields={isCurrentFields}
                handleScroll={onScroll}
              />
            </>
          ) : (
            // Табличка
            <ItemDetailsView
              items={[...questionsItems, ...FieldsAllowedFC]}
              setActiveScope={setActiveScope}
              selectedQuestions={{
                Lead: [...selectedQuestions.Lead, ...SCFworld.Lead],
                Company: [...selectedQuestions.Company, ...SCFworld.Company],
                Customer: [...selectedQuestions.Customer, ...SCFworld.Customer],
                Contact: [...selectedQuestions.Contact, ...SCFworld.Contact]
              }}
              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}
            largeBtnText={"Сохранить"}
          />

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