"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import type { NotificationCategory, NotificationPrefs } from "@/lib/notification-prefs";

const CATEGORIES: NotificationCategory[] = [
  "follow", "comment", "reply", "reaction", "rating", "mention", "leftoverExpiring", "shoppingList",
];

export function NotificationCategoriesForm() {
  const t = useTranslations("settingsForm.notificationCategories");
  const t_common = useTranslations("common");
  const [prefs, setPrefs] = useState<NotificationPrefs | null>(null);
  const [saving, setSaving] = useState<NotificationCategory | null>(null);

  useEffect(() => {
    fetch("/api/v1/users/me/notification-prefs")
      .then((res) => (res.ok ? res.json() : null))
      .then((json) => setPrefs(json?.data ?? null))
      .catch(() => setPrefs(null));
  }, []);

  async function toggle(category: NotificationCategory, checked: boolean) {
    if (!prefs) return;
    const previous = prefs;
    setPrefs({ ...prefs, [category]: checked });
    setSaving(category);
    try {
      const res = await fetch("/api/v1/users/me/notification-prefs", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [category]: checked }),
      });
      if (!res.ok) {
        setPrefs(previous);
        toast.error(t_common("saveFailed"));
      }
    } catch {
      setPrefs(previous);
      toast.error(t_common("saveFailed"));
    } finally {
      setSaving(null);
    }
  }

  if (!prefs) return null;

  return (
    <div className="space-y-3">
      {CATEGORIES.map((category) => (
        <div key={category} className="flex items-center justify-between gap-3">
          <Label htmlFor={`notif-${category}`} className="cursor-pointer">
            {t(category)}
          </Label>
          <Switch
            id={`notif-${category}`}
            checked={prefs[category]}
            disabled={saving === category}
            onCheckedChange={(checked) => { void toggle(category, checked); }}
          />
        </div>
      ))}
    </div>
  );
}
