'use client';

import { useCallback, useEffect, useState } from 'react';
import type { AppMeta, WindowState } from '@/types/portfolio';

type WindowStatesMap = Record<string, WindowState>;

interface UseWindowManagerOptions {
  persistKey?: string;
  isUnlocked: boolean;
}

export function useWindowManager({
  persistKey = 'portfolio-os-state',
  isUnlocked,
}: UseWindowManagerOptions) {
  const [openWindows, setOpenWindows] = useState<AppMeta[]>([]);
  const [activeWindow, setActiveWindow] = useState<string | null>(null);
  const [minimizedWindows, setMinimizedWindows] = useState<string[]>([]);
  const [windowStates, setWindowStates] = useState<WindowStatesMap>({});

  // Load from localStorage
  useEffect(() => {
    if (!isUnlocked || typeof window === 'undefined') return;
    try {
      const raw = localStorage.getItem(persistKey);
      if (raw) {
        const parsed = JSON.parse(raw);
        setOpenWindows(parsed.openWindows ?? []);
        setActiveWindow(parsed.activeWindow ?? null);
        setMinimizedWindows(parsed.minimizedWindows ?? []);
        setWindowStates(parsed.windowStates ?? {});
      }
    } catch (e) {
      console.error('[WM] Failed to load state:', e);
    }
  }, [isUnlocked, persistKey]);

  // Save to localStorage (debounced)
  useEffect(() => {
    if (!isUnlocked || typeof window === 'undefined') return;
    const t = setTimeout(() => {
      try {
        const payload = { openWindows, activeWindow, minimizedWindows, windowStates };
        localStorage.setItem(persistKey, JSON.stringify(payload));
      } catch (e) {
        console.error('[WM] Failed to save state:', e);
      }
    }, 300);
    return () => clearTimeout(t);
  }, [openWindows, activeWindow, minimizedWindows, windowStates, isUnlocked, persistKey]);

  const setWindowState = useCallback((id: string, patch: Partial<WindowState>) => {
    setWindowStates((prev) => ({
      ...prev,
      [id]: {
        ...(prev[id] ?? {
          position: { x: 100, y: 100 },
          size: { width: 800, height: 600 },
          isMaximized: false,
        }),
        ...patch,
      },
    }));
  }, []);

  const openWindow = useCallback((app: AppMeta) => {
    setMinimizedWindows((prev) => prev.filter((m) => m !== app.id));
    setOpenWindows((prev) => {
      const exists = prev.some((w) => w.id === app.id);
      if (!exists) {
        setActiveWindow(app.id);
        setWindowStates((prevStates) => ({
          ...prevStates,
          [app.id]: prevStates[app.id] ?? {
            position: {
              x: 100 + Object.keys(prevStates).length * 20,
              y: 100 + Object.keys(prevStates).length * 20,
            },
            size: { width: 800, height: 600 },
            isMaximized: false,
          },
        }));
        return [...prev, app];
      } else {
        setActiveWindow(app.id);
        return prev;
      }
    });
  }, []);

  const closeWindow = useCallback((id: string) => {
    setOpenWindows((prev) => prev.filter((w) => w.id !== id));
    setMinimizedWindows((prev) => prev.filter((m) => m !== id));
    setWindowStates((prev) => {
      const c = { ...prev };
      delete c[id];
      return c;
    });
    setActiveWindow((prev) => (prev === id ? null : prev));
  }, []);

  const minimizeWindow = useCallback((id: string) => {
    setMinimizedWindows((prev) => (prev.includes(id) ? prev : [...prev, id]));
    setActiveWindow((prev) => (prev === id ? null : prev));
  }, []);

  const focusWindow = useCallback((id: string) => {
    setMinimizedWindows((prev) => prev.filter((m) => m !== id));
    setActiveWindow(id);
  }, []);

  return {
    // state
    openWindows,
    activeWindow,
    minimizedWindows,
    windowStates,
    // actions
    openWindow,
    closeWindow,
    minimizeWindow,
    focusWindow,
    setActiveWindow,
    setWindowState,
  };
}
