import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import {
  Box,
  Button,
  IconButton,
  Link,
  Paper,
  SxProps,
  TextField,
  Theme,
  Typography,
  useTheme,
  Popover,
  useMediaQuery,
  Divider,
} from "@mui/material";
import { incrementCurrentStep, updateQuiz } from "@root/quizes/actions";
import CustomTextField from "@ui_kit/CustomTextField";
import React, { ReactNode, useRef, useState } from "react";
import Info from "../../assets/icons/Info";
import Trash from "@icons/trash";
import { OneIcon } from "../../assets/icons/questionsPage/OneIcon";
import AddPlus from "../../assets/icons/questionsPage/addPlus";
import ArrowLeft from "../../assets/icons/questionsPage/arrowLeft";
import { decrementCurrentStep } from "@root/quizes/actions";
import ButtonSettingForms from "./ButtonSettingForms";
import DrawerNewField from "./DrawerParent";
import WindowMessengers from "./Massengers/WindowMessengers";
import WindowNewField from "./NewField/WindowNewField";
import SwitchContactForm from "./switchContactForm";
import GearIcon from "@icons/GearIcon";
import { useQuestionsStore } from "@root/questions/store";
import { useCurrentQuiz } from "@root/quizes/hooks";
import {
  FieldSettingsDrawerState,
  FormContactFieldName,
} from "@model/quizSettings";

const buttons: { key: FormContactFieldName; name: string; desc: string }[] = [
  { name: "Имя", desc: "Дмитрий", key: "name" },
  { name: "Email", desc: "mail@example.ru", key: "email" },
  { name: "Номер", desc: "+7 900 000 00 00", key: "phone" },
  { name: "Фамилия", desc: "Иванов", key: "text" },
  { name: "Адрес", desc: "Москва, Лаврушинский пер., 10", key: "address" },
];

export default function ContactFormPage() {
  const theme = useTheme();
  const quiz = useCurrentQuiz();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const [drawerNewField, setDrawerNewField] =
    useState<FieldSettingsDrawerState>({ field: "", isEdit: false });
  const [drawerMessenger, setDrawerMessenger] = useState(false);

  const drawerMessengerHC = (bool: boolean) => {
    setDrawerMessenger(bool);
  };

  return (
    <Box
      sx={{
        p: isTablet ? "0 0 150px 0" : "0",
      }}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: "10px",
          m: "67px 0 41px 0",
        }}
      >
        <Link
          sx={{
            fontSize: "16px",
            lineHeight: "19px",
            color: theme.palette.brightPurple.main,
            textDecorationColor: theme.palette.brightPurple.main,
          }}
        >
          Как собрать данные посетителя
        </Link>{" "}
        {/* <Popover>
          <Info />
        </Popover> */}
      </Box>
      {!quiz?.config.formContact.fields.name.used &&
      !quiz?.config.formContact.fields.email.used &&
      !quiz?.config.formContact.fields.phone.used &&
      !quiz?.config.formContact.fields.text.used &&
      !quiz?.config.formContact.fields.address.used ? (
        <ContactFormParent>
          <EmptyCard drawerNewFieldHC={setDrawerNewField} />
        </ContactFormParent>
      ) : (
        <ContactFormParent>
          <ButtonsCard drawerNewFieldHC={setDrawerNewField} />
        </ContactFormParent>
      )}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          maxWidth: "796px",
        }}
      >
        <Box sx={{ display: "flex", gap: "8px" }}>
          <Button onClick={decrementCurrentStep} variant="outlined">
            <ArrowLeft />
          </Button>
          <Button
            variant="contained"
            sx={{ padding: "10px 20px" }}
            onClick={incrementCurrentStep}
          >
            Установка quiz
          </Button>
        </Box>
      </Box>
      <DrawerNewField
        isOpenDrawer={drawerNewField.field}
        drawerNewFieldHC={() => setDrawerNewField({ field: "", isEdit: false })}
      >
        <WindowNewField
          drawerState={drawerNewField}
          closeDrawer={() => setDrawerNewField({ field: "", isEdit: false })}
        />
      </DrawerNewField>
    </Box>
  );
}

