import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/cloudflare";
import DragableBox from "./DragableBox";
import { useEffect, useState } from "react";
import { useLoaderData, useSearchParams } from "@remix-run/react";

export const meta: MetaFunction = () => {
  return [
    { title: "Convert images for the web!" },
    { name: "image converter", content: "Image conversion service" },
  ];
};

export default function Index() {
  const [searchParams] = useSearchParams();
  const [selectorHeight, setSelectorHeight] = useState(0);
  const [selectorWidth, setSelectorWidth] = useState(0);
  const [selectorTop, setSelectorTop] = useState(0);
  const [selectorLeft, setSelectorLeft] = useState(0);
  const [firstDragable, setFirstDragable] = useState({
    x: 0,
    y: 0
  })

  const [secondDragable, setSecondDragable] = useState({
    x: 0,
    y: 0
  })

  // Use useEffect to calculate dimensions and position
  useEffect(() => {
    // Calculate width
    const width = Math.abs(secondDragable.x - firstDragable.x);
    setSelectorWidth(width);

    // Calculate height
    const height = Math.abs(secondDragable.y - firstDragable.y);
    setSelectorHeight(height);

    // Calculate top position (minimum of y coordinates)
    setSelectorTop(Math.min(firstDragable.y, secondDragable.y));

    // Calculate left position (minimum of x coordinates)
    setSelectorLeft(Math.min(firstDragable.x, secondDragable.x));
  }, [firstDragable, secondDragable]);

  return (
    <div className="flex h-screen w-screen justify-center items-center">
      <div className="relative w-1/3 h-1/3 border-black border">
        <div
          className="border border-black absolute"
          style={{
            top: `${selectorTop}px`,
            left: `${selectorLeft}px`,
            height: `${selectorHeight}px`,
            width: `${selectorWidth}px`,
          }}
        />
        <DragableBox initialX={0} initialY={0} setter={setFirstDragable} />
        <DragableBox initialX={100} initialY={100} setter={setSecondDragable} />
      </div>
    </div>
  );
}
