import React, { useCallback, useMemo, useState } from 'react';
import { Cross1Icon } from '@radix-ui/react-icons';
import { Box, Button, Dialog, Flex, IconButton, Typo } from '@/atoms';
import { type CurriculumReviewContents } from '@/types/curriculumContents.type';
import { useCurriculumContext } from '../curriculum-context';
import CurriculumReviewSteps from './CurriculumReviewSteps';

interface CurriculumReviewProps {
  item: CurriculumReviewContents;
  sectionTitle: string | undefined;
}

function CurriculumReview(props: CurriculumReviewProps): React.ReactNode {
  const { item, sectionTitle } = props;
  const { description, buttonTitle } = item;
  const {
    curriculum,
    onReviewSubmit: _onReviewSubmit,
    onReviewValueChange: _onReviewValueChange,
    curriculumReviewAnswers,
    tempCurriculumReviewAnswers,
    curriculumCompleteMap,
  } = useCurriculumContext();
  const [open, setOpen] = useState(false);
  const [isChanged, setIsChanged] = useState(false);
  const [closeDialogOpen, setCloseDialogOpen] = useState(false);

  const onReviewValueChange = useCallback(
    ({
      reviewId,
      answer,
    }: {
      reviewId: string;
      answer: Record<string, string>;
    }) => {
      if (curriculumReviewAnswers[reviewId] === answer[reviewId]) {
        return;
      }

      setIsChanged(true);
      _onReviewValueChange({ reviewId, answer });
    },
    [_onReviewValueChange, curriculumReviewAnswers]
  );

  const onReviewSubmit = useCallback(
    (values: Record<string, string>) => {
      return _onReviewSubmit({ reviewId: item.uuid, answer: values }).then(
        (result) => {
          setIsChanged(false);
          return result;
        }
      );
    },
    [item.uuid, _onReviewSubmit]
  );

  const onClickEndReview = useCallback(() => {
    setOpen(false);
  }, []);

  const onClickCloseDrawer = useCallback(() => {
    if (isChanged) {
      setCloseDialogOpen(true);
    } else {
      setOpen(false);
    }
  }, [isChanged]);

  const mode = useMemo(() => {
    return item.questions.every(
      (question) =>
        curriculumReviewAnswers[question.uuid] &&
        curriculumReviewAnswers[question.uuid] !== ''
    )
      ? 'edit'
      : 'create';
  }, [curriculumReviewAnswers, item.questions]);

  const defaultValues = useMemo(() => {
    const allAnswers = {
      ...tempCurriculumReviewAnswers,
      ...curriculumReviewAnswers,
    };

    return item.questions.reduce<Record<string, string>>((acc, question) => {
      acc[question.uuid] = allAnswers[question.uuid] || '';
      return acc;
    }, {});
  }, [curriculumReviewAnswers, item.questions, tempCurriculumReviewAnswers]);

  const done = useMemo(() => {
    return Boolean(curriculumCompleteMap[item.uuid]);
  }, [curriculumCompleteMap, item.uuid]);

  const bgColor = done ? 'var(--color-panel-solid)' : undefined;

  return (
    <Dialog.Root onOpenChange={setOpen} open={open}>
      <Flex
        align="center"
        direction="column"
        height="100%"
        justify="center"
        px="3"
        py="3"
        style={{
          backgroundImage: `url(https://tipp-coaching-live.s3.ap-northeast-2.amazonaws.com/images/curriculum_review_bg.png)`,
          backgroundPosition: 'center',
          backgroundSize: 'cover',
          backgroundRepeat: 'no-repeat',
        }}
        width="100%"
      >
        <Typo color="gray" weight="bold">
          {curriculum.title}
        </Typo>
        <Typo align="center" as="p" color="gray">
          {description}
        </Typo>

        <Dialog.Trigger>
          <Button
            mt="3"
            style={{ minWidth: 232, backgroundColor: bgColor }}
            variant={done ? 'outline' : 'solid'}
          >
            <Typo truncate>{done ? '나의 응답 다시보기' : buttonTitle}</Typo>
          </Button>
        </Dialog.Trigger>
      </Flex>
      <Dialog.Content
        height="100%"
        hideCloseButton
        style={{ borderRadius: 0, padding: 0 }}
        title=""
        width="100%"
      >
        <Flex
          align="center"
          height="100%"
          justify="center"
          pb="3"
          position="relative"
          width="100%"
        >
          <CurriculumReviewSteps
            contents={item}
            curriculum={curriculum}
            defaultValues={defaultValues}
            done={done}
            mode={mode}
            onClickEndReview={onClickEndReview}
            onReviewValueChange={onReviewValueChange}
            onSubmit={onReviewSubmit}
            title={sectionTitle}
          />
          {/* 닫기 버튼 */}
          <Box position="absolute" right="16px" top="16px">
            <IconButton
              color="gray"
              onClick={onClickCloseDrawer}
              variant="ghost"
            >
              <Box display={{ initial: 'none', md: 'block' }}>
                <Cross1Icon height={20} width={20} />
              </Box>
              <Box display={{ initial: 'block', md: 'none' }}>
                <Cross1Icon height={16} width={16} />
              </Box>
            </IconButton>
          </Box>

          {/* 진짜 닫겠습니까 모달 */}
          <Dialog.Root onOpenChange={setCloseDialogOpen} open={closeDialogOpen}>
            <Dialog.Content
              buttons={
                <Flex gap="3" justify="end">
                  <Dialog.Close asChild>
                    <Button color="gray" variant="outline">
                      돌아가기
                    </Button>
                  </Dialog.Close>
                  <Dialog.Close>
                    <Button color="red" onClick={onClickEndReview}>
                      나가기
                    </Button>
                  </Dialog.Close>
                </Flex>
              }
              title="작성을 중단하시겠습니까?"
            >
              <Typo>페이지에서 벗어나면 작성한 내용이 저장되지 않습니다.</Typo>
            </Dialog.Content>
          </Dialog.Root>
        </Flex>
      </Dialog.Content>
    </Dialog.Root>
  );
}

export default CurriculumReview;
