"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Wand2, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import type { RegeneratedRecipe } from "@/lib/ai/features/regenerate-recipe";

type CurrentRecipe = {
  title: string;
  description?: string;
  baseServings: number;
  difficulty?: "easy" | "medium" | "hard" | "";
  ingredients: Array<{ rawName: string; quantity?: string; unit?: string }>;
  steps: Array<{ instruction: string }>;
};

export function RegenerateRecipeButton({
  current,
  onRegenerated,
}: {
  current: CurrentRecipe;
  onRegenerated: (recipe: RegeneratedRecipe) => void;
}) {
  const t = useTranslations("recipe");
  const [open, setOpen] = useState(false);
  const [instruction, setInstruction] = useState("");
  const [regenerating, setRegenerating] = useState(false);

  async function handleRegenerate() {
    if (!instruction.trim()) return;
    setRegenerating(true);
    try {
      const res = await fetch("/api/v1/ai/regenerate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: current.title,
          description: current.description || undefined,
          baseServings: current.baseServings,
          difficulty: current.difficulty || undefined,
          ingredients: current.ingredients,
          steps: current.steps,
          instruction: instruction.trim(),
        }),
      });
      if (!res.ok) {
        const err = await res.json() as { error?: string };
        toast.error(err.error ?? t("regenerateFailed"));
        return;
      }
      const regenerated = await res.json() as RegeneratedRecipe;
      onRegenerated(regenerated);
      toast.success(t("regenerated"));
      setOpen(false);
      setInstruction("");
    } catch {
      toast.error(t("regenerateFailed"));
    } finally {
      setRegenerating(false);
    }
  }

  return (
    <>
      <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)} className="gap-1.5">
        <Wand2 className="h-3.5 w-3.5" />
        {t("regenerateWithAi")}
      </Button>

      <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) setInstruction(""); }}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Wand2 className="h-5 w-5 text-primary" />
              {t("regenerateTitle")}
            </DialogTitle>
            <DialogDescription>{t("regenerateDescription")}</DialogDescription>
          </DialogHeader>

          <div className="space-y-2">
            <Label htmlFor="regenerate-instruction">{t("regenerateInstructionLabel")}</Label>
            <Textarea
              id="regenerate-instruction"
              value={instruction}
              onChange={(e) => setInstruction(e.target.value)}
              placeholder={t("regenerateInstructionPlaceholder")}
              rows={3}
              maxLength={500}
              disabled={regenerating}
            />
          </div>

          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setOpen(false)} disabled={regenerating}>
              {t("regenerateCancel")}
            </Button>
            <Button onClick={handleRegenerate} disabled={regenerating || !instruction.trim()}>
              {regenerating
                ? <><Loader2 className="h-4 w-4 animate-spin" />{t("regenerating")}</>
                : <><Wand2 className="h-4 w-4" />{t("regenerateApply")}</>
              }
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
