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);

  // Parse the values and convert to numbers, using 0 as fallback
  let x1 = Number(searchParams.get("x1") || 0);
  let y1 = Number(searchParams.get("y1") || 0);
  let x2 = Number(searchParams.get("x2") || 0);
  let y2 = Number(searchParams.get("y2") || 0);

  // Use useEffect to calculate dimensions and position
  useEffect(() => {
    // Calculate width
    const width = Math.abs(x2 - x1);
    setSelectorWidth(width);
    
    // Calculate height
    const height = Math.abs(y2 - y1);
    setSelectorHeight(height);
    
    // Calculate top position (minimum of y coordinates)
    setSelectorTop(Math.min(y1, y2));
    
    // Calculate left position (minimum of x coordinates)
    setSelectorLeft(Math.min(x1, x2));
  }, [x1, x2, y1, y2]);

  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 tag="1" initialX={0} initialY={0} />
        <DragableBox tag="2" initialX={100} initialY={100} />
      </div>
    </div>
  );
}
