"use client";

import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { Button } from "@/components/ui/Button";
import { deleteAllRoles } from "@/features/opportunities/services/roles";
import { useLanguageStore } from "@/store/languageStore";
import { getApiErrorMessage } from "@/lib/api/errors";

interface ParticipantsMismatchModalProps {
  id: number;
  onClose: () => void;
  roleModalClose?: () => void;
  refetch: () => void;
  stopNavigationBlock: () => void;
}

export default function ParticipantsMismatchModal({
  onClose,
  id,
  roleModalClose,
  refetch,
  stopNavigationBlock,
}: ParticipantsMismatchModalProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const deleteAllRolesMutation = useMutation({ mutationFn: deleteAllRoles });

  // `isPending` drops when the request resolves, but the dialog stays up
  // through the settle delay below: success keeps the buttons disabled too.
  const busy = deleteAllRolesMutation.isPending || deleteAllRolesMutation.isSuccess;

  const handleDeleteAllRoles = async () => {
    if (busy) return;
    try {
      await deleteAllRolesMutation.mutateAsync(id);
      refetch?.();
      toast.success(t("COMMON.TOAST.DELETE_ROLES_SUCCESS"));
      await stopNavigationBlock();

      // Small delay so the state updates settle before the modals unmount
      setTimeout(() => {
        onClose();
        roleModalClose?.();
      }, 500);
    } catch (error) {
      // Both envelopes (`response_status.validation_errors`, legacy pair).
      toast.error(
        getApiErrorMessage(error, selectedLanguage, t("COMMON.TOAST.DELETE_ROLES_FAILED")),
      );
    }
  };

  return (
    <div className="flex flex-col items-center justify-center">
      <p className="text-center pb-10 text-lg">
        {t("COMMON.CONFIRM_DELETE_ALL_ROLES")}
      </p>
      <div className="flex xss:flex-col justify-center w-full gap-5">
        {/*
          Both buttons are disabled while the delete is in flight. Without it a
          second click re-sends `deleteAllRoles` for the same id: the dialog stays
          mounted for the deliberate 500ms settle delay *after* the request
          succeeds, so the window for a double-click is wide, not theoretical.
          Every other confirmation in the app disables both; this one did not.
        */}
        <Button
          variant="primary"
          type="submit"
          size="medium"
          onClick={handleDeleteAllRoles}
          disabled={busy}
          className="xss:!w-full"
        >
          {t("COMMON.CONFIRM")}
        </Button>
        <Button
          variant="secondary"
          size="medium"
          type="button"
          onClick={onClose}
          disabled={busy}
          className="xss:!w-full"
        >
          {t("COMMON.CANCEL")}
        </Button>
      </div>
    </div>
  );
}
