"use client";

import { Rnd } from "react-rnd";

import { getCropAspectRatioValue } from "@/lib/image-editor-crop";
import type { CropRect, ImageCropAspectRatio } from "@/lib/image-editor-types";

interface ImageCropOverlayProps {
  cropRect: CropRect;
  scale: number;
  aspectRatio: ImageCropAspectRatio;
  onCropChange: (rect: CropRect) => void;
}

export function ImageCropOverlay({
  cropRect,
  scale,
  aspectRatio,
  onCropChange,
}: ImageCropOverlayProps) {
  const lockRatio = getCropAspectRatioValue(aspectRatio);

  return (
    <Rnd
      size={{
        width: cropRect.w * scale,
        height: cropRect.h * scale,
      }}
      position={{
        x: cropRect.x * scale,
        y: cropRect.y * scale,
      }}
      bounds="parent"
      lockAspectRatio={lockRatio}
      onDragStop={(_e, data) =>
        onCropChange({
          ...cropRect,
          x: data.x / scale,
          y: data.y / scale,
        })
      }
      onResizeStop={(_e, _dir, ref, _delta, position) =>
        onCropChange({
          x: position.x / scale,
          y: position.y / scale,
          w: ref.offsetWidth / scale,
          h: ref.offsetHeight / scale,
        })
      }
      className="border-2 border-dashed border-violet-500 bg-violet-500/10"
    />
  );
}
