"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Plus, ShoppingCart } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

export function NewShoppingListButton({
  defaultWeekStart,
  defaultName,
}: {
  /** Pre-fills and locks the source week, e.g. when generating from the currently-viewed meal-plan week. */
  defaultWeekStart?: string;
  defaultName?: string;
}) {
  const t = useTranslations("mealPlan");
  const tCommon = useTranslations("common");
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [name, setName] = useState(defaultName ?? "");
  const [weekStart, setWeekStart] = useState(defaultWeekStart ?? "");
  const [saving, setSaving] = useState(false);

  function openDialog() {
    if (defaultWeekStart) { setName(defaultName ?? ""); setWeekStart(defaultWeekStart); }
    setOpen(true);
  }

  async function create() {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const res = await fetch("/api/v1/shopping-lists", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: name.trim(),
          fromMealPlanWeek: weekStart || undefined,
        }),
      });
      if (!res.ok) { toast.error(t("listCreateFailed")); return; }
      const { id } = await res.json() as { id: string };
      toast.success(t("listCreated"));
      setOpen(false);
      setName(""); setWeekStart("");
      router.push(`/shopping-lists/${id}`);
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      {defaultWeekStart ? (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger render={
              <Button size="icon" variant="ghost" onClick={openDialog} aria-label={t("generateFromThisWeek")}>
                <ShoppingCart className="h-4 w-4" />
              </Button>
            } />
            <TooltipContent>{t("generateFromThisWeek")}</TooltipContent>
          </Tooltip>
        </TooltipProvider>
      ) : (
        <Button size="sm" onClick={openDialog} variant="default">
          <Plus className="h-4 w-4" />
          {t("newList")}
        </Button>
      )}
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader><DialogTitle>{t("newListTitle")}</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>{t("listNameLabel")}</Label>
              <Input value={name} onChange={(e) => setName(e.target.value)} placeholder={t("listNamePlaceholder")} />
            </div>
            {!defaultWeekStart && (
              <div className="space-y-2">
                <Label>{t("generateFromWeek")}</Label>
                <Input type="date" value={weekStart} onChange={(e) => setWeekStart(e.target.value)} />
                <p className="text-xs text-muted-foreground">{t("generateFromWeekHint")}</p>
              </div>
            )}
            {defaultWeekStart && (
              <p className="text-xs text-muted-foreground">{t("generateFromThisWeekHint")}</p>
            )}
            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setOpen(false)}>{tCommon("cancel")}</Button>
              <Button onClick={create} disabled={!name.trim() || saving}>{saving ? t("listCreating") : t("listCreate")}</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
