import React, {
  createContext,
  useContext,
  useState,
  ReactNode,
  useCallback,
  useEffect,
} from 'react';
import { useIsMobile } from '../components/shared/use-mobile';

const SIDEBAR_COOKIE_NAME = 'sidebar_state';
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;

interface LayoutContextType {
  sidebarExpanded: boolean;
  assistenteExpanded: boolean;
  toggleSidebar: () => void;
  toggleAssistente: () => void;
  toggleAssistenteWithTab: (tab: string) => void;
  setSidebarExpanded: (expanded: boolean) => void;
  setAssistenteExpanded: (expanded: boolean) => void;
  sidebarWidth: number;
  setSidebarWidth: (width: number) => void;
  isMobile: boolean;
}

const LayoutContext = createContext<LayoutContextType | undefined>(undefined);

/**
 * Helper to get cookie value
 */
function getCookie(name: string): string | null {
  if (typeof document === 'undefined') return null;
  const nameLenPlus = name.length + 1;
  return (
    document.cookie
      .split(';')
      .map(c => c.trim())
      .filter(cookie => {
        return cookie.substring(0, nameLenPlus) === `${name}=`;
      })
      .map(cookie => {
        return decodeURIComponent(cookie.substring(nameLenPlus));
      })[0] || null
  );
}

/**
 * Helper to set cookie
 */
function setCookie(name: string, value: string) {
  if (typeof document === 'undefined') return;
  document.cookie = `${name}=${value}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}; SameSite=Lax`;
}

export function LayoutProvider({ children }: { children: ReactNode }) {
  // Initialize from cookie if available
  const [sidebarExpanded, setSidebarExpandedState] = useState(() => {
    if (typeof document === 'undefined') return false;
    const saved = getCookie(SIDEBAR_COOKIE_NAME);
    return saved === 'true';
  });

  const [assistenteExpanded, setAssistenteExpandedState] = useState(false);
  const [sidebarWidth, setSidebarWidth] = useState(256);
  const isMobile = useIsMobile();

  // Persist sidebar state
  useEffect(() => {
    setCookie(SIDEBAR_COOKIE_NAME, sidebarExpanded.toString());
  }, [sidebarExpanded]);

  // Função para alternar a sidebar - fecha o assistente se estiver aberto
  // Nota: atalhos de teclado (Ctrl+B) são registrados via useLayoutShortcuts()
  // no componente raiz da aplicação — ver components/hooks/use-layout-shortcuts.ts
  const toggleSidebar = useCallback(() => {
    setSidebarExpandedState(prev => {
      const newState = !prev;
      if (newState && assistenteExpanded) {
        setAssistenteExpandedState(false);
      }
      return newState;
    });
  }, [assistenteExpanded]);

  // Função para alternar o assistente - fecha a sidebar se estiver aberta
  const toggleAssistente = useCallback(() => {
    setAssistenteExpandedState(prev => {
      const newState = !prev;
      if (newState && sidebarExpanded) {
        setSidebarExpandedState(false);
      }
      return newState;
    });
  }, [sidebarExpanded]);

  // Função para abrir assistente com tab específica - fecha a sidebar se estiver aberta
  const toggleAssistenteWithTab = useCallback(
    (tab: string) => {
      if (!assistenteExpanded) {
        if (sidebarExpanded) {
          setSidebarExpandedState(false);
        }
        setAssistenteExpandedState(true);
      }
    },
    [assistenteExpanded, sidebarExpanded]
  );

  return (
    <LayoutContext.Provider
      value={{
        sidebarExpanded,
        assistenteExpanded,
        toggleSidebar,
        toggleAssistente,
        toggleAssistenteWithTab,
        setSidebarExpanded: setSidebarExpandedState,
        setAssistenteExpanded: setAssistenteExpandedState,
        sidebarWidth,
        setSidebarWidth,
        isMobile,
      }}
    >
      {children}
    </LayoutContext.Provider>
  );
}

export function useLayout() {
  const context = useContext(LayoutContext);
  if (context === undefined) {
    throw new Error('useLayout must be used within a LayoutProvider');
  }
  return context;
}

export function useOptionalLayout() {
  return useContext(LayoutContext) ?? null;
}
