"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Plus } 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 { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";

type Visibility = "private" | "unlisted" | "public" | "followers";

export function NewCollectionButton() {
  const t = useTranslations("collections");
  const tSocial = useTranslations("social");
  const tCommon = useTranslations("common");
  const tRecipe = useTranslations("recipe");
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [visibility, setVisibility] = useState<Visibility>("private");
  const [saving, setSaving] = useState(false);

  async function create() {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const res = await fetch("/api/v1/collections", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim(), description: description.trim() || undefined, visibility }),
      });
      if (!res.ok) { toast.error(t("createFailed")); return; }
      const { id } = await res.json() as { id: string };
      toast.success(tSocial("collectionCreated"));
      setOpen(false);
      setName(""); setDescription(""); setVisibility("private");
      router.push(`/collections/${id}`);
      router.refresh();
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <Button size="sm" onClick={() => setOpen(true)}>
        <Plus className="h-4 w-4" /> {t("new")}
      </Button>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader><DialogTitle>{t("newTitle")}</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="col-name">{t("nameLabel")}</Label>
              <Input id="col-name" value={name} onChange={(e) => setName(e.target.value)} placeholder={t("namePlaceholder")} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="col-desc">{t("descriptionLabel")}</Label>
              <Textarea id="col-desc" value={description} onChange={(e) => setDescription(e.target.value)} rows={2} placeholder={t("descriptionPlaceholder")} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="col-visibility">{tRecipe("visibilityMenuLabel")}</Label>
              <select
                id="col-visibility"
                value={visibility}
                onChange={(e) => setVisibility(e.target.value as Visibility)}
                className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs"
              >
                <option value="private">{tRecipe("visibility.private")}</option>
                <option value="followers">{tRecipe("visibility.followers")}</option>
                <option value="unlisted">{tRecipe("visibility.unlisted")}</option>
                <option value="public">{tRecipe("visibility.public")}</option>
              </select>
            </div>
            <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("creating") : t("create")}</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
