"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",
];

type Field = keyof NotificationPrefs;

export function NotificationCategoriesForm() {
  const t = useTranslations("settingsForm.notificationCategories");
  const t_common = useTranslations("common");
  const [prefs, setPrefs] = useState<NotificationPrefs | null>(null);
  const [saving, setSaving] = useState<Field | 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(field: Field, checked: boolean) {
    if (!prefs) return;
    const previous = prefs;
    setPrefs({ ...prefs, [field]: checked });
    setSaving(field);
    try {
      const res = await fetch("/api/v1/users/me/notification-prefs", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [field]: 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-1">
      <div className="grid grid-cols-[1fr_auto_auto] items-center gap-3 pb-2">
        <span />
        <span className="text-xs font-medium text-muted-foreground w-12 text-center">{t("push")}</span>
        <span className="text-xs font-medium text-muted-foreground w-12 text-center">{t("email")}</span>
      </div>

      {CATEGORIES.map((category) => {
        const emailField = `${category}Email` as const;
        return (
          <div key={category} className="grid grid-cols-[1fr_auto_auto] items-center gap-3 py-2 border-t first:border-t-0">
            <Label htmlFor={`notif-${category}`} className="cursor-pointer">
              {t(category)}
            </Label>
            <div className="w-12 flex justify-center">
              <Switch
                id={`notif-${category}`}
                checked={prefs[category]}
                disabled={saving === category}
                onCheckedChange={(checked) => { void toggle(category, checked); }}
              />
            </div>
            <div className="w-12 flex justify-center">
              <Switch
                id={`notif-${emailField}`}
                checked={prefs[emailField]}
                disabled={saving === emailField}
                onCheckedChange={(checked) => { void toggle(emailField, checked); }}
              />
            </div>
          </div>
        );
      })}

      <div className="grid grid-cols-[1fr_auto_auto] items-center gap-3 py-2 border-t">
        <div>
          <Label htmlFor="notif-weeklyDigestEmail" className="cursor-pointer">
            {t("weeklyDigest")}
          </Label>
          <p className="text-xs text-muted-foreground">{t("weeklyDigestDescription")}</p>
        </div>
        <span className="w-12" />
        <div className="w-12 flex justify-center">
          <Switch
            id="notif-weeklyDigestEmail"
            checked={prefs.weeklyDigestEmail}
            disabled={saving === "weeklyDigestEmail"}
            onCheckedChange={(checked) => { void toggle("weeklyDigestEmail", checked); }}
          />
        </div>
      </div>
    </div>
  );
}
