'use client';

import { useCallback } from 'react';

import { useLocalStorage } from '@djangocfg/ui-core/hooks';

import type { ChatDockMode, ChatDockSide } from '../launcher/ChatDock';

export interface ChatDockPrefs {
  /** Popover (FAB-style) or side-docked panel. */
  mode: ChatDockMode;
  /** Which edge the side dock attaches to. */
  side: ChatDockSide;
  /** Width in px when side-docked (resizable in the future). */
  sideWidth: number;
}

export const DEFAULT_DOCK_PREFS: ChatDockPrefs = {
  mode: 'popover',
  side: 'right',
  sideWidth: 420,
};

const DEFAULT_KEY = 'chat.dock.prefs';

export interface UseChatDockPrefsOptions {
  /** localStorage key. @default 'chat.dock.prefs' */
  storageKey?: string;
  /** Override the baseline defaults (per-product branding, etc.). */
  defaults?: Partial<ChatDockPrefs>;
}

export interface UseChatDockPrefsReturn extends ChatDockPrefs {
  /** Merge-update — pass only the fields that changed. */
  setPrefs: (patch: Partial<ChatDockPrefs>) => void;
  /** Convenience toggle: popover ⇆ side. */
  toggleMode: () => void;
  /** Convenience toggle: right ⇆ left (only affects side mode). */
  toggleSide: () => void;
  /** Reset to defaults. */
  reset: () => void;
}

/**
 * Persistent dock preferences (mode / side / width) via ui-core localStorage.
 *
 * SSR-safe: returns defaults on the server, hydrates on mount.
 * Survives reloads — power users keep their preferred chat layout.
 */
export function useChatDockPrefs(opts: UseChatDockPrefsOptions = {}): UseChatDockPrefsReturn {
  const key = opts.storageKey ?? DEFAULT_KEY;
  const initial: ChatDockPrefs = { ...DEFAULT_DOCK_PREFS, ...opts.defaults };

  const [prefs, setStored] = useLocalStorage<ChatDockPrefs>(key, initial);

  const setPrefs = useCallback(
    (patch: Partial<ChatDockPrefs>) => {
      setStored((prev) => ({ ...prev, ...patch }));
    },
    [setStored],
  );

  const toggleMode = useCallback(() => {
    setStored((prev) => ({ ...prev, mode: prev.mode === 'side' ? 'popover' : 'side' }));
  }, [setStored]);

  const toggleSide = useCallback(() => {
    setStored((prev) => ({ ...prev, side: prev.side === 'right' ? 'left' : 'right' }));
  }, [setStored]);

  const reset = useCallback(() => setStored(initial), [setStored, initial]);

  return { ...prefs, setPrefs, toggleMode, toggleSide, reset };
}
