"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Shuffle, Loader2 } from "lucide-react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Badge } from "@/components/ui/badge";

type Substitution = {
  name: string;
  ratio: string;
  note: string;
  flavorImpact: "minimal" | "moderate" | "significant";
};

const IMPACT_VARIANT = {
  minimal: "default",
  moderate: "secondary",
  significant: "destructive",
} as const;

export function SubstituteIngredientPopover({
  ingredient,
  recipeTitle,
}: {
  ingredient: string;
  recipeTitle: string;
}) {
  const t = useTranslations("substitute");
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [substitutions, setSubstitutions] = useState<Substitution[]>([]);
  const [fetched, setFetched] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function fetchSubstitutions() {
    if (fetched) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/v1/ai/substitute", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ingredient, recipeTitle }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => null) as { error?: string } | null;
        setError(body?.error ?? t("fetchError"));
        return;
      }
      const data = await res.json() as { substitutions: Substitution[] };
      setSubstitutions(data.substitutions);
      setFetched(true);
    } catch {
      setError(t("fetchError"));
    } finally {
      setLoading(false);
    }
  }

  function handleOpen(v: boolean) {
    setOpen(v);
    if (v && !fetched) fetchSubstitutions();
  }

  return (
    <Popover open={open} onOpenChange={handleOpen}>
      <PopoverTrigger
        className="h-5 w-5 opacity-0 group-hover:opacity-60 hover:opacity-100 transition-opacity shrink-0 inline-flex items-center justify-center rounded hover:bg-accent"
        title={t("titleFor", { ingredient })}
      >
        <Shuffle className="h-3 w-3" />
      </PopoverTrigger>
      <PopoverContent className="w-[min(92vw,26rem)] p-3 space-y-3" align="start">
        <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
          {t("substitutesFor")} <span className="text-foreground normal-case">{ingredient}</span>
        </p>
        {loading && (
          <div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">
            <Loader2 className="h-3.5 w-3.5 animate-spin" />
            {t("finding")}
          </div>
        )}
        {!loading && substitutions.length > 0 && (
          <div className="space-y-2.5">
            {substitutions.map((sub, i) => (
              <div key={i} className="space-y-0.5">
                <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                  <span className="text-sm font-medium break-words">{sub.name}</span>
                  <Badge variant={IMPACT_VARIANT[sub.flavorImpact]} className="text-[10px] px-1.5 py-0 shrink-0">
                    {sub.flavorImpact}
                  </Badge>
                  <span className="text-xs text-muted-foreground font-mono w-full sm:w-auto">{sub.ratio}</span>
                </div>
                <p className="text-xs text-muted-foreground">{sub.note}</p>
              </div>
            ))}
          </div>
        )}
        {!loading && error && (
          <p className="text-sm text-destructive py-1">{error}</p>
        )}
        {!loading && fetched && substitutions.length === 0 && (
          <p className="text-sm text-muted-foreground py-1">{t("noneFound")}</p>
        )}
      </PopoverContent>
    </Popover>
  );
}
