"use client";
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Modal } from "@/components/ui/Modal";
import Button from "@/components/ui/Button";
import { getOpportunityById } from "../services/opportunities";
import { reopenVolunteerOpportunityRegistration } from "../services/registrations";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";
export default function ReopenRegistrationModal({ id, open, onClose, onChanged }: { id: string; open: boolean; onClose: () => void; onChanged: () => void }) {
  const { t } = useTranslation(); const language = useLanguageStore(s => s.language);
  const [increase, setIncrease] = useState(false); const [capacity, setCapacity] = useState(""); const [submitted, setSubmitted] = useState(false);
  const query = useQuery({ queryKey: ["reopen-capacity", id], queryFn: () => getOpportunityById(id), enabled: open, staleTime: 0 });
  const current = Number(query.data?.data?.participants_needed ?? 0);
  const used = Number(query.data?.data?.registered_volunteers_count ?? 0);
  const next = increase ? Number(capacity) : current;
  const valid = Number.isInteger(next) && next >= current && next > used;
  const mutation = useMutation({ mutationFn: () => reopenVolunteerOpportunityRegistration(id, increase ? { participants_needed: next } : undefined),
    onSuccess: () => { onClose(); onChanged(); toast.success(t("COMMON.TOAST.REOPEN_REGISTRATION_SUCCESS")); },
    onError: e => toast.error(getApiErrorMessage(e, language) || t("COMMON.UPDATE_FAILED")) });
  return <Modal open={open} onClose={onClose} size="small" title={t("COMMON.REOPEN_REGISTRATION")}>
    <form className="space-y-5 py-3" onSubmit={e => { e.preventDefault(); setSubmitted(true); if (valid) mutation.mutate(); }}>
      <p className="text-sm leading-relaxed">{t("COMMON.REOPEN_CAPACITY_QUESTION")}</p>
      <label className="flex items-center gap-3"><input type="checkbox" checked={increase} onChange={e => { setIncrease(e.target.checked); if (!capacity) setCapacity(String(Math.max(current, used) + 1)); }} />{t("COMMON.INCREASE_CAPACITY")}</label>
      {increase && <label className="block space-y-2"><span>{t("COMMON.PARTICIPANTS_NEEDED")}</span><input aria-label={t("COMMON.PARTICIPANTS_NEEDED")} type="number" min={Math.max(current, used + 1)} value={capacity} onChange={e => setCapacity(e.target.value)} className="w-full rounded-xl border p-3" /></label>}
      {submitted && !valid && <p role="alert" className="text-sm text-red-600">{t("COMMON.REOPEN_CAPACITY_INVALID")}</p>}
      {query.isError && <p role="alert">{t("COMMON.UPDATE_FAILED")}</p>}
      <div className="flex flex-wrap justify-center gap-3 pt-3">
        <Button
          type="submit"
          size="medium"
          className="min-h-11 !w-auto min-w-[120px] flex-1 px-6 sm:flex-none"
          loading={mutation.isPending}
          disabled={query.isFetching || query.isError}
        >
          {t("COMMON.CONFIRM")}
        </Button>
        <Button
          type="button"
          variant="secondary"
          size="medium"
          className="min-h-11 !w-auto min-w-[120px] flex-1 border border-primary-5/20 px-6 sm:flex-none"
          onClick={onClose}
          disabled={mutation.isPending}
        >
          {t("COMMON.CANCEL")}
        </Button>
      </div>
    </form>
  </Modal>;
}
