"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { ChefHat, Loader2, Minus, Plus } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";

function Counter({ value, onChange, max = 6 }: { value: number; onChange: (v: number) => void; max?: number }) {
  return (
    <div className="flex items-center gap-2">
      <Button type="button" variant="outline" size="icon" onClick={() => onChange(Math.max(0, value - 1))}>
        <Minus className="h-4 w-4" />
      </Button>
      <span className="w-8 text-center font-medium tabular-nums">{value}</span>
      <Button type="button" variant="outline" size="icon" onClick={() => onChange(Math.min(max, value + 1))}>
        <Plus className="h-4 w-4" />
      </Button>
    </div>
  );
}

export function BatchCookGenerateDialog({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const t = useTranslations("batchCooking");
  const tCommon = useTranslations("common");
  const tRecipe = useTranslations("recipe");
  const router = useRouter();

  const [dinners, setDinners] = useState(4);
  const [lunches, setLunches] = useState(0);
  const [servings, setServings] = useState(4);
  const [dietaryPrefs, setDietaryPrefs] = useState("");
  const [difficulty, setDifficulty] = useState<"" | "easy" | "medium" | "hard">("");
  const [busy, setBusy] = useState(false);

  function handleClose() {
    if (busy) return;
    onOpenChange(false);
  }

  async function handleGenerate() {
    setBusy(true);
    try {
      const res = await fetch("/api/v1/ai/batch-cook/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          dinners,
          lunches,
          servings,
          dietaryPrefs: dietaryPrefs.trim() || undefined,
          difficulty: difficulty || undefined,
        }),
      });
      if (!res.ok) {
        const err = await res.json() as { error?: string };
        toast.error(err.error ?? t("generateFailed"));
        return;
      }
      const { id } = await res.json() as { id: string };
      toast.success(t("generateSuccess"));
      onOpenChange(false);
      router.push(`/recipes/${id}`);
    } finally {
      setBusy(false);
    }
  }

  const canSubmit = dinners + lunches > 0;

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <ChefHat className="h-5 w-5 text-primary" />
            {t("wizardTitle")}
          </DialogTitle>
          <DialogDescription>{t("wizardDescription")}</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <Label>{t("dinners")}</Label>
            <Counter value={dinners} onChange={setDinners} />
          </div>
          <div className="flex items-center justify-between">
            <Label>{t("lunches")}</Label>
            <Counter value={lunches} onChange={setLunches} />
          </div>
          <div className="flex items-center justify-between">
            <Label>{t("servingsPerMeal")}</Label>
            <Counter value={servings} onChange={setServings} max={12} />
          </div>
          <div className="space-y-2">
            <Label>{tCommon("difficulty")}</Label>
            <Select value={difficulty} onValueChange={(v) => setDifficulty(v as typeof difficulty)} disabled={busy}>
              <SelectTrigger>
                <SelectValue placeholder={t("anyDifficulty")} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="">{t("anyDifficulty")}</SelectItem>
                <SelectItem value="easy">{tRecipe("difficulty.easy")}</SelectItem>
                <SelectItem value="medium">{tRecipe("difficulty.medium")}</SelectItem>
                <SelectItem value="hard">{tRecipe("difficulty.hard")}</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="batch-dietary">{t("dietaryPrefs")}</Label>
            <Input
              id="batch-dietary"
              value={dietaryPrefs}
              onChange={(e) => setDietaryPrefs(e.target.value)}
              placeholder={t("dietaryPrefsPlaceholder")}
              disabled={busy}
            />
          </div>
        </div>

        <FakeProgressBar active={busy} durationMs={20000} label={busy ? t("generating") : undefined} />

        <div className="flex gap-2 justify-end pt-1">
          <Button variant="ghost" onClick={handleClose} disabled={busy}>
            {tCommon("cancel")}
          </Button>
          <Button onClick={() => { void handleGenerate(); }} disabled={!canSubmit || busy}>
            {busy ? (
              <><Loader2 className="h-4 w-4 animate-spin" />{t("generating")}</>
            ) : (
              <><ChefHat className="h-4 w-4" />{t("generate")}</>
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
