"use client";

import { useCallback, useEffect, useRef } from "react";
import { useTranslations } from "next-intl";
import { Rnd } from "react-rnd";

import type { AspectRatioPreset, CropBox } from "@/lib/trimmer-types";
import { getAspectRatioValue } from "@/lib/trimmer-utils";
import { cn } from "@/lib/utils";

const ASPECT_OPTIONS: { id: AspectRatioPreset; labelKey: string }[] = [
  { id: "free", labelKey: "aspectFree" },
  { id: "16:9", labelKey: "aspect16x9" },
  { id: "9:16", labelKey: "aspect9x16" },
  { id: "1:1", labelKey: "aspect1x1" },
  { id: "4:3", labelKey: "aspect4x3" },
];

interface TrimmerVideoPreviewProps {
  videoUrl: string | null;
  aspectRatio: AspectRatioPreset;
  cropBox: CropBox;
  onCropChange: (crop: CropBox) => void;
  onAspectRatioChange: (preset: AspectRatioPreset) => void;
  onVideoMetadata: (duration: number, size: { width: number; height: number }) => void;
  onDisplaySize: (size: { width: number; height: number }) => void;
}

export function TrimmerVideoPreview({
  videoUrl,
  aspectRatio,
  cropBox,
  onCropChange,
  onAspectRatioChange,
  onVideoMetadata,
  onDisplaySize,
}: TrimmerVideoPreviewProps) {
  const t = useTranslations("auto.componentsTrimmerTrimmerVideoPreview");
  const videoRef = useRef<HTMLVideoElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const syncDisplaySize = useCallback(() => {
    const video = videoRef.current;
    if (!video) return;
    onDisplaySize({
      width: video.clientWidth,
      height: video.clientHeight,
    });
  }, [onDisplaySize]);

  useEffect(() => {
    if (!videoUrl) return;
    const video = videoRef.current;
    if (!video) return;

    const handleLoaded = () => {
      const w = video.clientWidth;
      const h = video.clientHeight;
      onVideoMetadata(video.duration, {
        width: video.videoWidth,
        height: video.videoHeight,
      });
      onCropChange({ x: 0, y: 0, w, h });
      onDisplaySize({ width: w, height: h });
    };

    video.addEventListener("loadedmetadata", handleLoaded);
    window.addEventListener("resize", syncDisplaySize);

    return () => {
      video.removeEventListener("loadedmetadata", handleLoaded);
      window.removeEventListener("resize", syncDisplaySize);
    };
  }, [videoUrl, onVideoMetadata, onCropChange, onDisplaySize, syncDisplaySize]);

  if (!videoUrl) return null;

  const lockRatio = getAspectRatioValue(aspectRatio);

  return (
    <section className="rounded-xl border border-gray-800 bg-gray-900 p-6 shadow-sm">
      <h2 className="mb-4 text-sm font-semibold text-white">{t("previewAndCrop")}</h2>
      <div className="mb-4 flex flex-wrap gap-2">
        {ASPECT_OPTIONS.map((option) => (
          <button
            key={option.id}
            type="button"
            onClick={() => onAspectRatioChange(option.id)}
            className={cn(
              "rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500",
              aspectRatio === option.id
                ? "border-blue-600 bg-blue-600 text-white"
                : "border-gray-700 bg-gray-800 text-gray-200 hover:border-gray-600"
            )}
          >
            {t(option.labelKey)}
          </button>
        ))}
      </div>
      <div ref={containerRef} className="relative mx-auto w-full max-w-3xl overflow-hidden rounded-lg bg-black">
        <video
          ref={videoRef}
          src={videoUrl}
          controls
          playsInline
          className="block h-auto w-full"
          onLoadedData={syncDisplaySize}
        />
        <Rnd
          size={{ width: cropBox.w, height: cropBox.h }}
          position={{ x: cropBox.x, y: cropBox.y }}
          bounds="parent"
          lockAspectRatio={lockRatio}
          onDragStop={(_event, data) => {
            onCropChange({
              ...cropBox,
              x: data.x,
              y: data.y,
            });
          }}
          onResizeStop={(_event, _dir, ref, _delta, position) => {
            onCropChange({
              x: position.x,
              y: position.y,
              w: ref.offsetWidth,
              h: ref.offsetHeight,
            });
          }}
          className="border-2 border-blue-500 bg-blue-500/20 shadow-lg"
          enableResizing={{
            top: true,
            right: true,
            bottom: true,
            left: true,
            topRight: true,
            bottomRight: true,
            bottomLeft: true,
            topLeft: true,
          }}
        />
      </div>
    </section>
  );
}
