"use client";

import { useState, useCallback, useMemo } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { ListChecks, X, FolderInput, FolderMinus, Check, GripVertical, Search } from "lucide-react";
import {
  DndContext,
  type DragEndEvent,
  PointerSensor,
  useSensor,
  useSensors,
  closestCenter,
} from "@dnd-kit/core";
import {
  SortableContext,
  useSortable,
  verticalListSortingStrategy,
  arrayMove,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { RecipeGridCard, type GridCardRecipe } from "@/components/recipe/recipe-grid-card";
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { cn } from "@/lib/utils";

function SortableRecipeCard({
  recipe,
  selectMode,
  selected,
  onToggle,
  dragDisabled,
}: {
  recipe: GridCardRecipe;
  selectMode: boolean;
  selected: boolean;
  onToggle: () => void;
  dragDisabled: boolean;
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: recipe.id,
    disabled: dragDisabled,
  });

  const style = { transform: CSS.Transform.toString(transform), transition };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={cn("relative", selectMode && "cursor-pointer", isDragging && "z-10 opacity-70")}
      onClick={selectMode ? onToggle : undefined}
    >
      {selectMode && (
        <div
          className={cn(
            "absolute top-2 left-2 z-10 h-5 w-5 rounded-full border-2 flex items-center justify-center shadow-sm",
            selected ? "bg-primary border-primary" : "bg-black/30 border-white/70"
          )}
        >
          {selected && <Check className="h-3 w-3 text-primary-foreground stroke-[3]" />}
        </div>
      )}
      {!selectMode && !dragDisabled && (
        <button
          type="button"
          {...attributes}
          {...listeners}
          className="absolute top-2 right-2 z-10 h-6 w-6 rounded-md bg-background/90 border shadow-sm flex items-center justify-center text-muted-foreground cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 hover:text-foreground transition-opacity"
          onClick={(e) => e.preventDefault()}
          aria-label="Drag to reorder"
        >
          <GripVertical className="h-3.5 w-3.5" />
        </button>
      )}
      <div className={cn("group", selectMode && "pointer-events-none", selectMode && selected && "rounded-xl ring-2 ring-primary")}>
        {selectMode ? (
          <RecipeGridCard recipe={recipe} />
        ) : (
          <Link href={`/recipes/${recipe.id}`}>
            <RecipeGridCard recipe={recipe} />
          </Link>
        )}
      </div>
    </div>
  );
}

export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }: { collectionId: string; recipes: GridCardRecipe[] }) {
  const t = useTranslations("collections");
  const tCommon = useTranslations("common");
  const [recipes, setRecipes] = useState(initialRecipes);
  const [selectMode, setSelectMode] = useState(false);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [moveOpen, setMoveOpen] = useState(false);
  const [removeConfirmOpen, setRemoveConfirmOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [search, setSearch] = useState("");

  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));

  const toggleSelect = useCallback((id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }, []);

  const exitSelect = () => {
    setSelectMode(false);
    setSelected(new Set());
  };

  async function removeFromCollection() {
    setBusy(true);
    try {
      const res = await fetch(`/api/v1/collections/${collectionId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ removeRecipeIds: [...selected] }),
      });
      if (!res.ok) throw new Error();
      setRecipes((prev) => prev.filter((r) => !selected.has(r.id)));
      toast.success(t("removedFromCollection", { count: selected.size }));
      exitSelect();
    } catch {
      toast.error(t("removeFromCollectionFailed"));
    } finally {
      setBusy(false);
    }
  }

  async function persistOrder(ordered: GridCardRecipe[]) {
    try {
      const res = await fetch(`/api/v1/collections/${collectionId}/reorder`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ recipeIds: ordered.map((r) => r.id) }),
      });
      if (!res.ok) throw new Error();
    } catch {
      toast.error(t("reorderFailed"));
    }
  }

  function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    const oldIndex = recipes.findIndex((r) => r.id === active.id);
    const newIndex = recipes.findIndex((r) => r.id === over.id);
    if (oldIndex === -1 || newIndex === -1) return;
    const reordered = arrayMove(recipes, oldIndex, newIndex);
    setRecipes(reordered);
    void persistOrder(reordered);
  }

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return recipes;
    return recipes.filter((r) => r.title.toLowerCase().includes(q));
  }, [recipes, search]);

  const searchActive = search.trim().length > 0;

  if (recipes.length === 0) return null;

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
          <Input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder={t("searchRecipesPlaceholder")}
            className="pl-9"
          />
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={selectMode ? exitSelect : () => setSelectMode(true)}
          className={cn("gap-1.5 shrink-0", selectMode && "text-muted-foreground")}
        >
          {selectMode ? (
            <><X className="h-4 w-4" />{tCommon("cancel")}</>
          ) : (
            <><ListChecks className="h-4 w-4" />{t("selectRecipes")}</>
          )}
        </Button>
      </div>

      {filtered.length === 0 ? (
        <p className="text-sm text-muted-foreground py-8 text-center">{t("noRecipeSearchResults")}</p>
      ) : (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={filtered.map((r) => r.id)} strategy={verticalListSortingStrategy}>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
              {filtered.map((recipe) => (
                <SortableRecipeCard
                  key={recipe.id}
                  recipe={recipe}
                  selectMode={selectMode}
                  selected={selected.has(recipe.id)}
                  onToggle={() => toggleSelect(recipe.id)}
                  dragDisabled={selectMode || searchActive}
                />
              ))}
            </div>
          </SortableContext>
        </DndContext>
      )}

      {selectMode && selected.size > 0 && (
        <div className="fixed bottom-4 sm:bottom-8 left-1/2 -translate-x-1/2 z-50 w-[calc(100vw-2rem)] sm:w-auto sm:max-w-none animate-in slide-in-from-bottom-4 duration-200">
          <div className="flex items-center gap-1 sm:gap-2 bg-popover border shadow-2xl rounded-2xl px-2 sm:px-5 py-2 sm:py-3 overflow-x-auto sm:overflow-visible [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
            <span className="text-sm font-semibold tabular-nums mr-1 shrink-0">{selected.size}</span>
            <div className="w-px h-5 bg-border mx-1 shrink-0" />
            <Button variant="ghost" size="sm" onClick={() => setMoveOpen(true)} disabled={busy} className={buttonVariants({ variant: "ghost", size: "sm" }) + " gap-1.5 shrink-0"} aria-label={t("moveToCollection")}>
              <FolderInput className="h-4 w-4" />
              <span className="hidden sm:inline">{t("moveToCollection")}</span>
            </Button>
            <Button variant="destructive" size="sm" onClick={() => setRemoveConfirmOpen(true)} disabled={busy} className="gap-1.5 shrink-0" aria-label={t("removeFromCollection")}>
              <FolderMinus className="h-4 w-4" />
              <span className="hidden sm:inline">{t("removeFromCollection")}</span>
            </Button>
          </div>
        </div>
      )}

      <AddToCollectionDialog
        open={moveOpen}
        onOpenChange={setMoveOpen}
        recipeIds={[...selected]}
        sourceCollectionId={collectionId}
        onDone={() => {
          setRecipes((prev) => prev.filter((r) => !selected.has(r.id)));
          exitSelect();
        }}
      />

      <AlertDialog open={removeConfirmOpen} onOpenChange={setRemoveConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("removeFromCollectionConfirmTitle", { count: selected.size })}</AlertDialogTitle>
            <AlertDialogDescription>{t("removeFromCollectionConfirmDescription")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{tCommon("cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => { setRemoveConfirmOpen(false); void removeFromCollection(); }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {t("removeFromCollection")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
