"use client";

import { useCallback, useRef, useState } from "react";
import { useTranslations } from "next-intl";

import {
  clampSceneDuration,
  SCENE_BLOCK_COLORS,
} from "@/lib/studio-timeline";
import type { Scene } from "@/lib/studio-types";
import { cn } from "@/lib/utils";

interface SceneBlockProps {
  scene: Scene;
  colorIndex: number;
  isActive: boolean;
  pxPerSecond: number;
  onSelect: () => void;
  onDurationChange: (duration: number) => void;
}

export function SceneBlock({
  scene,
  colorIndex,
  isActive,
  pxPerSecond,
  onSelect,
  onDurationChange,
}: SceneBlockProps) {
  const t = useTranslations("auto.componentsStudioTimelineSceneBlock");
  const [resizeDuration, setResizeDuration] = useState<number | null>(null);
  const resizeRef = useRef({
    startX: 0,
    startDuration: scene.duration,
  });

  const duration = resizeDuration ?? scene.duration;
  const width = duration * pxPerSecond;
  const colors = SCENE_BLOCK_COLORS[colorIndex % SCENE_BLOCK_COLORS.length];

  const handleResizeStart = useCallback(
    (clientX: number) => {
      resizeRef.current = {
        startX: clientX,
        startDuration: scene.duration,
      };
      setResizeDuration(scene.duration);

      const handleMove = (event: globalThis.MouseEvent) => {
        const deltaSeconds =
          (event.clientX - resizeRef.current.startX) / pxPerSecond;
        setResizeDuration(
          clampSceneDuration(resizeRef.current.startDuration + deltaSeconds)
        );
      };

      const handleUp = (event: globalThis.MouseEvent) => {
        const deltaSeconds =
          (event.clientX - resizeRef.current.startX) / pxPerSecond;
        onDurationChange(
          clampSceneDuration(resizeRef.current.startDuration + deltaSeconds)
        );
        setResizeDuration(null);
        document.removeEventListener("mousemove", handleMove);
        document.removeEventListener("mouseup", handleUp);
      };

      document.addEventListener("mousemove", handleMove);
      document.addEventListener("mouseup", handleUp);
    },
    [scene.duration, pxPerSecond, onDurationChange]
  );

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={onSelect}
      onKeyDown={(event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          onSelect();
        }
      }}
      className={cn(
        "relative flex h-10 shrink-0 cursor-pointer items-center overflow-hidden rounded-md px-2 text-left transition-colors",
        isActive ? colors.active : colors.base,
        isActive && "ring-2 ring-white ring-offset-1 ring-offset-[#111827]"
      )}
      style={{ width }}
    >
      <div className="min-w-0 flex-1">
        <p className="truncate text-[11px] font-semibold text-white">
          {scene.name}
        </p>
        <p className="text-[10px] text-white/80">{duration}s</p>
      </div>
      <div
        role="separator"
        aria-orientation="vertical"
        aria-label={t("resizeDuration", { name: scene.name })}
        onMouseDown={(event) => {
          event.stopPropagation();
          event.preventDefault();
          handleResizeStart(event.clientX);
        }}
        className="absolute right-0 top-0 z-10 h-full w-2 cursor-ew-resize bg-white/20 hover:bg-white/40"
      />
    </div>
  );
}
