/**
 * Modal hook for managing modal state and behavior
 */

import { useState, useCallback, useEffect } from 'react';

interface ModalState {
  isOpen: boolean;
  data?: any;
}

interface ModalOptions {
  closeOnEscape?: boolean;
  closeOnBackdropClick?: boolean;
  preventBodyScroll?: boolean;
  autoFocus?: boolean;
}

interface ModalActions {
  openModal: (data?: any) => void;
  closeModal: () => void;
  toggleModal: () => void;
  setData: (data: any) => void;
}

const DEFAULT_OPTIONS: Required<ModalOptions> = {
  closeOnEscape: true,
  closeOnBackdropClick: true,
  preventBodyScroll: true,
  autoFocus: true,
};

export const useModal = (
  initialState: boolean = false,
  options: ModalOptions = {}
): ModalState & ModalActions => {
  const [state, setState] = useState<ModalState>({
    isOpen: initialState,
    data: undefined,
  });

  const config = { ...DEFAULT_OPTIONS, ...options };

  // Open modal
  const openModal = useCallback((data?: any) => {
    setState(prev => ({
      ...prev,
      isOpen: true,
      data,
    }));
  }, []);

  // Close modal
  const closeModal = useCallback(() => {
    setState(prev => ({
      ...prev,
      isOpen: false,
      data: undefined,
    }));
  }, []);

  // Toggle modal
  const toggleModal = useCallback(() => {
    setState(prev => ({
      ...prev,
      isOpen: !prev.isOpen,
    }));
  }, []);

  // Set modal data
  const setData = useCallback((data: any) => {
    setState(prev => ({
      ...prev,
      data,
    }));
  }, []);

  // Handle escape key
  useEffect(() => {
    const handleEscape = (event: KeyboardEvent) => {
      if (config.closeOnEscape && event.key === 'Escape' && state.isOpen) {
        closeModal();
      }
    };

    if (state.isOpen) {
      document.addEventListener('keydown', handleEscape);
    }

    return () => {
      document.removeEventListener('keydown', handleEscape);
    };
  }, [state.isOpen, config.closeOnEscape, closeModal]);

  // Handle body scroll prevention
  useEffect(() => {
    if (config.preventBodyScroll && state.isOpen) {
      const originalOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';

      return () => {
        document.body.style.overflow = originalOverflow;
      };
    }
  }, [state.isOpen, config.preventBodyScroll]);

  return {
    ...state,
    openModal,
    closeModal,
    toggleModal,
    setData,
  };
};