"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Tag, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";

export function BulkTagsDialog({
  open,
  onOpenChange,
  recipeIds,
  availableTags,
  onDone,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  recipeIds: string[];
  availableTags: string[];
  onDone: (addTags: string[], removeTags: string[]) => void;
}) {
  const t = useTranslations("recipe");
  const tCommon = useTranslations("common");
  const [addInput, setAddInput] = useState("");
  const [toAdd, setToAdd] = useState<string[]>([]);
  const [toRemove, setToRemove] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);

  function commitAddInput() {
    const tag = addInput.trim();
    if (tag && !toAdd.includes(tag)) setToAdd((prev) => [...prev, tag]);
    setAddInput("");
  }

  function toggleRemove(tag: string) {
    setToRemove((prev) => (prev.includes(tag) ? prev.filter((x) => x !== tag) : [...prev, tag]));
  }

  async function save() {
    if (toAdd.length === 0 && toRemove.length === 0) {
      onOpenChange(false);
      return;
    }
    setSaving(true);
    try {
      const res = await fetch("/api/v1/recipes/bulk", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: recipeIds, addTags: toAdd, removeTags: toRemove }),
      });
      if (!res.ok) throw new Error();
      toast.success(t("bulkTagsUpdated", { count: recipeIds.length }));
      onOpenChange(false);
      onDone(toAdd, toRemove);
      setToAdd([]);
      setToRemove([]);
    } catch {
      toast.error(t("bulkUpdateFailed"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Tag className="h-5 w-5 text-primary" />
            {t("bulkTagsTitle", { count: recipeIds.length })}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <p className="text-sm font-medium">{t("bulkTagsAddLabel")}</p>
            <div className="flex gap-2">
              <Input
                value={addInput}
                onChange={(e) => setAddInput(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === ",") {
                    e.preventDefault();
                    commitAddInput();
                  }
                }}
                placeholder={t("bulkTagsAddPlaceholder")}
              />
              <Button type="button" variant="outline" onClick={commitAddInput} disabled={!addInput.trim()}>
                {t("bulkTagsAddButton")}
              </Button>
            </div>
            {toAdd.length > 0 && (
              <div className="flex flex-wrap gap-1.5">
                {toAdd.map((tag) => (
                  <Badge key={tag} variant="secondary" className="gap-1 pr-1">
                    {tag}
                    <button onClick={() => setToAdd((prev) => prev.filter((x) => x !== tag))} className="rounded-full hover:bg-muted-foreground/20 p-0.5">
                      <X className="h-3 w-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}
          </div>

          {availableTags.length > 0 && (
            <div className="space-y-2">
              <p className="text-sm font-medium">{t("bulkTagsRemoveLabel")}</p>
              <div className="flex flex-wrap gap-1.5">
                {availableTags.map((tag) => (
                  <button key={tag} onClick={() => toggleRemove(tag)}>
                    <Badge variant={toRemove.includes(tag) ? "destructive" : "outline"} className="cursor-pointer">
                      {tag}
                    </Badge>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}>
            {tCommon("cancel")}
          </Button>
          <Button onClick={() => { void save(); }} disabled={saving || (toAdd.length === 0 && toRemove.length === 0)}>
            {tCommon("save")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
