"use client";

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

import Button from "@/components/ui/Button";
import Toggle from "@/components/ui/Toggle";
import { getApiErrorMessage } from "@/lib/api/errors";
import { useLanguageStore } from "@/store/languageStore";
import {
  getVolunteerProfile,
  updateVolunteerProfile,
} from "@/features/profile/services/profileApi";

/** Saves the email preference directly from the switch. */
export default function QuietModeCard() {
  const { t } = useTranslation();
  const language = useLanguageStore((s) => s.language);
  const queryClient = useQueryClient();

  const { data, isError, error, refetch } = useQuery({
    queryKey: ["volunteer-profile"],
    queryFn: getVolunteerProfile,
  });
  const enabled = Boolean(data?.data?.do_not_disturb);

  const mutation = useMutation({
    mutationFn: (value: boolean) => updateVolunteerProfile({ do_not_disturb: value }),
    onSuccess: async (_response, value) => {
      toast.success(t(value ? "COMMON.QUIET_MODE_SAVED_ON" : "COMMON.QUIET_MODE_SAVED_OFF"));
      await queryClient.invalidateQueries({ queryKey: ["volunteer-profile"] });
    },
    onError: (error) => {
      toast.error(getApiErrorMessage(error, language) || t("COMMON.QUIET_MODE_SAVE_FAILED"));
    },
  });


  return (
    <section className="rounded-3xl border border-[#29246D14] bg-white p-5">
      <div className="flex items-center justify-between gap-4">
        <h2 className="text-base font-bold text-primary-5">{t("COMMON.DO_NOT_DISTURB")}</h2>
        {(data || !isError) && <Toggle
          label=""
          ariaLabel={t("COMMON.DO_NOT_DISTURB")}
          checked={enabled}
          disabled={!data || mutation.isPending}
          onChange={() => mutation.mutate(!enabled)}
        />}
      </div>
      <p className="mt-2 text-sm text-secondary-102">{t("COMMON.DO_NOT_DISTURB_HINT")}</p>
      {/* A failed read must not look like "off": the switch is hidden and the card says why. */}
      {isError && !data && (
        <div role="alert" className="mt-3 flex flex-wrap items-center gap-3 text-sm text-red-600">
          <span>{getApiErrorMessage(error, language) || t("COMMON.QUIET_MODE_LOAD_FAILED")}</span>
          <Button type="button" size="small" onClick={() => void refetch()}>{t("COMMON.RETRY")}</Button>
        </div>
      )}

    </section>
  );
}
