"use client";

import { useDeletionSource } from "@/features/shared/useDeletionSource";
import DeletionSourceNotice from "@/features/shared/DeletionSourceNotice";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { markServerReadsStale } from "@/providers/mutationStaleness";
import { useTranslation } from "react-i18next";
import Button from "@/components/ui/Button";
import { requestOpportunityDeletion } from "@/features/opportunities/services/opportunities";
import { toast } from "sonner";
import { useLanguageStore } from "@/store/languageStore";
import { getApiErrorMessages, getLocalizedApiMessage } from "@/lib/api/errors";

interface DeleteOpportunityModalProps {
  opportunityId: string;
  requestOnly?: boolean;
  navigateBackOnDelete?: boolean;
  type: "volunteer" | "learnserve";
  setOpenModal: () => void;
  refetch: () => void;
  /**
   * **Declared and never read.** The modal's copy is a fixed question, so the
   * title has never reached the screen; the prop is plumbed from the card
   * through two components to here. Typed to the real contract —
   * `title_en`/`title_ar` are nullable columns — rather than to the `string`
   * the card types used to claim. Recorded in the checklist as dead plumbing
   * to remove with its four call sites, not widened in place to hide it.
   */
  opportunityTitle?: {
    title_en: string | null;
    title_ar: string | null;
  };
}

export default function DeleteOpportunityModal({
  opportunityId,
  requestOnly = false,
  navigateBackOnDelete = false,
  type,
  setOpenModal,
  refetch,
}: DeleteOpportunityModalProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const source = useDeletionSource(opportunityId, type, requestOnly);
  const [reason, setReason] = useState("");
  const [deleteLoading, setDeleteLoading] = useState(false);
  const queryClient = useQueryClient();

  const handleDelete = async () => {
    if (!opportunityId) return;
    setDeleteLoading(true);
    try {
      if (!await source.guard()) return;
      const response = await requestOpportunityDeletion({
        id: opportunityId,
        type, reason: reason.trim() || undefined, requestOnly,
      });
      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_OPPORTUNITY_SUCCESS"),
      );
      setOpenModal();
      // Refresh lists on return without requesting the deleted detail again.
      void markServerReadsStale(queryClient);
      if (navigateBackOnDelete && !requestOnly) {
        if (window.history.length > 1) router.back();
        else router.replace("/");
      } else {
        refetch();
      }
    } catch (err) {
      /* Both envelope shapes, `msg` and the localized pair are all handled by
         `lib/api/errors.ts`. One ordering difference from the block this
         replaces: that one preferred `msg` over `message_${lang}`, whereas
         `getLocalizedApiMessage` prefers the localized pair — which is the
         right way round, since `msg` is localized by the request header while
         the pair is explicit. */
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(
          getLocalizedApiMessage(
            err,
            selectedLanguage,
            t("COMMON.TOAST.DELETE_OPPORTUNITY_FAILED"),
          ),
        );
      }
    } finally {
      setDeleteLoading(false);
    }
  };

  return (
    <div className="md:w-[100%] rounded-lg bg-white filtermodal">
      <DeletionSourceNotice state={source} />
      {!source.loading && !source.query.isError && !source.errorKey && <>
      <h2 className="text-center pb-10 text-lg">
        {requestOnly ? t("COMMON.DELETION_REVIEW_NOTICE") : type === "volunteer"
          ? t("COMMON.ARE_YOU_SURE_DELETE_VOLUNTEER_OPPORTUNITY")
          : t("COMMON.ARE_YOU_SURE_DELETE_LEARNSHARE_OPPORTUNITY")}
      </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>
  );
}
