"use client";

import { useState } from "react";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type NutritionGoals = {
  caloriesKcal: number | null;
  proteinG: number | null;
  carbsG: number | null;
  fatG: number | null;
} | null;

interface NutritionGoalsFormProps {
  initialGoals: NutritionGoals;
}

export function NutritionGoalsForm({ initialGoals }: NutritionGoalsFormProps) {
  const t = useTranslations("settings.nutritionGoals");
  const [caloriesKcal, setCaloriesKcal] = useState<string>(
    initialGoals?.caloriesKcal != null ? String(initialGoals.caloriesKcal) : ""
  );
  const [proteinG, setProteinG] = useState<string>(
    initialGoals?.proteinG != null ? String(initialGoals.proteinG) : ""
  );
  const [carbsG, setCarbsG] = useState<string>(
    initialGoals?.carbsG != null ? String(initialGoals.carbsG) : ""
  );
  const [fatG, setFatG] = useState<string>(
    initialGoals?.fatG != null ? String(initialGoals.fatG) : ""
  );
  const [saving, setSaving] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);

    const body: Record<string, number> = {};
    if (caloriesKcal !== "") body.caloriesKcal = parseInt(caloriesKcal, 10);
    if (proteinG !== "") body.proteinG = parseInt(proteinG, 10);
    if (carbsG !== "") body.carbsG = parseInt(carbsG, 10);
    if (fatG !== "") body.fatG = parseInt(fatG, 10);

    try {
      const res = await fetch("/api/v1/users/me/nutrition-goals", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (!res.ok) {
        toast.error(t("saveError"));
        return;
      }

      toast.success(t("saveSuccess"));
    } catch {
      toast.error(t("saveError"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="caloriesKcal">{t("caloriesLabel")}</Label>
          <Input
            id="caloriesKcal"
            type="number"
            min={0}
            value={caloriesKcal}
            onChange={(e) => setCaloriesKcal(e.target.value)}
            placeholder={t("caloriesPlaceholder")}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="proteinG">{t("proteinLabel")}</Label>
          <Input
            id="proteinG"
            type="number"
            min={0}
            value={proteinG}
            onChange={(e) => setProteinG(e.target.value)}
            placeholder={t("proteinPlaceholder")}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="carbsG">{t("carbsLabel")}</Label>
          <Input
            id="carbsG"
            type="number"
            min={0}
            value={carbsG}
            onChange={(e) => setCarbsG(e.target.value)}
            placeholder={t("carbsPlaceholder")}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="fatG">{t("fatLabel")}</Label>
          <Input
            id="fatG"
            type="number"
            min={0}
            value={fatG}
            onChange={(e) => setFatG(e.target.value)}
            placeholder={t("fatPlaceholder")}
          />
        </div>
      </div>
      <Button type="submit" disabled={saving}>
        {saving ? t("saving") : t("saveButton")}
      </Button>
    </form>
  );
}
