"use client";

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

import { SceneBrowserModal } from "@/components/studio/SceneBrowserModal";
import { SceneThumbnailBlock } from "@/components/studio/timeline/SceneThumbnailBlock";
import { TimelinePlayhead } from "@/components/studio/timeline/TimelinePlayhead";
import { TimeRuler } from "@/components/studio/timeline/TimeRuler";
import {
  getProjectDuration,
  getSceneTimelineSegments,
  STRIP_PX_PER_SECOND,
} from "@/lib/studio-timeline";
import { useStudioStore } from "@/lib/studio-store";

interface SceneThumbnailStripProps {
  onSceneSelect?: () => void;
}

export function SceneThumbnailStrip({ onSceneSelect }: SceneThumbnailStripProps) {
  const t = useTranslations("auto.componentsStudioTimelineSceneThumbnailStrip");
  const scrollRef = useRef<HTMLDivElement>(null);
  const [browserOpen, setBrowserOpen] = useState(false);

  const scenes = useStudioStore((state) => state.scenes);
  const activeSceneId = useStudioStore((state) => state.activeSceneId);
  const currentTime = useStudioStore((state) => state.currentTime);
  const addScene = useStudioStore((state) => state.addScene);
  const addSceneFromTemplate = useStudioStore((state) => state.addSceneFromTemplate);
  const setActiveScene = useStudioStore((state) => state.setActiveScene);
  const setCurrentTime = useStudioStore((state) => state.setCurrentTime);
  const updateScene = useStudioStore((state) => state.updateScene);
  const duplicateScene = useStudioStore((state) => state.duplicateScene);
  const deleteScene = useStudioStore((state) => state.deleteScene);

  const segments = useMemo(() => getSceneTimelineSegments(scenes), [scenes]);
  const totalDuration = useMemo(() => getProjectDuration(scenes), [scenes]);

  const stripWidth = Math.max(
    totalDuration * STRIP_PX_PER_SECOND + 160,
    STRIP_PX_PER_SECOND * 5 + 160
  );
  const canDelete = scenes.length > 1;

  return (
    <>
      <div className="relative shrink-0 bg-gray-50" style={{ height: 136 }}>
        <div
          ref={scrollRef}
          className="h-full overflow-x-auto overflow-y-hidden"
          style={{ scrollbarWidth: "thin", scrollbarColor: "#d1d5db transparent" }}
        >
          <div className="flex flex-col" style={{ minWidth: stripWidth }}>
            {/* Time ruler */}
            <TimeRuler
              totalDuration={totalDuration}
              pxPerSecond={STRIP_PX_PER_SECOND}
              currentTime={currentTime}
              onSeek={setCurrentTime}
            />

            {/* Scene blocks */}
            <div className="relative flex items-end gap-1.5 px-2 pb-1 pt-1">
              {segments.map(({ scene, index }) => (
                <SceneThumbnailBlock
                  key={scene.id}
                  scene={scene}
                  pxPerSecond={STRIP_PX_PER_SECOND}
                  colorIndex={index}
                  isActive={scene.id === activeSceneId}
                  canDelete={canDelete}
                  onSelect={() => {
                    setActiveScene(scene.id);
                    onSceneSelect?.();
                  }}
                  onRename={(name) => updateScene(scene.id, { name })}
                  onDurationChange={(duration) => updateScene(scene.id, { duration })}
                  onDuplicate={() => duplicateScene(scene.id)}
                  onDelete={() => deleteScene(scene.id)}
                />
              ))}

              <button
                type="button"
                onClick={() => setBrowserOpen(true)}
                className="mb-5 flex h-20 w-10 shrink-0 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-400 transition-colors hover:border-blue-400 hover:bg-blue-50 hover:text-blue-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
                aria-label={t("browseScenes")}
              >
                <LayoutGrid className="h-5 w-5" aria-hidden />
              </button>

              <button
                type="button"
                onClick={() => addScene()}
                className="mb-5 flex h-20 w-10 shrink-0 items-center justify-center rounded-lg border-2 border-dashed border-gray-300 text-gray-300 transition-colors hover:border-blue-400 hover:text-blue-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
                aria-label={t("addScene")}
              >
                <Plus className="h-5 w-5" aria-hidden />
              </button>

              <TimelinePlayhead
                currentTime={currentTime}
                pxPerSecond={STRIP_PX_PER_SECOND}
              />
            </div>
          </div>
        </div>
      </div>

      <SceneBrowserModal
        open={browserOpen}
        onOpenChange={setBrowserOpen}
        onScenesAdd={(templates) => {
          templates.forEach((t) => addSceneFromTemplate(t));
        }}
      />
    </>
  );
}
