"use client";

import { useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { ListChecks, X, FolderInput, FolderMinus, Check } from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";
import { RecipeCard } from "@/components/recipe/recipe-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";

type Recipe = {
  id: string;
  title: string;
  description: string | null;
  baseServings: number;
  prepMins: number | null;
  cookMins: number | null;
  difficulty: "easy" | "medium" | "hard" | null;
  visibility: "private" | "unlisted" | "public" | "followers";
  updatedAt: Date;
  photos?: Array<{ storageKey: string; isCover: boolean }>;
  sourceUrl?: string | null;
};

export function CollectionRecipesGrid({ collectionId, recipes: initialRecipes }: { collectionId: string; recipes: Recipe[] }) {
  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 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);
    }
  }

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

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-end">
        <Button
          variant="ghost"
          size="sm"
          onClick={selectMode ? exitSelect : () => setSelectMode(true)}
          className={cn("gap-1.5", selectMode && "text-muted-foreground")}
        >
          {selectMode ? (
            <><X className="h-4 w-4" />{tCommon("cancel")}</>
          ) : (
            <><ListChecks className="h-4 w-4" />{t("selectRecipes")}</>
          )}
        </Button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {recipes.map((recipe) => (
          <div key={recipe.id} className={cn("relative", selectMode && "cursor-pointer")} onClick={selectMode ? () => toggleSelect(recipe.id) : 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.has(recipe.id) ? "bg-primary border-primary" : "bg-black/30 border-white/70"
                )}
              >
                {selected.has(recipe.id) && <Check className="h-3 w-3 text-primary-foreground stroke-[3]" />}
              </div>
            )}
            <div className={cn(selectMode && "pointer-events-none", selectMode && selected.has(recipe.id) && "rounded-xl ring-2 ring-primary")}>
              <RecipeCard recipe={recipe} />
            </div>
          </div>
        ))}
      </div>

      {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>
  );
}
