"use client";

import type { VolunteerOpportunityTeamRecord } from "@/features/opportunities/rolesAndTeamsRecord";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { Button } from "@/components/ui/Button";
import { deleteTeam } from "@/features/opportunities/services/registrations";
import { useLanguageStore } from "@/store/languageStore";
import { getApiErrorMessages, getLocalizedApiMessage } from "@/lib/api/errors";

interface DeleteTeamModalProps {
  /** The team's integer id, or null before a row has been chosen. */
  teamId: number | null;
  setOpenDeleteModal: () => void;
  refetch: () => void;
  dropdownRefetch?: () => void;
  /** The whole team row, for the confirmation copy's localized name. */
  teamName?: VolunteerOpportunityTeamRecord;
}

export default function DeleteTeam({
  teamId,
  setOpenDeleteModal,
  refetch,
  dropdownRefetch,
  teamName,
}: DeleteTeamModalProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const deleteTeamMutation = useMutation({ mutationFn: deleteTeam });

  const handleDelete = async () => {
    if (!teamId) return;
    try {
      await deleteTeamMutation.mutateAsync(String(teamId));
      toast.success(t("COMMON.TOAST.DELETE_TEAM_SUCCESS"));
      setOpenDeleteModal();
      refetch();
      dropdownRefetch?.();
    } catch (error) {
      /* Both envelope shapes, and the localized pair, are handled by
         `lib/api/errors.ts`; this block used to re-implement the
         legacy `errors[field][lang]` walk by hand. */
      const messages = getApiErrorMessages(error, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(
          getLocalizedApiMessage(
            error,
            selectedLanguage,
            t("COMMON.TOAST.DELETE_TEAM_FAILED"),
          ),
        );
      }
    }
  };

  return (
    <div className="md:w-[100%] rounded-lg bg-white filtermodal">
      <h2 className="text-center text-lg pb-10">
        {t("COMMON.ARE_YOU_SURE_DELETE_TEAM", {
          /* Explicit branch: the resource has exactly the `_en`/`_ar` pair and
             both are nullable, so a built key could miss and `String(null)`
             could print "null". */
          team:
            (selectedLanguage === "ar"
              ? teamName?.team_name_ar
              : teamName?.team_name_en) || t("COMMON.TEAM"),
        })}
      </h2>
      <div className="flex xss:flex-col justify-center w-full gap-5">
        <Button
          variant="primary"
          type="button"
          size="medium"
          onClick={handleDelete}
          disabled={deleteTeamMutation.isPending}
          className="xss:!w-full"
        >
          {t("COMMON.CONFIRM")}
        </Button>
        <Button
          variant="secondary"
          size="medium"
          type="button"
          onClick={() => setOpenDeleteModal()}
          disabled={deleteTeamMutation.isPending}
          className="xss:!w-full"
        >
          {t("COMMON.CANCEL")}
        </Button>
      </div>
    </div>
  );
}
