import React, { useCallback, useMemo, useState } from 'react';
import { format, startOfDay } from 'date-fns';
import type { BadgeProps } from '../../atoms';
import {
  Box,
  Button,
  Card,
  Collapse,
  Flex,
  Heading,
  Badge,
  Typo,
  Popover,
  Grid,
  Separator,
  IconButton,
} from '../../atoms';
import {
  ChevronDownIcon,
  ChevronUpIcon,
  Pencil1Icon,
  RocketIcon,
  TrashIcon,
} from '../../icon';

export interface GoalManageCardProps {
  defaultOpen?: boolean;
  title?: string;
  dueDate?: Date;
  completed?: boolean;
  expectedEffect?: string;
  huddle?: string;
  onClickDelete?: () => void;
  onClickEdit?: () => void;
  onClickComplete?: () => void;
  onClickIncomplete?: () => void;
}

export function GoalManageCardRead(
  props: GoalManageCardProps
): React.ReactElement {
  const {
    title,
    dueDate,
    completed,
    expectedEffect,
    huddle,
    onClickDelete,
    onClickEdit,
    defaultOpen,
    onClickIncomplete,
    onClickComplete,
  } = props;
  const [open, setOpen] = useState<boolean>(Boolean(defaultOpen));
  const onClickOpen = useCallback(() => {
    setOpen((p) => !p);
  }, []);

  const icon = open ? <ChevronUpIcon /> : <ChevronDownIcon />;

  const badgeMeta = useMemo<BadgeProps | null>(() => {
    if (!completed && dueDate) {
      if (dueDate >= startOfDay(new Date()))
        return {
          color: 'success',
          children: '진행 중',
        } as const;
      return { color: 'error', children: '미달성' };
    }
    return null;
  }, [completed, dueDate]);

  const renderSubTitle = useCallback((subTitle: string) => {
    return (
      <Heading mb="2" variant="heading5">
        {subTitle}
      </Heading>
    );
  }, []);

  const renderSubContent = useCallback((content?: string) => {
    return (
      <Typo as="p" color="gray">
        {content}
      </Typo>
    );
  }, []);

  const renderCompleteButton = useCallback(() => {
    if (completed) {
      return (
        <Button onClick={onClickIncomplete} size="small" variant="surface">
          진행중인 과제로 돌려놓기
        </Button>
      );
    }

    return (
      <Popover.Root>
        <Popover.Trigger>
          <Button size="small">
            <RocketIcon />
            달성하기
          </Button>
        </Popover.Trigger>
        <Popover.Content>
          <Typo color="gray">목표를 달성하시겠습니까?</Typo>
          <Flex gap="3" justify="end" mt="3">
            <Popover.Close>
              <Button color="gray" size="small" variant="outline">
                아니요
              </Button>
            </Popover.Close>
            <Popover.Close>
              <Button onClick={onClickComplete} size="small">
                예
              </Button>
            </Popover.Close>
          </Flex>
        </Popover.Content>
      </Popover.Root>
    );
  }, [completed, onClickIncomplete, onClickComplete]);

  return (
    <Card>
      <Grid align="center" columns="auto 1fr" gapX="3">
        <IconButton onClick={onClickOpen} variant="ghost">
          {icon}
        </IconButton>
        <Heading variant="heading4">{title}</Heading>

        <Flex align="center" gridColumnStart="2" justify="between" mt="2">
          <Flex align="center" gap="3">
            {badgeMeta ? <Badge {...badgeMeta} /> : null}
            <Typo color="gray">
              {dueDate ? format(dueDate, 'yyyy년 MM월 dd일') : null}
            </Typo>
          </Flex>
          {renderCompleteButton()}
        </Flex>
        {open ? (
          <Separator
            mb="4"
            mt="4"
            size="4"
            style={{ gridColumnStart: 'span 2' }}
          />
        ) : null}
        <Box gridColumnStart="2" p="0">
          <Collapse open={open}>
            <Flex direction="column" gap="5">
              <Box>
                {renderSubTitle(
                  '해당 목표를 달성하면, 아래와 같은 결과를 얻을 수 있습니다'
                )}
                {renderSubContent(expectedEffect)}
              </Box>
              <Box>
                {renderSubTitle(
                  '목표를 이루기까지 방해가 될 수 있는 요소들은 다음과 같습니다'
                )}
                {renderSubContent(huddle)}
              </Box>
            </Flex>
            <Flex align="center" gap="3" justify="end" mt="3">
              <Popover.Root>
                <Popover.Trigger>
                  <Button color="gray" size="small" variant="ghost">
                    <TrashIcon />
                    삭제하기
                  </Button>
                </Popover.Trigger>
                <Popover.Content>
                  <Typo color="gray">목표를 삭제하시겠습니까?</Typo>
                  <Flex gap="3" justify="end" mt="3">
                    <Popover.Close>
                      <Button color="gray" size="small" variant="outline">
                        아니요
                      </Button>
                    </Popover.Close>
                    <Popover.Close>
                      <Button onClick={onClickDelete} size="small">
                        예
                      </Button>
                    </Popover.Close>
                  </Flex>
                </Popover.Content>
              </Popover.Root>
              <Button onClick={onClickEdit} size="small" variant="surface">
                <Pencil1Icon />
                수정하기
              </Button>
            </Flex>
          </Collapse>
        </Box>
      </Grid>
    </Card>
  );
}
