"use client";

import { useState } from "react";
import { toast } from "sonner";
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 [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("Failed to save nutrition goals");
        return;
      }

      toast.success("Nutrition goals saved");
    } catch {
      toast.error("Failed to save nutrition goals");
    } 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">Calories (kcal/day)</Label>
          <Input
            id="caloriesKcal"
            type="number"
            min={0}
            value={caloriesKcal}
            onChange={(e) => setCaloriesKcal(e.target.value)}
            placeholder="e.g. 2000"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="proteinG">Protein (g/day)</Label>
          <Input
            id="proteinG"
            type="number"
            min={0}
            value={proteinG}
            onChange={(e) => setProteinG(e.target.value)}
            placeholder="e.g. 50"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="carbsG">Carbs (g/day)</Label>
          <Input
            id="carbsG"
            type="number"
            min={0}
            value={carbsG}
            onChange={(e) => setCarbsG(e.target.value)}
            placeholder="e.g. 250"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="fatG">Fat (g/day)</Label>
          <Input
            id="fatG"
            type="number"
            min={0}
            value={fatG}
            onChange={(e) => setFatG(e.target.value)}
            placeholder="e.g. 70"
          />
        </div>
      </div>
      <Button type="submit" disabled={saving}>
        {saving ? "Saving..." : "Save goals"}
      </Button>
    </form>
  );
}
