// app/DraggableWindows.tsx

'use client';

import React from 'react';
import { Rnd } from 'react-rnd';
import {
  AiOutlineClose,
  AiOutlineMinus,
  AiOutlineFullscreen,
} from 'react-icons/ai';
import { useWindowManager } from '../contexts/WindowManagerContext';
import { motion, AnimatePresence } from 'framer-motion';

const DraggableWindows: React.FC = () => {
  const {
    windows,
    windowStates,
    closeWindow,
    minimizeWindow,
    maximizeWindow,
    updateWindowState,
    bringToFront,
  } = useWindowManager();

  return (
    <div className="w-full h-full fixed top-0 left-0">
      {Object.keys(windows).map((name) => {
        const { Component } = windows[name];
        const state = windowStates[name];

        if (!Component) return null;

        const isVisible = state.visible && !state.minimized;

        return (
          <AnimatePresence key={name}>
            {isVisible && (
              <WindowWrapper
                key={name}
                name={name}
                state={state}
                bringToFront={bringToFront}
                updateWindowState={updateWindowState}
                minimizeWindow={minimizeWindow}
                maximizeWindow={maximizeWindow}
                closeWindow={closeWindow}
              >
                <Component />
              </WindowWrapper>
            )}
          </AnimatePresence>
        );
      })}
    </div>
  );
};

interface WindowState {
  visible: boolean;
  minimized: boolean;
  maximized: boolean;
  width: number;
  height: number;
  x: number;
  y: number;
  zIndex: number;
}

interface WindowWrapperProps {
  name: string;
  state: WindowState;
  bringToFront: (name: string) => void;
  updateWindowState: (name: string, newState: Partial<WindowState>) => void;
  minimizeWindow: (name: string) => void;
  maximizeWindow: (name: string) => void;
  closeWindow: (name: string) => void;
  children: React.ReactNode;
}

const WindowWrapper: React.FC<WindowWrapperProps> = ({
  name,
  state,
  bringToFront,
  updateWindowState,
  minimizeWindow,
  maximizeWindow,
  closeWindow,
  children,
}) => {
  const { windowStates } = useWindowManager();

  // Determine if the window is the topmost window
  const maxZIndex = Math.max(...Object.values(windowStates).map((w) => w.zIndex));
  const isTopWindow = state.zIndex === maxZIndex;

  // Determine box shadow based on zIndex
  const boxShadow = isTopWindow
    ? '0px 0px 10px rgba(0,0,0,0.5)'
    : '0px 0px 5px rgba(0,0,0,0.2)';

  // Use layout animations for smooth transitions
  const windowMotionProps = {
    layout: true,
    initial: { opacity: 0 },
    animate: { opacity: 1 },
    exit: { opacity: 0 },
    transition: { duration: 0.2 },
  };

  return (
    <Rnd
  size={{ width: state.width, height: state.height }}
  position={{ x: state.x, y: state.y }}
  onMouseDown={() => bringToFront(name)}
  onDragStart={() => bringToFront(name)}
  onDrag={(e, d) => {
    updateWindowState(name, { x: d.x, y: d.y }, true); // skipGrid = true
  }}
  onDragStop={(e, d) => {
    updateWindowState(name, { x: d.x, y: d.y }); // Snap to grid after drag ends
  }}
  onResize={(e, direction, ref, delta, position) => {
    const newWidth = parseInt(ref.style.width, 10);
    const newHeight = parseInt(ref.style.height, 10);
    updateWindowState(
      name,
      {
        width: newWidth,
        height: newHeight,
        x: position.x,
        y: position.y,
      },
      true // skipGrid = true
    );
  }}
  onResizeStop={(e, direction, ref, delta, position) => {
    const newWidth = parseInt(ref.style.width, 10);
    const newHeight = parseInt(ref.style.height, 10);
    updateWindowState(name, {
      width: newWidth,
      height: newHeight,
      x: position.x,
      y: position.y,
    }); // Snap to grid after resize ends
  }}
  minWidth={200}
  minHeight={100}
  grid={[25, 25]} // Snapping to 25px grid
  dragHandleClassName="window-bar" 
  disableDragging={state.maximized}
  enableResizing={!state.maximized}
  bounds="parent"
  style={{ zIndex: state.zIndex }}
>
      <motion.div
        {...windowMotionProps}
        className="bg-white border border-gray-500 flex flex-col h-full"
        style={{ boxShadow }}
        onMouseDown={() => bringToFront(name)}
      >
        {/* Window Bar */}
        <div
          className="flex items-center justify-between bg-gray-200 p-1 window-bar" // Added 'window-bar' class
          style={{ cursor: state.maximized ? 'default' : 'move' }}
        >
          <span className="pl-2">{name}</span>
          <div className="flex">
            <button
              onClick={(e) => {
                e.stopPropagation();
                minimizeWindow(name);
              }}
              className="p-1 hover:bg-gray-300"
            >
              <AiOutlineMinus />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                maximizeWindow(name);
              }}
              className="p-1 hover:bg-gray-300"
            >
              <AiOutlineFullscreen />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                closeWindow(name);
              }}
              className="p-1 hover:bg-gray-300"
            >
              <AiOutlineClose />
            </button>
          </div>
        </div>
        {/* Window Content */}
        <div className="flex-grow overflow-auto window-content">{children}</div>
      </motion.div>
    </Rnd>
  );
};

export default DraggableWindows;

TASK: To make the UI better. for the content inside the window should have spacing of 5px all around it and teh title bar should use differnet icons fron react-icons that are more modern