import { useState, useRef, useEffect } from "react";
import Terminal from "./components/Terminal";
import "./App.css";
import Background from "./components/Background";
import BackgroundImages from "./components/BackgroundImages";

function App() {
  // State for terminal position and size
  const [position, setPosition] = useState({ x: 100, y: 100 });
  const [size, setSize] = useState({ width: 800, height: 500 });
  const [isDragging, setIsDragging] = useState(false);
  const [isResizing, setIsResizing] = useState(false);
  const [resizeDirection, setResizeDirection] = useState("");
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
  const [startSize, setStartSize] = useState({ width: 0, height: 0 });
  const [startResizePos, setStartResizePos] = useState({ x: 0, y: 0 });
  const terminalRef = useRef(null);

  console.log("Terminal state:", {
    position,
    size,
    isResizing,
    resizeDirection,
  });

  // Start dragging the terminal window
  const handleMouseDown = (e) => {
    e.preventDefault();
    setIsDragging(true);
    setStartPos({ x: e.clientX - position.x, y: e.clientY - position.y });
  };

  // Start resizing from a specific corner
  const handleResizeMouseDown = (direction) => (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsResizing(true);
    setResizeDirection(direction);
    setStartResizePos({ x: e.clientX, y: e.clientY });
    setStartSize({ ...size });
    setStartPos({ ...position });
  };

  // Handle mouse movement for dragging and resizing
  const handleMouseMove = (e) => {
    if (isDragging) {
      const newX = e.clientX - startPos.x;
      const newY = e.clientY - startPos.y;
      setPosition({
        x: Math.max(0, Math.min(newX, window.innerWidth - size.width)),
        y: Math.max(0, Math.min(newY, window.innerHeight - size.height)),
      });
    } else if (isResizing) {
      const deltaX = e.clientX - startResizePos.x;
      const deltaY = e.clientY - startResizePos.y;
      const minWidth = 400;
      const minHeight = 300;

      let newWidth = startSize.width;
      let newHeight = startSize.height;
      let newX = position.x;
      let newY = position.y;

      switch (resizeDirection) {
        case "bottom-right":
          newWidth = Math.max(minWidth, startSize.width + deltaX);
          newHeight = Math.max(minHeight, startSize.height + deltaY);
          break;
        case "bottom-left":
          newWidth = Math.max(minWidth, startSize.width - deltaX);
          newHeight = Math.max(minHeight, startSize.height + deltaY);
          newX = startPos.x + startSize.width - newWidth;
          break;
        case "top-right":
          newWidth = Math.max(minWidth, startSize.width + deltaX);
          newHeight = Math.max(minHeight, startSize.height - deltaY);
          newY = startPos.y + startSize.height - newHeight;
          break;
        case "top-left":
          newWidth = Math.max(minWidth, startSize.width - deltaX);
          newHeight = Math.max(minHeight, startSize.height - deltaY);
          newX = startPos.x + startSize.width - newWidth;
          newY = startPos.y + startSize.height - newHeight;
          break;
      }

      setSize({ width: newWidth, height: newHeight });
      setPosition({ x: newX, y: newY });
    }
  };

  // End dragging or resizing
  const handleMouseUp = () => {
    setIsDragging(false);
    setIsResizing(false);
  };

  // Set up event listeners
  useEffect(() => {
    // Change cursor style based on action
    if (isDragging) {
      document.body.style.cursor = "move";
    } else if (isResizing) {
      switch (resizeDirection) {
        case "bottom-right":
          document.body.style.cursor = "se-resize";
          break;
        case "bottom-left":
          document.body.style.cursor = "sw-resize";
          break;
        case "top-right":
          document.body.style.cursor = "ne-resize";
          break;
        case "top-left":
          document.body.style.cursor = "nw-resize";
          break;
      }
    } else {
      document.body.style.cursor = "auto";
    }

    // Add event listeners when dragging or resizing
    if (isDragging || isResizing) {
      window.addEventListener("mousemove", handleMouseMove);
      window.addEventListener("mouseup", handleMouseUp);
    }

    // Cleanup function
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
      document.body.style.cursor = "auto";
    };
  }, [
    isDragging,
    isResizing,
    resizeDirection,
    position,
    size,
    startPos,
    startSize,
    startResizePos,
  ]);

  return (
    <div className="App min-h-screen w-full fixed inset-0 bg-indigo-950">
      {/* Background images */}
      <BackgroundImages />

      {/* Your gothic header */}
      <div className="fixed top-0 left-0 w-full text-center pt-8 z-10 gothic-text">
        <h1 className="text-6xl text-purple-300 mb-2">Npc About Me</h1>
        <h2 className="text-3xl text-purple-400">Console View</h2>
      </div>

      {/* Your terminal component */}
      <div
        ref={terminalRef}
        className="rounded-lg shadow-2xl overflow-hidden border-2 border-purple-600 select-none terminal-window transition-all duration-300"
        style={{
          position: "absolute",
          left: `${position.x}px`,
          top: `${position.y}px`,
          width: `${size.width}px`,
          height: `${size.height}px`,
          zIndex: 10,
          boxShadow:
            "0 0 15px rgba(128, 0, 255, 0.5), 0 0 30px rgba(128, 0, 255, 0.3)",
          backdropFilter: "blur(3px)",
        }}
      >
        {/* Terminal header */}
        <div
          className="bg-gradient-to-r from-gray-800 to-gray-900 px-4 py-2 flex items-center border-b border-purple-500 cursor-move"
          onMouseDown={handleMouseDown}
        >
          <div className="flex space-x-3">
            <div className="h-3 w-3 bg-red-500 rounded-full hover:bg-red-600 transition-colors"></div>
            <div className="h-3 w-3 bg-yellow-500 rounded-full hover:bg-yellow-600 transition-colors"></div>
            <div className="h-3 w-3 bg-green-500 rounded-full hover:bg-green-600 transition-colors"></div>
          </div>
          <span className="mx-auto text-gray-300 gothic-text text-xl">
            terminal@npc-about-me
          </span>
        </div>

        {/* Terminal component with better background */}
        <div className="bg-terminal-bg w-full h-[calc(100%-2.5rem)] overflow-hidden">
          <Terminal />
        </div>

        {/* Improved resize handles */}
        <div
          className="absolute bottom-0 right-0 w-8 h-8 cursor-se-resize"
          onMouseDown={handleResizeMouseDown("bottom-right")}
          style={{
            background:
              "linear-gradient(135deg, transparent 70%, rgba(168, 85, 247, 0.7) 100%)",
            opacity: 0.7,
            transition: "opacity 0.2s ease",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.opacity = "1")}
          onMouseLeave={(e) => (e.currentTarget.style.opacity = "0.7")}
        />
        <div
          className="absolute bottom-0 left-0 w-8 h-8 cursor-sw-resize"
          onMouseDown={handleResizeMouseDown("bottom-left")}
          style={{
            background:
              "linear-gradient(225deg, transparent 70%, rgba(168, 85, 247, 0.7) 100%)",
            opacity: 0.7,
            transition: "opacity 0.2s ease",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.opacity = "1")}
          onMouseLeave={(e) => (e.currentTarget.style.opacity = "0.7")}
        />
        <div
          className="absolute top-0 right-0 w-8 h-8 cursor-ne-resize"
          onMouseDown={handleResizeMouseDown("top-right")}
          style={{
            background:
              "linear-gradient(45deg, transparent 70%, rgba(168, 85, 247, 0.7) 100%)",
            opacity: 0.7,
            transition: "opacity 0.2s ease",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.opacity = "1")}
          onMouseLeave={(e) => (e.currentTarget.style.opacity = "0.7")}
        />
        <div
          className="absolute top-0 left-0 w-8 h-8 cursor-nw-resize"
          onMouseDown={handleResizeMouseDown("top-left")}
          style={{
            background:
              "linear-gradient(315deg, transparent 70%, rgba(168, 85, 247, 0.7) 100%)",
            opacity: 0.7,
            transition: "opacity 0.2s ease",
          }}
          onMouseEnter={(e) => (e.currentTarget.style.opacity = "1")}
          onMouseLeave={(e) => (e.currentTarget.style.opacity = "0.7")}
        />
      </div>
    </div>
  );
}

export default App;
