"use client";

import { useState, useRef } from "react";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Sparkles, Loader2, Camera, Type, Upload, X, Shuffle, ChefHat } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
import { useLocale } from "@/lib/i18n/provider";
import { BatchCookFields, type BatchCookFieldsState } from "./batch-cook-fields";
import { UpgradeDialog } from "@/components/premium/upgrade-dialog";
import { ProBadge } from "@/components/premium/pro-badge";

const SURPRISE_PROMPTS = [
  "A cozy one-pot dish with whatever is in my pantry on a rainy evening",
  "A vibrant street food recipe from Southeast Asia",
  "A classic French bistro dish reimagined as a weeknight dinner",
  "A hearty plant-based bowl with bold spices",
  "A 5-ingredient pasta with pantry staples",
  "An unexpected fusion of Japanese and Mexican flavors",
  "A light summer salad with fresh herbs and a citrus dressing",
  "A slow-cooked braise that fills the house with aroma",
  "A festive appetizer that looks impressive but is easy to make",
  "A warming spiced soup from the Middle East",
  "A crowd-pleasing comfort food with a twist",
  "A 20-minute weeknight dinner using chicken thighs",
  "A rich chocolate dessert with a molten center",
  "A crispy baked dish that tastes deep-fried",
  "A refreshing no-cook meal for hot summer days",
];

type Tab = "describe" | "photo" | "batch";

type GeneratedRecipe = {
  title: string;
  description?: string;
  baseServings?: number;
  prepMins?: number;
  cookMins?: number;
  difficulty?: "easy" | "medium" | "hard";
  dietaryTags?: Record<string, boolean>;
  ingredients: Array<{ rawName: string; quantity?: string; unit?: string; note?: string }>;
  steps: Array<{ instruction: string; timerSeconds?: number }>;
};

