'use client'

import React, { createContext, useContext, useEffect, useState } from "react";

export interface FakeWindow {
  name: string;
  minimized: boolean;
  closed: boolean;
  offset: {
    x: number;
    y: number;
  }
}

interface WindowManagerContextType {
  windows: FakeWindow[];
  isLocalDataExists: boolean;
  get: (name: string) => FakeWindow | undefined;
  add: (window: FakeWindow) => void;
  updateWindow: (name: string, changes: Partial<FakeWindow>) => void;
  toggleMinimize: (name: string) => void;
  close: (name: string) => void;
  remove: (name: string) => void;
  move: (name: string, offset: { x: number; y: number }) => void;
  resetAll: () => void;
}

const WindowManagerContext = createContext<WindowManagerContextType | undefined>(undefined);

export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [windows, setWindows] = useState<FakeWindow[]>([]);
  const [isInit, setInit] = useState(false);
  const [isLocalDataExists, setExists] = useState(false);

  useEffect(() => {
    const data = localStorage.getItem("fake-windows-data");
    if (data) {
      setWindows(JSON.parse(data));
      setExists(true);
    }
    setInit(true);
  }, []);

  useEffect(() => {
    if (isInit && typeof window !== 'undefined' && windows.length > 0) {
      window.localStorage.setItem('fake-windows-data', JSON.stringify(windows));
    }
  }, [windows]);

  const get = (name: string) => windows.find(window => window.name == name);
  const add = (window: FakeWindow) => setWindows(w => [...w, window]);
  const updateWindow = (name: string, changes: Partial<FakeWindow>) =>
    setWindows(w =>
      w.map(win => win.name === name ? { ...win, ...changes } : win)
    );
  const toggleMinimize = (name: string) => 
    setWindows(w =>
      w.map(win => win.name === name ? { ...win, minimized: !win.minimized } : win)
    );
  const open = (name: string) => updateWindow(name, { closed: false });
  const close = (name: string) => updateWindow(name, { closed: true });
  const move = (name: string, offset: { x: number; y: number }) =>
    updateWindow(name, { offset });

  const remove = (name: string) => setWindows(w => w.filter(win => win.name !== name));

  const resetAll = () => setWindows(w =>
    w.map(win => ({
      name: win.name,
      closed: false,
      minimized: false,
      offset: { x: 0, y: 0 }
    }))
  );

  return (
    <WindowManagerContext.Provider value={{
      windows,
      isLocalDataExists,
      get, add, updateWindow, toggleMinimize, close, move, remove, resetAll
    }}>
      {children}
    </WindowManagerContext.Provider>
  );
};

export function useWindowManager() {
  const ctx = useContext(WindowManagerContext);
  if (!ctx) throw new Error("useWindowManager must be used within WindowManagerProvider");
  return ctx;
}