interface Props {
  outerContainerSx?: SxProps<Theme>;
  children?: ReactNode;
}

function ContactFormParent({ outerContainerSx: sx, children }: Props) {
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const quiz = useCurrentQuiz();

  if (!quiz) return null;

  return (
    <Paper
      sx={{
        maxWidth: "796px",
        width: "100%",
        borderRadius: "12px",
        margin: "20px 0",
        display: "flex",
      }}
    >
      <Box
        sx={{
          width: "100%",
          display: "flex",
          flexDirection: isTablet ? "column" : "row",
        }}
      >
        <Box
          sx={{
            // borderRight: isTablet ? "none" : `1px solid ${theme.palette.grey2.main}`,
            maxWidth: "386px",
            width: "100%",
            padding: "100px 20px 20px 20px",
            display: "flex",
            flexDirection: "column",
            gap: "20px",
          }}
        >
          <CustomTextField
            onChange={({ target }) => {
              updateQuiz(quiz.id, (quiz) => {
                quiz.config.formContact.title = target.value;
              });
            }}
            value={quiz.config.formContact.title}
            placeholder="Заголовок формы"
            text={""}
          />
          <TextField
            onChange={({ target }) => {
              updateQuiz(quiz.id, (quiz) => {
                quiz.config.formContact.desc = target.value;
              });
            }}
            value={quiz.config.formContact.desc}
            id="outlined-multiline-static"
            multiline
            rows={8}
            placeholder="Дополнительный текст формы"
            sx={{
              backgroundColor: theme.palette.background.default,

              "& .MuiInputBase-root": {
                borderRadius: "10px",
                alignItems: "start",
                color: theme.palette.grey2.main,
                color: "black",
              },
            }}
          />
        </Box>
        <Divider
          sx={{
            height: isTablet ? "1px" : "80%",
            width: isTablet ? "80%" : "1px",
            margin: "auto",
          }}
          orientation={isTablet ? "horizontal" : "vertical"}
        />
        {children}
      </Box>
    </Paper>
  );
}

const SettingField = ({
  name,
  placeholder,
  type,
  drawerNewFieldHC,
}: {
  name: string;
  placeholder: string;
  type: FormContactFieldName;
  drawerNewFieldHC: (state: FieldSettingsDrawerState) => void;
}) => {
  const theme = useTheme();
  const quiz = useCurrentQuiz();

  if (!quiz) return null;

  return (
    <>
      <Typography>
        {quiz.config.formContact.fields[type].text || name}
      </Typography>
      <Box sx={{ display: "flex", mb: "10px" }}>
        <Typography
          sx={{
            color: quiz.config.formContact.fields[type].innerText
              ? "black"
              : "#9A9AAF",
            fontSize: "20px",
            backgroundColor: theme.palette.background.default,
            height: "48px",
            borderRadius: "10px",
            border: "1px #9A9AAF solid",
            lineHeight: "21px",
            p: " 0 25px 0 14px ",
            display: "flex",
            alignItems: "center",
            width: "100%",
            overflow: "hidden",
            textOverflow: "ellipsis",
            position: "relative",
          }}
        >
          {quiz.config.formContact.fields[type].innerText || placeholder}
          <IconButton
            onClick={() => drawerNewFieldHC({ field: type, isEdit: true })}
            sx={{
              position: "absolute",
              right: "0",
            }}
          >
            <GearIcon height="20px" width="20px" color="#7e2aea" />
          </IconButton>
        </Typography>
        <IconButton
          onClick={() =>
            updateQuiz(quiz?.id, (quiz) => {
              quiz.config.formContact.fields[type].used = false;
            })
          }
          sx={{
            width: "48px",
            ml: "5px",
          }}
        >
          <Trash />
        </IconButton>
      </Box>
    </>
  );
};

