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 ArrowLeft from "@/assets/icons/questionsPage/arrowLeft";
import { decrementCurrentStep } from "@root/quizes/actions";
import DrawerNewField from "./DrawerParent";
import WindowNewField from "./NewField/WindowNewField";
import GearIcon from "@icons/GearIcon";
import { useCurrentQuiz } from "@root/quizes/hooks";
import {
  FieldSettingsDrawerState,
  FormContactFieldName,
} from "@model/quizSettings";
import CustomizedSwitch from "@ui_kit/CustomSwitch";

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",
        mt: "67px",
      }}
    >
        <Box sx={{display: "flex", gap: "20px", alignItems: "center"}}>
            <CustomizedSwitch
                checked={quiz.config.showfc}
                onChange={(e) => {
                    updateQuiz(quiz.id, (quiz) => {
                        quiz.config.showfc = e.target.checked;

                    })
                }}
            />
            <Typography sx={{fontWeight: 500,
                color: theme.palette.grey3.main,}}
            >
                Показывать форму контактов</Typography>
        </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={{
            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="Заголовок формы"
            maxLength={200}
          />
          <CustomTextField
            onChange={({ target }) => {
              updateQuiz(quiz.id, (quiz) => {
                quiz.config.formContact.desc = target.value;
              });
            }}
            value={quiz.config.formContact.desc}
            rows={8}
            placeholder="Дополнительный текст формы"
            sxForm={{
              height: "197px",
            }}
            sx={{
              height: "197px",
            }}
            maxLength={300}
          />
        </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}
          {type === "text" && (
            <IconButton
              onClick={() => drawerNewFieldHC({ field: type, isEdit: true })}
              sx={{
                position: "absolute",
                right: "0",
              }}
            >
              <GearIcon height="20px" width="20px" color="#7e2aea" />
            </IconButton>
          )}
        </Typography>
        {(type !== "email" || quiz?.config.resultInfo.when !== "email") && (
          <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>
      )}
      <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>
      <PseudoButton />
    </Box>
  );
};

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

  if (!quiz) return null;

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