"use client";

import { useRef, useState, type KeyboardEvent } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Pencil, Tag, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";

export function EditCollectionDialog({
  collectionId,
  initialName,
  initialDescription,
  initialNotes,
  initialTags,
  initialIsPublic,
}: {
  collectionId: string;
  initialName: string;
  initialDescription: string | null;
  initialNotes: string | null;
  initialTags: string[];
  initialIsPublic: boolean;
}) {
  const t = useTranslations("collections");
  const tRecipeForm = useTranslations("recipeForm");
  const tCommon = useTranslations("common");
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [name, setName] = useState(initialName);
  const [description, setDescription] = useState(initialDescription ?? "");
  const [notes, setNotes] = useState(initialNotes ?? "");
  const [tags, setTags] = useState<string[]>(initialTags);
  const [tagInput, setTagInput] = useState("");
  const [isPublic, setIsPublic] = useState(initialIsPublic);
  const [saving, setSaving] = useState(false);
  const tagInputRef = useRef<HTMLInputElement>(null);

  function addTag(raw: string) {
    const tag = raw.trim().toLowerCase().slice(0, 50);
    if (!tag || tags.includes(tag) || tags.length >= 20) return;
    setTags((prev) => [...prev, tag]);
    setTagInput("");
  }

  function removeTag(tag: string) {
    setTags((prev) => prev.filter((tg) => tg !== tag));
  }

  function handleTagKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") {
      e.preventDefault();
      addTag(tagInput);
    } else if (e.key === "Backspace" && !tagInput && tags.length > 0) {
      setTags((prev) => prev.slice(0, -1));
    }
  }

  async function handleSave() {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/v1/collections/${collectionId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: name.trim(),
          description: description.trim() || null,
          notes: notes.trim() || null,
          tags,
          isPublic,
        }),
      });
      if (!res.ok) throw new Error();
      toast.success(t("editSuccess"));
      setOpen(false);
      router.refresh();
    } catch {
      toast.error(t("editFailed"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger render={
            <Button variant="ghost" size="icon" onClick={() => setOpen(true)} aria-label={tCommon("edit")}>
              <Pencil className="h-4 w-4" />
            </Button>
          } />
          <TooltipContent>{tCommon("edit")}</TooltipContent>
        </Tooltip>
      </TooltipProvider>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{t("editTitle")}</DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="edit-col-name">{t("nameLabel")}</Label>
              <Input id="edit-col-name" value={name} onChange={(e) => setName(e.target.value)} placeholder={t("namePlaceholder")} maxLength={100} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="edit-col-desc">{t("descriptionLabel")}</Label>
              <Textarea id="edit-col-desc" value={description} onChange={(e) => setDescription(e.target.value)} rows={2} placeholder={t("descriptionPlaceholder")} maxLength={500} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="edit-col-notes">{t("notesLabel")}</Label>
              <Textarea id="edit-col-notes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} placeholder={t("notesPlaceholder")} maxLength={2000} />
            </div>

            <div className="space-y-2">
              <Label>{t("tagsLabel")}</Label>
              <div
                className="flex flex-wrap gap-1.5 min-h-9 rounded-lg border border-input bg-transparent px-2.5 py-1.5 cursor-text focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50"
                onClick={() => tagInputRef.current?.focus()}
              >
                {tags.map((tag) => (
                  <span key={tag} className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-xs bg-muted text-muted-foreground">
                    <Tag className="h-2.5 w-2.5" />
                    {tag}
                    <button type="button" onClick={(e) => { e.stopPropagation(); removeTag(tag); }} className="hover:text-foreground transition-colors" aria-label={tRecipeForm("removeTagAriaLabel", { tag })}>
                      <X className="h-2.5 w-2.5" />
                    </button>
                  </span>
                ))}
                {tags.length < 20 && (
                  <input
                    ref={tagInputRef}
                    value={tagInput}
                    onChange={(e) => setTagInput(e.target.value)}
                    onKeyDown={handleTagKeyDown}
                    onBlur={() => { if (tagInput.trim()) addTag(tagInput); }}
                    placeholder={tags.length === 0 ? tRecipeForm("tagsPlaceholder") : ""}
                    className="flex-1 min-w-[120px] bg-transparent text-sm outline-none placeholder:text-muted-foreground"
                  />
                )}
              </div>
            </div>

            <label className="flex items-center gap-2 text-sm cursor-pointer">
              <input type="checkbox" checked={isPublic} onChange={(e) => setIsPublic(e.target.checked)} className="rounded" />
              {t("makePublic")}
            </label>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>{tCommon("cancel")}</Button>
            <Button onClick={() => { void handleSave(); }} disabled={!name.trim() || saving}>
              {saving ? t("saving") : tCommon("save")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
