"use client";

import { useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { LayoutGrid, Search, X } from "lucide-react";

import { SceneBrowserCard } from "@/components/studio/SceneBrowserCard";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  BROWSER_SCENES,
  filterBrowserScenes,
  SCENE_BROWSER_CATEGORIES,
  type BrowserSceneItem,
  type SceneBrowserCategoryId,
  type SceneBrowserMediaFilter,
} from "@/lib/scene-browser-data";
import { cn } from "@/lib/utils";

export interface SceneBrowserModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Called with ALL selected scenes when user clicks "Add to Video" */
  onScenesAdd: (scenes: BrowserSceneItem[]) => void;
}

export function SceneBrowserModal({
  open,
  onOpenChange,
  onScenesAdd,
}: SceneBrowserModalProps) {
  const t = useTranslations("auto.componentsStudioSceneBrowserModal");
  const [categoryId, setCategoryId] = useState<SceneBrowserCategoryId>("all");
  const [mediaFilter, setMediaFilter] = useState<SceneBrowserMediaFilter>("all");
  const [search, setSearch] = useState("");
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  const filteredScenes = useMemo(
    () =>
      filterBrowserScenes(BROWSER_SCENES, { categoryId, mediaFilter, search }),
    [categoryId, mediaFilter, search]
  );

  const toggleScene = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const deselectAll = () => setSelectedIds(new Set());

  const handleAdd = () => {
    const selected = BROWSER_SCENES.filter((s) => selectedIds.has(s.id));
    if (selected.length === 0) return;
    onScenesAdd(selected);
    // Reset state
    setSelectedIds(new Set());
    setSearch("");
    setCategoryId("all");
    setMediaFilter("all");
    onOpenChange(false);
  };

  const handleClose = () => {
    setSelectedIds(new Set());
    setSearch("");
    onOpenChange(false);
  };

  const selectedCount = selectedIds.size;

  return (
    <Dialog open={open} onOpenChange={(v) => { if (!v) handleClose(); }}>
      <DialogContent
        className={cn(
          "flex h-[88vh] max-h-[88vh] w-[calc(100%-2rem)] max-w-5xl flex-col gap-0 overflow-hidden",
          "border-gray-200 bg-white p-0 text-gray-900",
          "[&>button]:hidden" // hide default close — we have our own
        )}
      >
        {/* Header */}
        <DialogHeader className="shrink-0 border-b border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between gap-4">
            <DialogTitle className="font-heading text-lg font-semibold text-gray-900">
              {t("title")}
            </DialogTitle>
            <button
              type="button"
              onClick={handleClose}
              className="flex h-8 w-8 items-center justify-center rounded-lg text-gray-400 hover:bg-gray-100 hover:text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
              aria-label={t("closeAriaLabel")}
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          {/* Media tabs + search on same row */}
          <div className="mt-3 flex flex-wrap items-center justify-between gap-3">
            <Tabs
              value={mediaFilter}
              onValueChange={(v) => setMediaFilter(v as SceneBrowserMediaFilter)}
            >
              <TabsList className="bg-gray-100">
                <TabsTrigger value="all">{t("filterAll")}</TabsTrigger>
                <TabsTrigger value="video">{t("filterVideo")}</TabsTrigger>
                <TabsTrigger value="photo">{t("filterPhoto")}</TabsTrigger>
              </TabsList>
            </Tabs>

            <div className="relative w-full max-w-52">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" aria-hidden />
              <input
                type="search"
                placeholder={t("searchPlaceholder")}
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="h-9 w-full rounded-lg border border-gray-200 bg-white pl-9 pr-3 text-sm placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
              />
            </div>
          </div>
        </DialogHeader>

        {/* Body: sidebar + grid */}
        <div className="flex min-h-0 flex-1 overflow-hidden">
          {/* Category sidebar */}
          <aside className="w-[220px] shrink-0 overflow-y-auto border-r border-gray-200 bg-gray-50 p-3">
            <ul className="space-y-0.5">
              {SCENE_BROWSER_CATEGORIES.map((cat) => (
                <li key={cat.id}>
                  <button
                    type="button"
                    onClick={() => setCategoryId(cat.id)}
                    className={cn(
                      "w-full cursor-pointer rounded-lg px-4 py-2 text-left text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600",
                      categoryId === cat.id
                        ? "bg-blue-50 font-semibold text-blue-600"
                        : "text-gray-700 hover:bg-gray-100"
                    )}
                  >
                    {cat.label}
                  </button>
                </li>
              ))}
            </ul>
          </aside>

          {/* Scene grid */}
          <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
            <div className="min-h-0 flex-1 overflow-y-auto p-4">
              {filteredScenes.length === 0 ? (
                <div className="flex flex-col items-center gap-3 py-16 text-center text-sm text-gray-500">
                  <LayoutGrid className="h-10 w-10 text-gray-300" aria-hidden />
                  {t("emptyState")}
                </div>
              ) : (
                <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
                  {filteredScenes.map((scene) => (
                    <SceneBrowserCard
                      key={scene.id}
                      scene={scene}
                      isSelected={selectedIds.has(scene.id)}
                      onToggle={() => toggleScene(scene.id)}
                    />
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Footer — sticky "Add to Video" bar */}
        <div className="flex shrink-0 items-center justify-between gap-4 border-t border-gray-200 bg-white px-6 py-3">
          <div className="flex items-center gap-3">
            {selectedCount > 0 && (
              <span className="text-sm text-gray-600">
                <span className="font-semibold text-gray-900">{selectedCount}</span>{" "}
                {t("selectedSuffix", { count: selectedCount })}
              </span>
            )}
            {selectedCount > 0 && (
              <button
                type="button"
                onClick={deselectAll}
                className="text-sm text-gray-500 underline hover:text-gray-700 focus-visible:outline-none"
              >
                {t("deselectAll")}
              </button>
            )}
          </div>

          <div className="flex items-center gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={handleClose}
              className="border-gray-300 text-gray-700 hover:bg-gray-50"
            >
              {t("cancel")}
            </Button>
            <Button
              type="button"
              disabled={selectedCount === 0}
              onClick={handleAdd}
              className="min-w-[140px] bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
            >
              {selectedCount === 0
                ? t("addToVideo")
                : t("addToVideoCount", { count: selectedCount })}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
