'use client';

import { createContext, useContext, useState, useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { SubsectionNav } from '@/components/shared/SubsectionNav';
import { CompactFooter } from '@/components/shared/CompactFooter';
import { AnimatedBackground } from '@/components/shared/AnimatedBackground';

type NavItem = {
  label: string;
  href: string;
};

type PageContextValue = {
  isOpen: boolean;
  openModal: (content: React.ReactNode) => void;
  closeModal: () => void;
};

type PageProviderProps = {
  navItems: NavItem[];
  currentPath: string;
  rightSlot?: React.ReactNode;
  children: React.ReactNode;
};

const PageContext = createContext<PageContextValue | null>(null);

export const usePageContext = () => {
  const context = useContext(PageContext);
  if (!context) {
    throw new Error('usePageContext must be used within PageProvider');
  }
  return context;
};

export const PageProvider = ({ navItems, currentPath, rightSlot, children }: PageProviderProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const [modalContent, setModalContent] = useState<React.ReactNode | null>(null);
  const pathname = usePathname();

  const openModal = (content: React.ReactNode) => {
    setIsOpen(true);
    setModalContent(content);
  };

  const closeModal = () => {
    setIsOpen(false);
    setModalContent(null);
  };

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
  }, [isOpen]);

  useEffect(() => {
    if (isOpen) {
      closeModal();
    }
  }, [pathname]);

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        closeModal();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;

    const handleTab = (e: KeyboardEvent) => {
      if (e.key !== 'Tab') return;

      const modalElement = document.querySelector('[data-modal-overlay]');
      if (!modalElement) return;

      const focusableElements = modalElement.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
      );

      if (focusableElements.length === 0) return;

      const firstElement = focusableElements[0] as HTMLElement;
      const lastElement = focusableElements[focusableElements.length - 1] as HTMLElement;

      if (e.shiftKey && document.activeElement === firstElement) {
        e.preventDefault();
        lastElement.focus();
      } else if (!e.shiftKey && document.activeElement === lastElement) {
        e.preventDefault();
        firstElement.focus();
      }
    };

    document.addEventListener('keydown', handleTab);
    return () => document.removeEventListener('keydown', handleTab);
  }, [isOpen]);

  useEffect(() => {
    if (isOpen) {
      const closeButton = document.querySelector(
        '[data-modal-overlay] button[aria-label="Close fullscreen view"]',
      ) as HTMLElement;
      if (closeButton) {
        closeButton.focus();
      }
    }
  }, [isOpen]);

  const contextValue = { isOpen, openModal, closeModal };

  return (
    <PageContext.Provider value={contextValue}>
      <div aria-hidden={isOpen}>
        <AnimatedBackground />
        <SubsectionNav items={navItems} currentPath={currentPath} rightSlot={rightSlot} />
        <div className="relative z-10">{children}</div>
      </div>

      {isOpen && (
        <div
          className="fixed inset-0 z-50 flex flex-col bg-black/90 backdrop-blur-sm transition-opacity duration-300"
          role="dialog"
          aria-modal="true"
          aria-labelledby="modal-title"
          data-modal-overlay
        >
          <h2 id="modal-title" className="sr-only">
            Fullscreen Viewer
          </h2>

          <div className="relative overflow-hidden">
            <SubsectionNav
              items={navItems}
              currentPath={currentPath}
              rightSlot={
                <div className="flex items-center gap-3 pr-6">
                  <span className="hidden sm:block text-white/70 text-sm font-medium">
                    Press ESC to close
                  </span>
                  <button
                    onClick={closeModal}
                    className="w-9 h-9 sm:w-10 sm:h-10 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-black/90"
                    aria-label="Close fullscreen view"
                  >
                    <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M6 18L18 6M6 6l12 12"
                      />
                    </svg>
                  </button>
                </div>
              }
            />
          </div>

          <main className="flex-1 min-h-0 overflow-auto" role="main" aria-label="Modal content">
            {modalContent}
          </main>

          <CompactFooter />
        </div>
      )}
    </PageContext.Provider>
  );
};
