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
        style={{
          height: "28px",
          background: "#161b22",
          borderBottom: "1px solid #2d3748",
          flexShrink: 0,
          display: "flex",
          alignItems: "center",
          userSelect: "none",
        }}
      >
        {/* Zone draggable */}
        <div
          onMouseDown={e => { if (e.button === 0) win.startDragging(); }}
          style={{ flex: 1, display: "flex", alignItems: "center", paddingLeft: "12px", cursor: "grab", height: "100%" }}
        >
          <span style={{ fontSize: "11px", color: "#4a5568", pointerEvents: "none" }}>⠿ Image</span>
        </div>

        {/* Boutons — hors de la zone draggable */}
        <div style={{ display: "flex", alignItems: "center", gap: "2px", paddingRight: "6px" }}>
          <ViewerTitleButton onClick={() => win.minimize()} title="Réduire">—</ViewerTitleButton>
          <ViewerTitleButton onClick={() => win.close()} title="Fermer" danger>✕</ViewerTitleButton>
        </div>
      </div>

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

function ViewerTitleButton({
  children, onClick, title, danger,
}: {
  children: React.ReactNode;
  onClick: () => void;
  title?: string;
  danger?: boolean;
}) {
  return (
    <button
      onClick={onClick}
      title={title}
      style={{
        background: "transparent",
        border: "1px solid transparent",
        color: danger ? "#f87171" : "#94a3b8",
        padding: "3px 8px",
        borderRadius: "5px",
        cursor: "pointer",
        fontSize: "12px",
        fontWeight: 500,
        transition: "all 0.15s",
        display: "flex",
        alignItems: "center",
      }}
      onMouseEnter={e => {
        const el = e.currentTarget;
        el.style.background = danger ? "rgba(248,113,113,0.1)" : "rgba(255,255,255,0.05)";
        el.style.color = danger ? "#f87171" : "#e2e8f0";
      }}
      onMouseLeave={e => {
        const el = e.currentTarget;
        el.style.background = "transparent";
        el.style.color = danger ? "#f87171" : "#94a3b8";
      }}
    >
      {children}
    </button>
  );
}
