"use client";

import React, { createContext, useContext, useState, useCallback, useEffect } from "react";
import { usePathname } from "next/navigation";
import { ToastInput, ToastNotice, useToasts } from "./ToastStack";

export interface DashboardShellContextValue {
  isMobileDrawerOpen: boolean;
  setIsMobileDrawerOpen: (open: boolean) => void;
  toggleMobileDrawer: () => void;
  closeMobileDrawer: () => void;
  openMobileDrawer: () => void;
  isPaywallOpen: boolean;
  openPaywall: () => void;
  closePaywall: () => void;
  toasts: ToastNotice[];
  pushToast: (notice: ToastInput) => string;
  dismissToast: (id: string) => void;
}

const DashboardShellContext = createContext<DashboardShellContextValue | null>(null);

export function DashboardShellProvider({ children }: { children: React.ReactNode }) {
  const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false);
  const [isPaywallOpen, setIsPaywallOpen] = useState(false);
  const { toasts, push: pushToast, dismiss: dismissToast } = useToasts();
  const pathname = usePathname();

  const openPaywall = useCallback(() => setIsPaywallOpen(true), []);
  const closePaywall = useCallback(() => setIsPaywallOpen(false), []);

  const toggleMobileDrawer = useCallback(() => {
    setIsMobileDrawerOpen((prev) => !prev);
  }, []);

  const closeMobileDrawer = useCallback(() => {
    setIsMobileDrawerOpen(false);
  }, []);

  const openMobileDrawer = useCallback(() => {
    setIsMobileDrawerOpen(true);
  }, []);

  // Close drawer automatically on route navigation
  useEffect(() => {
    setIsMobileDrawerOpen(false);
  }, [pathname]);

  // Handle ESC key to dismiss mobile drawer
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isMobileDrawerOpen) {
        setIsMobileDrawerOpen(false);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isMobileDrawerOpen]);

  // Lock body scroll when mobile drawer is open to prevent background scrolling
  useEffect(() => {
    if (typeof document !== "undefined") {
      if (isMobileDrawerOpen) {
        document.body.style.overflow = "hidden";
      } else {
        document.body.style.overflow = "";
      }
    }
    return () => {
      if (typeof document !== "undefined") {
        document.body.style.overflow = "";
      }
    };
  }, [isMobileDrawerOpen]);

  return (
    <DashboardShellContext.Provider
      value={{
        isMobileDrawerOpen,
        setIsMobileDrawerOpen,
        toggleMobileDrawer,
        closeMobileDrawer,
        openMobileDrawer,
        isPaywallOpen,
        openPaywall,
        closePaywall,
        toasts,
        pushToast,
        dismissToast,
      }}
    >
      {children}
    </DashboardShellContext.Provider>
  );
}

export function useDashboardShell(): DashboardShellContextValue {
  const context = useContext(DashboardShellContext);
  if (!context) {
    // Return a safe fallback if used outside provider (e.g. in isolation or tests)
    return {
      isMobileDrawerOpen: false,
      setIsMobileDrawerOpen: () => {},
      toggleMobileDrawer: () => {},
      closeMobileDrawer: () => {},
      openMobileDrawer: () => {},
      isPaywallOpen: false,
      openPaywall: () => {},
      closePaywall: () => {},
      toasts: [],
      pushToast: () => "",
      dismissToast: () => {},
    };
  }
  return context;
}
