"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { UpgradeDialog } from "@/components/premium/upgrade-dialog";
import { ProBadge } from "@/components/premium/pro-badge";

type NutritionTotals = {
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
};

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

type NutritionCoverage = {
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
};

type NutritionResponse = {
  totals: NutritionTotals;
  dailyAverage: NutritionTotals;
  unknownCount: number;
  goals: NutritionGoals;
  coverage: NutritionCoverage;
};

interface WeeklyNutritionBarProps {
  weekStart: string;
  /** Available on some tier but not the viewer's — shows a locked teaser
   * (with a "Pro" upsell) instead of hiding, and skips fetching totals. */
  locked?: boolean;
}

type BarItem = {
  label: string;
  value: number;
  goal: number | null;
  unit: string;
  percentage: number;
  colorClass: string;
};

export function WeeklyNutritionBar({ weekStart, locked = false }: WeeklyNutritionBarProps) {
  const t = useTranslations("mealPlan.nutritionBar");
  const [data, setData] = useState<NutritionResponse | null>(null);
  const [upgradeOpen, setUpgradeOpen] = useState(false);

  useEffect(() => {
    if (locked) return;
    fetch(`/api/v1/meal-plans/${weekStart}/nutrition`)
      .then((res) => (res.ok ? res.json() : null))
      .then((json) => setData(json))
      .catch(() => setData(null));
  }, [weekStart, locked]);

  if (locked) {
    return (
      <>
        <button
          type="button"
          onClick={() => setUpgradeOpen(true)}
          className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
        >
          {t("dailyAverageVsGoals")}
          <ProBadge />
        </button>
        <UpgradeDialog
          open={upgradeOpen}
          onOpenChange={setUpgradeOpen}
          featureKey="weekly_nutrition"
          featureLabel="Weekly nutrition"
        />
      </>
    );
  }

  if (!data || !data.goals) return null;

  const { dailyAverage, goals, coverage, unknownCount } = data;

  const bars: BarItem[] = [
    {
      label: t("calories"),
      value: dailyAverage.calories,
      goal: goals.caloriesKcal,
      unit: "kcal",
      percentage: coverage.calories,
      colorClass: "bg-orange-500",
    },
    {
      label: t("protein"),
      value: dailyAverage.protein,
      goal: goals.proteinG,
      unit: "g",
      percentage: coverage.protein,
      colorClass: "bg-blue-500",
    },
    {
      label: t("carbs"),
      value: dailyAverage.carbs,
      goal: goals.carbsG,
      unit: "g",
      percentage: coverage.carbs,
      colorClass: "bg-green-500",
    },
    {
      label: t("fat"),
      value: dailyAverage.fat,
      goal: goals.fatG,
      unit: "g",
      percentage: coverage.fat,
      colorClass: "bg-yellow-500",
    },
  ];

  return (
    <div className="space-y-3">
      <p className="text-xs text-muted-foreground">{t("dailyAverageVsGoals")}</p>
      {bars.map((bar) => {
        if (bar.goal == null) return null;
        const width = Math.min(bar.percentage, 100);
        return (
          <div key={bar.label} className="space-y-1">
            <div className="flex justify-between text-sm">
              <span className="font-medium">{bar.label}</span>
              <span className="text-muted-foreground">
                {bar.value} / {bar.goal} {bar.unit}
              </span>
            </div>
            <div className="h-2 w-full rounded bg-muted overflow-hidden">
              <div
                className={`h-full rounded ${bar.colorClass}`}
                style={{ width: `${width}%` }}
              />
            </div>
          </div>
        );
      })}
      {unknownCount > 0 && (
        <p className="text-xs text-muted-foreground">
          {t(unknownCount === 1 ? "missingDataSingular" : "missingDataPlural", { count: unknownCount })}
        </p>
      )}
    </div>
  );
}
