import { FC, useState } from 'react';

import { useMutation, useQueryClient } from 'react-query';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconClockEdit } from '@material-hu/icons/tabler';

import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';
import { MenuItemProps } from '@material-hu/components/design-system/Menu/components/MenuItem/types';

import { useMoreMenu } from 'src/contexts/MoreMenuContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { feedKeys } from 'src/pages/dashboard/feed/queries';
import { groupsKeys } from 'src/pages/dashboard/groups/queries';
import { updateGroupPollDeadline as updateGroupPollDeadlineService } from 'src/services/groups';
import { updatePollDeadline } from 'src/services/posts';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import PollDeadlineForm from 'src/components/poll/PollDeadlineForm';

type PollEditDeadlineMenuItemProps = Omit<MenuItemProps, 'id'> & {
  postId: number;
  pollId: number;
  endsAt?: string | null;
  isGroupPoll?: boolean;
  groupId?: string;
};

export const POLL_EDIT_DEADLINE_MENU_ITEM_Z_INDEX = 1500;

const PollEditDeadlineMenuItem: FC<PollEditDeadlineMenuItemProps> = ({
  postId,
  pollId,
  endsAt,
  isGroupPoll = false,
  groupId,
  ...menuProps
}) => {
  const { t } = useTranslation('post');
  const showGeneralError = useGeneralError();
  const queryClient = useQueryClient();
  const { closeMenu } = useMoreMenu();

  const [newEndsAt, setNewEndsAt] = useState<Date | null>(
    endsAt ? new Date(endsAt) : null,
  );
  const [deadlineEnabled, setDeadlineEnabled] = useState<boolean>(!!endsAt);

  const updateDeadlineMutation = useMutation(
    (newDeadline: string | null) => {
      if (isGroupPoll && groupId) {
        return updateGroupPollDeadlineService(
          Number(groupId),
          postId,
          pollId,
          newDeadline,
        );
      }
      return updatePollDeadline(postId, pollId, newDeadline);
    },
    {
      onSuccess: () => {
        if (isGroupPoll && groupId) {
          queryClient.invalidateQueries(groupsKeys.postList(groupId));
        } else {
          queryClient.invalidateQueries(feedKeys.list());
          queryClient.invalidateQueries(feedKeys.detail(postId));
        }
        closeMenu?.();
      },
      onError: err => showGeneralError(err, t('poll_deadline_update_error')),
    },
  );

  const handleSaveDeadline = () => {
    if (deadlineEnabled && newEndsAt) {
      updateDeadlineMutation.mutate(newEndsAt.toISOString());
    } else if (!deadlineEnabled) {
      updateDeadlineMutation.mutate(null);
    }
  };

  const drawerContent = () => (
    <PollDeadlineForm
      deadlineEnabled={deadlineEnabled}
      endsAt={newEndsAt}
      onDeadlineEnabledChange={setDeadlineEnabled}
      onEndsAtChange={setNewEndsAt}
      disabled={updateDeadlineMutation.isLoading}
    />
  );

  const { showDrawer, drawer } = useDrawerV2(({ closeDrawer }) => ({
    title: t('poll_edit_deadline_title'),
    children: drawerContent(),
    primaryButtonProps: {
      children: t('save'),
      onClick: () => {
        handleSaveDeadline();
        closeDrawer();
      },
      disabled:
        updateDeadlineMutation.isLoading ||
        (deadlineEnabled &&
          (!newEndsAt || (newEndsAt && newEndsAt <= new Date()))),
      sx: { width: '100%' },
    },
    onClose: () => {
      closeDrawer();
      closeMenu?.();
    },
    sx: { zIndex: POLL_EDIT_DEADLINE_MENU_ITEM_Z_INDEX },
  }));

  return (
    <>
      <HuMenuItem
        {...menuProps}
        onClick={() => showDrawer({})}
        sx={{ p: 0 }}
      >
        <HuListItem
          sx={{ p: 0 }}
          avatar={{ Icon: IconClockEdit }}
          text={{ title: t('poll_edit_deadline') }}
        />
      </HuMenuItem>
      {drawer}
    </>
  );
};

export default PollEditDeadlineMenuItem;