const ButtonsCard = ({
  drawerNewFieldHC,
}: {
  drawerNewFieldHC: (state: FieldSettingsDrawerState) => void;
}) => {
  const theme = useTheme();
  const quiz = useCurrentQuiz();

  if (!quiz) return null;

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        padding: "20px",
        width: "100%",
        gap: "20px",
      }}
    >
      {buttons.flatMap((contentData) => {
        const content = quiz.config.formContact.fields[contentData.key];
        return content.used ? (
          <SettingField
            drawerNewFieldHC={drawerNewFieldHC}
            key={contentData.key}
            type={contentData.key}
            name={content.text || contentData.name}
            placeholder={content.innerText || contentData.desc}
          />
        ) : (
          []
        );
      })}
      {quiz.config.formContact.fields.name.used &&
      quiz.config.formContact.fields.email.used &&
      quiz.config.formContact.fields.phone.used &&
      quiz.config.formContact.fields.text.used &&
      quiz.config.formContact.fields.address.used ? (
        <></>
      ) : (
        <Button
          onClick={() => drawerNewFieldHC({ field: "all", isEdit: false })}
          variant="contained"
          sx={{ maxWidth: "fit-content", padding: "10px 20px" }}
        >
          Добавить поле +
        </Button>
      )}
      {/* <Link
        component="button"
        // onClick={() => drawerMessengerHC(true)}
        sx={{
          fontSize: "16px",
          lineHeight: "19px",
          color: theme.palette.brightPurple.main,
          textDecorationColor: theme.palette.brightPurple.main,
          textAlign: "left",
        }}
      >
        Добавить мессенджеры
      </Link> */}

      <PseudoButton />
    </Box>
  );
};
const EmptyCard = ({
  drawerNewFieldHC,
}: {
  drawerNewFieldHC: (state: FieldSettingsDrawerState) => void;
}) => {
  const theme = useTheme();
  const [FC, setFC] = useState(false);
  const openFC = () => setFC(true);
  const closeFC = () => setFC(false);
  const popover = useRef(null);

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        padding: "100px 20px 20px 20px",
        width: "100%",
        gap: "20px",
      }}
    >
      <Button
        onClick={() => drawerNewFieldHC({ field: "all", isEdit: false })}
        variant="contained"
        sx={{ maxWidth: "fit-content", padding: "10px 20px" }}
      >
        Добавить поле +
      </Button>
      <Box sx={{ display: "flex" }}>
        <Typography sx={{ color: theme.palette.orange.main }}>
          Будут показаны поля по умолчанию
        </Typography>
        <Box ref={popover}>
          <Info sx={{ ml: "6px", p: "0" }} onClick={openFC} />
        </Box>

        <Popover
          open={FC}
          onClose={closeFC}
          anchorEl={popover.current}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "center",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "center",
          }}
          disableRestoreFocus
        >
          <Typography sx={{ m: "20px", textAlign: "center" }}>
            Будут поля:<br></br> Имя, Email, Телефон
          </Typography>
        </Popover>
      </Box>
      {/* <Link
        sx={{
          mt: "20px",
          fontSize: "16px",
          lineHeight: "19px",
          color: theme.palette.brightPurple.main,
          textDecorationColor: theme.palette.brightPurple.main,
        }}
      >
        Добавить мессенджеры
      </Link> */}
      <PseudoButton />
    </Box>
  );
};

const PseudoButton = () => {
  const quiz = useCurrentQuiz();

  if (!quiz) return null;

  return (
    <TextField
      onChange={({ target }) => {
        updateQuiz(quiz.id, (quiz) => {
          quiz.config.formContact.button = target.value;
        });
      }}
      value={quiz.config.formContact.button}
      sx={{
        heigth: "44px",
        width: "190px",
        "& .MuiInputBase-root": {
          backgroundColor: "#7E2AEA",
          borderRadius: "8px",
          color: "white",
        },
        "& .MuiInputBase-input": {
          padding: "10px 20px",
          textAlign: "center",
        },
        "& .MuiInputBase-input::placeholder": {
          color: "white",
          opacity: "1",
        },
      }}
      placeholder="Название кнопки"
    >
      {quiz.config.formContact.button || "Название кнопки"}
    </TextField>
  );
};