export function AiGenerateDialog({
  open,
  onOpenChange,
  photoTabAvailable = true,
  photoTabLocked = false,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Tier feature flag (recipe_import_photo) disabled for every tier —
   * hides the Photo tab entirely, since there's no upgrade path. */
  photoTabAvailable?: boolean;
  /** Available on some tier but not the viewer's — the tab still shows
   * (with a "Pro" upsell); generating opens an upgrade prompt instead of
   * calling the import API. */
  photoTabLocked?: boolean;
}) {
  const t = useTranslations("ai.generate");
  const tCommon = useTranslations("common");
  const tRecipe = useTranslations("recipe");
  const tBatch = useTranslations("batchCooking");
  const router = useRouter();
  const { locale } = useLocale();
  const [tab, setTab] = useState<Tab>("describe");

  // describe tab
  const [prompt, setPrompt] = useState("");
  const [difficulty, setDifficulty] = useState<"" | "easy" | "medium" | "hard">("");

  // photo tab
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [photoBase64, setPhotoBase64] = useState<string | null>(null);
  const [photoMime, setPhotoMime] = useState<string>("image/jpeg");
  const fileRef = useRef<HTMLInputElement>(null);

  // batch tab
  const [batchFields, setBatchFields] = useState<BatchCookFieldsState>({
    dinners: 4,
    lunches: 0,
    servings: 4,
    difficulty: "",
    dietaryPrefs: "",
    description: "",
  });

  const [busy, setBusy] = useState(false);
  const [upgradeOpen, setUpgradeOpen] = useState(false);

  function handleClose() {
    if (busy) return;
    onOpenChange(false);
    setTimeout(() => {
      setPrompt("");
      setPhotoPreview(null);
      setPhotoBase64(null);
      setBatchFields({ dinners: 4, lunches: 0, servings: 4, difficulty: "", dietaryPrefs: "", description: "" });
      setTab("describe");
    }, 200);
  }

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setPhotoMime(file.type);
    const reader = new FileReader();
    reader.onload = (ev) => {
      const dataUrl = ev.target?.result as string;
      setPhotoPreview(dataUrl);
      // strip the data:mime;base64, prefix
      setPhotoBase64(dataUrl.split(",")[1] ?? null);
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  }

  async function handleDescribeGenerate() {
    if (!prompt.trim()) return;
    setBusy(true);
    try {
      const res = await fetch("/api/v1/ai/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt: prompt.trim(), language: locale, difficulty: difficulty || undefined }),
      });
      if (!res.ok) {
        const err = await res.json() as { error?: string };
        toast.error(err.error ?? t("error"));
        return;
      }
      const generated = await res.json() as GeneratedRecipe;
      const saveRes = await fetch("/api/v1/recipes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true, language: locale }),
      });
      if (!saveRes.ok) { toast.error(t("saveError")); return; }
      const saved = await saveRes.json() as { id: string };
      toast.success(t("success"));
      handleClose();
      router.push(`/recipes/${saved.id}/edit`);
    } finally {
      setBusy(false);
    }
  }

  async function handlePhotoGenerate() {
    if (!photoBase64) return;
    if (photoTabLocked) {
      setUpgradeOpen(true);
      return;
    }
    setBusy(true);
    try {
      const res = await fetch("/api/v1/ai/import-photo", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ imageBase64: photoBase64, mimeType: photoMime }),
      });
      if (!res.ok) {
        let msg = res.status === 422 ? tRecipe("photoNoRecipeFound") : t("photoError");
        if (res.status !== 422) {
          try { msg = ((await res.json()) as { error?: string }).error ?? msg; } catch { /* non-JSON body */ }
        }
        toast.error(msg);
        return;
      }
      const { id } = await res.json() as { id: string };
      toast.success(t("photoSuccess"));
      handleClose();
      router.push(`/recipes/${id}/edit`);
    } finally {
      setBusy(false);
    }
  }

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

  const canSubmit = tab === "describe" ? !!prompt.trim() : tab === "photo" ? !!photoBase64 : batchFields.dinners + batchFields.lunches > 0;

  return (
    <>
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-xl max-h-[85vh] flex flex-col gap-0 p-0">
        <div className="overflow-y-auto p-4 space-y-4 min-h-0">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            {t("title")}
          </DialogTitle>
          <DialogDescription>
            {t("descriptionFull")}
          </DialogDescription>
        </DialogHeader>

        {/* Tab switcher */}
        <div className="flex gap-1 p-1 bg-muted rounded-lg">
          {([
            { key: "describe", label: t("tabDescribe"), icon: Type },
            ...(photoTabAvailable ? [{ key: "photo" as Tab, label: t("tabPhoto"), icon: Camera }] : []),
            { key: "batch", label: tBatch("title"), icon: ChefHat },
          ] as { key: Tab; label: string; icon: React.ElementType }[]).map(({ key, label, icon: Icon }) => (
            <button
              key={key}
              onClick={() => setTab(key)}
              disabled={busy}
              className={cn(
                "flex-1 flex items-center justify-center gap-1.5 py-2 px-3 rounded-md text-sm font-medium transition-all",
                tab === key
                  ? "bg-background shadow-sm text-foreground"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              <Icon className="h-4 w-4" />
              {label}
              {key === "photo" && photoTabLocked && <ProBadge />}
            </button>
          ))}
        </div>

        {/* Describe tab */}
        {tab === "describe" && (
          <div className="space-y-4">
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="ai-prompt">{t("prompt")}</Label>
                <button
                  type="button"
                  onClick={() => {
                    const idx = Math.floor(Math.random() * SURPRISE_PROMPTS.length);
                    setPrompt(SURPRISE_PROMPTS[idx]!);
                  }}
                  disabled={busy}
                  className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors disabled:opacity-50"
                >
                  <Shuffle className="h-3 w-3" />
                  {t("surpriseMe")}
                </button>
              </div>
              <Textarea
                id="ai-prompt"
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                placeholder={t("placeholder")}
                rows={4}
                disabled={busy}
              />
            </div>
            <div className="space-y-2">
              <Label>{t("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>
        )}

        {/* Photo tab */}
        {tab === "photo" && (
          <div className="space-y-3">
            <input
              ref={fileRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="hidden"
              onChange={handleFileChange}
            />
            {photoPreview ? (
              <div className="relative rounded-xl overflow-hidden border bg-muted aspect-video">
                <Image
                  src={photoPreview}
                  alt="Preview of uploaded dish photo for AI recipe generation"
                  fill
                  className="object-cover"
                />
                <button
                  onClick={() => { setPhotoPreview(null); setPhotoBase64(null); }}
                  className="absolute top-2 right-2 h-7 w-7 rounded-full bg-black/60 flex items-center justify-center text-white hover:bg-black/80 transition-colors"
                  disabled={busy}
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            ) : (
              <button
                onClick={() => fileRef.current?.click()}
                disabled={busy}
                className="w-full border-2 border-dashed rounded-xl p-10 flex flex-col items-center gap-3 text-muted-foreground hover:border-primary/50 hover:text-foreground transition-colors"
              >
                <Upload className="h-8 w-8" />
                <div className="text-sm text-center">
                  <span className="font-medium text-foreground">{t("uploadClick")}</span> {t("uploadDrag")}
                  <p className="text-xs mt-1">{t("uploadFormats")}</p>
                </div>
              </button>
            )}
            {photoPreview && (
              <p className="text-xs text-muted-foreground text-center">
                {t("photoAnalysisNote")}
              </p>
            )}
          </div>
        )}

        {/* Batch cooking tab */}
        {tab === "batch" && (
          <BatchCookFields state={batchFields} onChange={setBatchFields} disabled={busy} />
        )}

        <div className="min-h-[26px]">
          <FakeProgressBar
            active={busy}
            durationMs={tab === "photo" ? 12000 : tab === "batch" ? 20000 : 10000}
            label={busy ? (tab === "photo" ? t("analyzePhoto") : tab === "batch" ? tBatch("generating") : t("generating")) : undefined}
          />
        </div>
        </div>
        {/* Actions */}
        <div className="flex gap-2 justify-end p-4 border-t shrink-0">
          <Button variant="ghost" onClick={handleClose} disabled={busy}>
            {tCommon("cancel")}
          </Button>
          <Button
            onClick={
              tab === "describe" ? () => { void handleDescribeGenerate(); }
              : tab === "photo" ? () => { void handlePhotoGenerate(); }
              : () => { void handleBatchGenerate(); }
            }
            disabled={!canSubmit || busy}
          >
            {busy ? (
              <><Loader2 className="h-4 w-4 animate-spin" />{tab === "batch" ? tBatch("generating") : t("analyzing")}</>
            ) : (
              <><Sparkles className="h-4 w-4" />{tab === "photo" ? t("recognizeDish") : tab === "batch" ? tBatch("generate") : t("button")}</>
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
    <UpgradeDialog
      open={upgradeOpen}
      onOpenChange={setUpgradeOpen}
      featureKey="recipe_import_photo"
      featureLabel="Import from photo"
    />
    </>
  );
}
