"use client";

import type React from "react";
import { useState, useRef, memo, lazy, Suspense } from "react";
import { motion } from "framer-motion";
import { X, Minus, Square } from "lucide-react";
import styles from "./Window.module.css";
import { WindowState } from "@/app/page";

// 🧠 DEBUG FLAG
const DEBUG =
  (typeof process !== "undefined" &&
    process.env.NODE_ENV !== "production") ||
  (typeof process !== "undefined" &&
    process.env.NEXT_PUBLIC_DEBUG === "true");

const dlog = (...args: any[]) => {
  if (DEBUG) console.log("[Window]", ...args);
};

// 🧩 Lazy imports for performance
const AboutContent = lazy(() => import("./windows/AboutContent"));
const ProjectsContent = lazy(() => import("./windows/ProjectsContent"));
const SkillsContent = lazy(() => import("./windows/SkillsContent"));
const ContactContent = lazy(() => import("./windows/ContactContent"));
const ResumeContent = lazy(() => import("./windows/ResumeContent"));
const BrowserContent = lazy(() => import("./windows/BrowserContent"));
const PredictiveDashboardContent = lazy(
  () => import("./windows/PredictiveDashboardContent")
);

interface WindowProps {
  app: {
    id: string;
    name: string;
    icon: string;
    type: string;
    url?: string;
    openWindow?: (app: any) => void;
  };
  onClose: () => void;
  onMinimize: () => void;
  onFocus: () => void;
  isActive: boolean;
  zIndex: number;
  initialPosition?: { x: number; y: number };
  initialSize?: { width: number; height: number };
  isMaximized?: boolean;
  setWindowState?: (id: string, newState: Partial<WindowState>) => void;
}

// 🌀 Spinner for lazy loading
const LoadingSpinner = memo(() => (
  <div className={styles.loadingSpinner}>
    <div className={styles.spinner}></div>
    <p>Loading...</p>
  </div>
));
LoadingSpinner.displayName = "LoadingSpinner";

export default function Window({
  app,
  onClose,
  onMinimize,
  onFocus,
  isActive,
  zIndex,
  initialPosition = { x: 100, y: 100 },
  initialSize = { width: 800, height: 600 },
  isMaximized: propIsMaximized = false,
  setWindowState = () => {},
}: WindowProps) {
  const [isDragging, setIsDragging] = useState(false);
  const dragRef = useRef<HTMLDivElement>(null);
  const windowRef = useRef<HTMLDivElement>(null);

  // ===========================
  // 🖱️ Dragging behavior
  // ===========================
  const handleMouseDown = (e: React.MouseEvent) => {
    if (propIsMaximized) return;
    setIsDragging(true);
    onFocus();

    const startX = e.clientX - initialPosition.x;
    const startY = e.clientY - initialPosition.y;

    const handleMouseMove = (e: MouseEvent) => {
      if (typeof window !== "undefined") {
        const newX = Math.max(
          0,
          Math.min(window.innerWidth - initialSize.width, e.clientX - startX)
        );
        const newY = Math.max(
          60,
          Math.min(window.innerHeight - initialSize.height, e.clientY - startY)
        );
        setWindowState(app.id, { position: { x: newX, y: newY } });
        if (DEBUG) dlog(`🖐️ Dragging ${app.id} → (${newX}, ${newY})`);
      }
    };

    const handleMouseUp = () => {
      setIsDragging(false);
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
      if (DEBUG) dlog(`✅ Released drag for ${app.id}`);
    };

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
  };

  // ===========================
  // 🧱 Maximize / Restore
  // ===========================
  const handleMaximize = () => {
    if (typeof window === "undefined") return;
    if (propIsMaximized) {
      dlog(`🧩 Restoring window ${app.id}`);
      setWindowState(app.id, {
        isMaximized: false,
        size: { width: 800, height: 600 },
        position: { x: 100, y: 100 },
      });
    } else {
      dlog(`🧱 Maximizing window ${app.id}`);
      setWindowState(app.id, {
        isMaximized: true,
        size: {
          width: window.innerWidth,
          height: window.innerHeight - 60,
        },
        position: { x: 0, y: 60 },
      });
    }
  };

  // ===========================
  // 🪟 Render Window Content
  // ===========================
  const renderContent = () => {
    dlog(`🎨 Rendering content for ${app.id}`);
    switch (app.id) {
      case "about":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <AboutContent />
          </Suspense>
        );
      case "projects":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <ProjectsContent />
          </Suspense>
        );
      case "skills":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <SkillsContent />
          </Suspense>
        );
      case "contact":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <ContactContent />
          </Suspense>
        );
      case "resume":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <ResumeContent />
          </Suspense>
        );
      case "predictive-dashboard":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <PredictiveDashboardContent />
          </Suspense>
        );
      case "github":
      case "linkedin":
      case "chrome":
        return (
          <Suspense fallback={<LoadingSpinner />}>
            <BrowserContent url={app.url ?? ""} />
          </Suspense>
        );
      default:
        return (
          <div className={styles.defaultContent}>
            <h2>{app.name}</h2>
            <p>This is the {app.name} application.</p>
          </div>
        );
    }
  };

  // ===========================
  // 🧩 Render JSX
  // ===========================
  return (
    <motion.div
      ref={windowRef}
      role="dialog"
      aria-label={app.name}
      className={`${styles.window} ${isActive ? styles.active : ""} ${
        propIsMaximized ? styles.maximized : ""
      }`}
      style={{
        left: initialPosition.x,
        top: initialPosition.y,
        width: initialSize.width,
        height: initialSize.height,
        zIndex,
      }}
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
      transition={{ duration: 0.15 }}
      onClick={onFocus}
    >
      {/* 🧱 Title Bar */}
      <div
        ref={dragRef}
        className={styles.titleBar}
        onMouseDown={handleMouseDown}
        onDoubleClick={handleMaximize}
      >
        <div className={styles.titleLeft}>
          <span className={styles.windowIcon}>{app.icon}</span>
          <span className={styles.windowTitle}>{app.name}</span>
        </div>

        <div className={styles.titleRight}>
          <button
            className={styles.controlButton}
            aria-label="Minimize"
            onClick={() => {
              onMinimize();
              dlog(`➖ Minimized window ${app.id}`);
            }}
            type="button"
          >
            <Minus size={14} />
          </button>
          <button
            className={styles.controlButton}
            aria-label="Maximize"
            onClick={handleMaximize}
            type="button"
          >
            <Square size={14} />
          </button>
          <button
            className={`${styles.controlButton} ${styles.closeButton}`}
            aria-label="Close"
            onClick={() => {
              onClose();
              dlog(`❌ Closed window ${app.id}`);
            }}
            type="button"
          >
            <X size={14} />
          </button>
        </div>
      </div>

      {/* 🪟 Content */}
      <div className={styles.windowContent}>{renderContent()}</div>
    </motion.div>
  );
}
