"use client";

import {
  getApiErrorMessages,
  getLocalizedApiMessage,
} from "@/lib/api/errors";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/Button";
import { requestEventDeletion } from "@/features/events/services/eventsApi";
import { toast } from "sonner";
import { useLanguageStore } from "@/store/languageStore";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { invalidateEventReads } from "../eventQueryKeys";
import { useState } from "react";
import { useDeletionSource } from "@/features/shared/useDeletionSource";
import DeletionSourceNotice from "@/features/shared/DeletionSourceNotice";
import type { EventTitlePair } from "@/features/events/eventRecord";

interface DeleteEventModalProps {
  eventId: string;
  requestOnly?: boolean;
  setOpenModal: () => void;
  refetch: () => void;
  eventTitle?: EventTitlePair;
}

function DeleteEventModal({
  eventId,
  requestOnly = false,
  setOpenModal,
  refetch,
}: DeleteEventModalProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const source = useDeletionSource(eventId, "event", requestOnly);
  const [reason, setReason] = useState("");
  const queryClient = useQueryClient();

  const { mutate: performDelete, isPending: deleteLoading } = useMutation({
    mutationFn: async () => {
      if (!await source.guard()) return null;
      return requestEventDeletion(eventId, { requestOnly, reason: reason.trim() || undefined });
    },
    onSuccess: (response) => {
      if (!response) return;
      const successMessage =
        /* `msg` only. `ApiResponse::success()` builds
           `{ key, msg, code, response_status, data }` — `message_en` /
           `message_ar` are a shape some *error* bodies use (see
           `ErrorPayload`), and the catch block below still reads them from
           there. On a success envelope both terms were always `undefined`. */
        response?.msg;
      toast.success(successMessage || t(requestOnly ? "COMMON.DELETION_REQUEST_SENT" : "COMMON.TOAST.DELETE_EVENT_SUCCESS"));
      setOpenModal();
      // A deleted event must leave every list, not only the page that asked.
      void invalidateEventReads(queryClient);
      refetch();
    },
    /*
     * Read through `lib/api/errors.ts` rather than walking
     * `err.response.data.errors[key][lang]` by hand.
     *
     * `getApiErrorMessages` already covers both envelope shapes — the current
     * `response_status.validation_errors` field map and the older
     * `errors: { field: { en, ar } }` one this block was written against — and
     * `getLocalizedApiMessage` covers the `msg` / `message_en` / `message_ar`
     * fallbacks. The messages arrive already localized from the language
     * header, so there is nothing to select per language either.
     */
    onError: (err: unknown) => {
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
        return;
      }
      toast.error(
        getLocalizedApiMessage(
          err,
          selectedLanguage,
          t("COMMON.TOAST.DELETE_EVENT_FAILED")
        )
      );
    },
  });

  const handleDelete = () => {
    if (!eventId) return;
    performDelete();
  };

  return (
    <div className="md:w-[100%] rounded-lg bg-white filtermodal">
      <DeletionSourceNotice state={source} />
      {!source.loading && !source.query.isError && !source.errorKey && <>
        <h2 className="pb-6 text-center text-lg leading-relaxed">
          {t(requestOnly ? "COMMON.DELETION_REVIEW_NOTICE" : "COMMON.ARE_YOU_SURE_DELETE_VOLUNTEER_EVENT")}
        </h2>
        {requestOnly && <label className="mb-5 block text-sm">{t("COMMON.DELETION_REASON_OPTIONAL")}<textarea value={reason} onChange={event => setReason(event.target.value)} rows={3} maxLength={2000} className="mt-2 w-full rounded-xl border p-3" /></label>}
      </>}
      <div className="flex xss:flex-col justify-center w-full gap-5">
        <Button
          variant="primary"
          type="button"
          size="medium"
          onClick={handleDelete}
          disabled={deleteLoading || source.loading || source.query.isFetching || source.query.isError || Boolean(source.errorKey)}
          className="xss:!w-full"
        >
          {t("COMMON.CONFIRM")}
        </Button>
        <Button
          variant="secondary"
          size="medium"
          type="button"
          onClick={() => setOpenModal()}
          disabled={deleteLoading}
          className="xss:!w-full"
        >
          {t("COMMON.CANCEL")}
        </Button>
      </div>
    </div>
  );
}

export default DeleteEventModal;
