import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";
import ResizeHandles from "./ResizeHandles";

export default function ImageViewerWindow() {
  const params = new URLSearchParams(window.location.search);
  const [imageUrl, setImageUrl] = useState(decodeURIComponent(params.get("imageUrl") ?? ""));
  const win = getCurrentWindow();

  useEffect(() => {
    let debounce: ReturnType<typeof setTimeout> | null = null;

    const unlistenImage = win.listen<string>("set-viewer-image", (event) => {
      setImageUrl(event.payload);
    });

    const unlistenResize = win.onResized(async () => {
      if (debounce) clearTimeout(debounce);
      debounce = setTimeout(async () => {
        const [size, factor] = await Promise.all([win.innerSize(), win.scaleFactor()]);
        await invoke("set_setting", { key: "viewer_width", value: String(Math.round(size.width / factor)) });
        await invoke("set_setting", { key: "viewer_height", value: String(Math.round(size.height / factor)) });
      }, 500);
    });

    const unlistenMove = win.onMoved(async () => {
      if (debounce) clearTimeout(debounce);
      debounce = setTimeout(async () => {
        const [pos, factor] = await Promise.all([win.outerPosition(), win.scaleFactor()]);
        await invoke("set_setting", { key: "viewer_x", value: String(Math.round(pos.x / factor)) });
        await invoke("set_setting", { key: "viewer_y", value: String(Math.round(pos.y / factor)) });
      }, 500);
    });

    return () => {
      unlistenImage.then(f => f());
      unlistenResize.then(f => f());
      unlistenMove.then(f => f());
    };
  }, []);

  return (
    <div style={{ height: "100vh", display: "flex", flexDirection: "column", background: "#0d1117", overflow: "hidden" }}>
      <ResizeHandles />
      <div
        onMouseDown={e => { if (e.button === 0) win.startDragging(); }}
        style={{
          height: "28px",
          background: "#161b22",
          borderBottom: "1px solid #2d3748",
          cursor: "grab",
          flexShrink: 0,
          display: "flex",
          alignItems: "center",
          paddingLeft: "12px",
          userSelect: "none",
        }}
      >
        <span style={{ fontSize: "11px", color: "#4a5568", pointerEvents: "none" }}>⠿ Image</span>
      </div>

      <div style={{ flex: 1, overflowY: "auto", overflowX: "hidden" }}>
        {imageUrl && (
          <img
            src={imageUrl}
            style={{ width: "100%", display: "block" }}
            draggable={false}
          />
        )}
      </div>
    </div>
  );
}
