/**
 * useDrawer Hook
 *
 * A composable hook for managing drawer/side panel state.
 * Supports passing data to the drawer, position configuration, and callbacks.
 *
 * @example
 * ```tsx
 * interface FilterDrawerData {
 *   initialFilters: Record<string, unknown>;
 * }
 *
 * const filterDrawer = useDrawer<FilterDrawerData>({
 *   position: 'right',
 *   onClose: () => console.log('Filters closed'),
 * });
 *
 * return (
 *   <div>
 *     <button onClick={() => filterDrawer.open({ initialFilters: { status: 'active' } })}>
 *       Open Filters
 *     </button>
 *
 *     {filterDrawer.isOpen && (
 *       <Drawer
 *         position={filterDrawer.position}
 *         onClose={filterDrawer.close}
 *       >
 *         <FilterForm initialFilters={filterDrawer.data?.initialFilters} />
 *       </Drawer>
 *     )}
 *   </div>
 * );
 * ```
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import { useState, useCallback, useRef, useEffect } from 'react';
import type {
  DrawerPosition,
  DrawerOptions,
  DrawerState,
  DrawerActions,
  UseDrawerResult,
} from '../types';

/**
 * Hook for managing drawer state.
 *
 * @param options - Drawer options
 * @returns Drawer state and actions
 */
export function useDrawer<T = undefined>(
  options: DrawerOptions<T> = {}
): UseDrawerResult<T> {
  const {
    initialOpen = false,
    initialData,
    position: initialPosition = 'right',
    onOpen,
    onClose,
  } = options;

  const [isOpen, setIsOpen] = useState(initialOpen);
  const [data, setDataState] = useState<T | undefined>(initialData);
  const [position] = useState<DrawerPosition>(initialPosition);

  // Track mounted state to avoid state updates after unmount
  const isMountedRef = useRef(true);
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Actions
  const open = useCallback(
    (newData?: T) => {
      if (!isMountedRef.current) return;
      setDataState(newData);
      setIsOpen(true);
      onOpen?.(newData);
    },
    [onOpen]
  );

  const close = useCallback(() => {
    if (!isMountedRef.current) return;
    setIsOpen(false);
    onClose?.();
  }, [onClose]);

  const toggle = useCallback(() => {
    if (!isMountedRef.current) return;
    if (isOpen) {
      close();
    } else {
      open(data);
    }
  }, [isOpen, close, open, data]);

  const setData = useCallback((newData: T) => {
    if (!isMountedRef.current) return;
    setDataState(newData);
  }, []);

  // Build state object
  const state: DrawerState<T> = {
    isOpen,
    data,
    position,
  };

  // Build actions object
  const actions: DrawerActions<T> = {
    open,
    close,
    toggle,
    setData,
  };

  return {
    ...state,
    ...actions,
  };
}

export default useDrawer;
