"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 { FeatureKey, FeaturePrefs } from "@/lib/feature-prefs";

const FEATURES: FeatureKey[] = ["nutrition", "pantry", "mealPlan", "shoppingLists", "collections", "messages"];

export function FeatureTogglesForm() {
  const t = useTranslations("settingsForm.featureToggles");
  const t_common = useTranslations("common");
  const [prefs, setPrefs] = useState<FeaturePrefs | null>(null);
  const [saving, setSaving] = useState<FeatureKey | null>(null);

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

  async function toggle(feature: FeatureKey, checked: boolean) {
    if (!prefs) return;
    const previous = prefs;
    setPrefs({ ...prefs, [feature]: checked });
    setSaving(feature);
    try {
      const res = await fetch("/api/v1/users/me/feature-prefs", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [feature]: checked }),
      });
      if (!res.ok) {
        setPrefs(previous);
        toast.error(t_common("saveFailed"));
      } else {
        // Nav reads this same endpoint on its own mount — no shared client
        // cache to invalidate, so a hard reason to re-fetch is a full nav
        // refresh. Cheapest correct fix: reload so the nav picks it up now
        // instead of on the next navigation.
        window.dispatchEvent(new Event("epicure:feature-prefs-changed"));
      }
    } catch {
      setPrefs(previous);
      toast.error(t_common("saveFailed"));
    } finally {
      setSaving(null);
    }
  }

  if (!prefs) return null;

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