import { useEffect, useRef } from 'react';

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

import { POLL_MAX_OPTIONS, POLL_MIN_OPTIONS } from 'src/constants/posts';
import { PollState } from 'src/types/feed';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import {
  getPollCreateDrawerConfig,
  usePollCreateState,
} from './PollCreateDrawer';

export type UsePollDrawerProps = {
  withPoll: boolean;
  canAddPoll: boolean;
  isSubmitting: boolean;
  pollState: PollState;
  pollOptionsForEdit?: string[];
  pollVotersVisible?: boolean;
  isEdit?: boolean;
  onPollUpdate: (options: string[], isSave?: boolean) => void;
  onPollVotersVisibilityChange?: (visible: boolean) => void;
  pollDeadlineEnabled?: boolean;
  pollEndsAt?: Date | null;
  onPollDeadlineChange?: (
    deadlineEnabled: boolean,
    endsAt: Date | null,
  ) => void;
  setWithPoll: (withPoll: boolean) => void;
  shouldClearPollWhenCancelling?: boolean;
};

export const usePollDrawer = (props: UsePollDrawerProps) => {
  const {
    withPoll,
    canAddPoll,
    isSubmitting,
    pollState,
    pollOptionsForEdit = [],
    pollVotersVisible = false,
    isEdit = false,
    onPollUpdate,
    onPollVotersVisibilityChange,
    pollDeadlineEnabled = false,
    pollEndsAt = null,
    onPollDeadlineChange,
    setWithPoll,
    shouldClearPollWhenCancelling = true,
  } = props;

  const { t } = useTranslation();

  const pollCreateState = usePollCreateState({
    min: POLL_MIN_OPTIONS,
    max: POLL_MAX_OPTIONS,
    options: pollOptionsForEdit,
    votersVisible: pollVotersVisible,
    isSubmitting,
    pollState,
    onSave: (
      options: string[],
      votersVisible: boolean,
      deadlineEnabled: boolean,
      endsAt: Date | null,
    ) => {
      onPollUpdate(options, true);
      onPollVotersVisibilityChange?.(votersVisible);
      onPollDeadlineChange?.(deadlineEnabled, endsAt);
    },
    onChange: (
      options: string[],
      votersVisible: boolean,
      deadlineEnabled: boolean,
      endsAt: Date | null,
    ) => {
      onPollUpdate(options, false);
      onPollVotersVisibilityChange?.(votersVisible);
      onPollDeadlineChange?.(deadlineEnabled, endsAt);
    },
    deadlineEnabled: pollDeadlineEnabled,
    endsAt: pollEndsAt,
  });

  const { drawer, showDrawer } = useDrawerV2(({ closeDrawer }) =>
    getPollCreateDrawerConfig(
      pollCreateState,
      closeDrawer,
      t('post:poll_create'),
      () => {
        if (shouldClearPollWhenCancelling) {
          onPollUpdate([]);
          onPollVotersVisibilityChange?.(false);
          onPollDeadlineChange?.(false, null);
          setWithPoll(false);
        }
      },
      pollState,
    ),
  );

  // Track previous withPoll state to only open drawer on transition
  const prevWithPollRef = useRef(withPoll);
  const hasExistingPollOptions = pollOptionsForEdit.some(option =>
    option.trim(),
  );

  // Show poll drawer when withPoll changes from false to true
  useEffect(() => {
    const prevWithPoll = prevWithPollRef.current;
    prevWithPollRef.current = withPoll;

    // Auto-open for create flow and for edit flow only when adding a brand-new poll.
    // Keep readonly/edition-approval edits from opening the drawer.
    const shouldAutoOpenPollDrawer =
      !isEdit || (!hasExistingPollOptions && !pollState.form.disabled);

    if (!prevWithPoll && withPoll && canAddPoll && shouldAutoOpenPollDrawer) {
      showDrawer({});
    }
  }, [
    withPoll,
    canAddPoll,
    showDrawer,
    isEdit,
    hasExistingPollOptions,
    pollState.form.disabled,
  ]);

  return { drawer, showDrawer };
};
