
import React, { ReactNode, useEffect, useState } from 'react';
import Sidebar from '@/components/layout/Sidebar';
import Topbar from '@/components/layout/Topbar';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { getClients } from '@/store/features/client/thunk';
import { getArticles } from '@/store/features/article/thunk';
import { getDevisList } from '@/store/features/devis/thunk';
import { getCommandes } from '@/store/features/commande/thunk';
import LoadingPage from '../loading';
import { clientStatus } from '@/store/features/client/selectors';
import { articleStatus } from '@/store/features/article/selectors';
import { devisStatus } from '@/store/features/devis/selectors';
import { commandeStatus } from '@/store/features/commande/selectors';
import GlobalMessageBanner from './GlobalMessageBanner';
import { GlobalMessageProvider, useGlobalMessage } from '@/contexts/GlobalMessageContext';
import SystemStatusDrawer from '../system/SystemStatusDrawer';
import { CompanyProvider } from '@/context/CompanyContext';
import PriorityBanner from '../PriorityBanner';
import SecondaryBanner from '../SecondaryBanner';
import { BannerProvider } from '@/context/BannerContext';
import { ModuleProvider } from '@/context/ModuleContext';
import PremiumHeader from '../PremiumHeader';
import { DisplayModeProvider } from '@/context/DisplayModeContext';
import { getUniversigns } from '@/store/features/universign/thunk';
import { universignStatus } from '@/store/features/universign/selectors';
import { useNavigate } from 'react-router-dom';
import { authMe } from '@/store/features/user/thunk';
import { getGateways, getSociete } from '@/store/features/gateways/thunk';
import { getFactures } from '@/store/features/factures/thunk';
import { getCommercials } from '@/store/features/commercial/thunk';
import { getAvoirs } from '@/store/features/avoir/thunk';




const AppContent = ({ children, onMenuClick, isSidebarOpen, onCloseSidebar }) => {
  const { showMessage } = useGlobalMessage();

  // Show the requested banner on mount
  useEffect(() => {
    showMessage("Nouvelle version disponible : Découvrez la gestion de stock avancée et les nouvelles fonctionnalités.", {
      type: 'success', // This ensures green color (#338660)
      dismissible: true,
      actionLabel: "Voir les nouveautés",
      onAction: () => console.log('Changelog opened')
    });
  }, [showMessage]);

  return (
    <div className="lg:pl-64 flex flex-col min-h-screen transition-all duration-300">
      {/* <Topbar onMenuClick={onMenuClick} /> */}
      {/* <GlobalMessageBanner /> */}

      {/* Banners Layer - Stacked */}
      <div className="flex flex-col z-30 relative">
        <PriorityBanner />
        <SecondaryBanner />
      </div>

       <PremiumHeader 
          onMenuClick={onMenuClick}
          onAnnouncementsClick={() => setIsAnnouncementsOpen(true)}
        />

      
      <main className="flex-1 overflow-x-hidden p-6">
        <div className="max-w-[1600px] mx-auto animate-in fade-in duration-500">
          {children}
        </div>
      </main>
    </div>
  );
};


const AppLayout = ({ children }) => {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [isSystemStatusOpen, setIsSystemStatusOpen] = useState(false);

  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const [isLoading, setIsLoading] = useState(false);

  const [value, setValue] = useState(0)
  const [text, setText] = useState("Chargement")

  const statusClients = useAppSelector(clientStatus) ;
  const statusArticle = useAppSelector(articleStatus) ;
  const statusDevis = useAppSelector(devisStatus) ;
  const statusCommandes = useAppSelector(commandeStatus) ;
  
  const toggleSidebar = () => setSidebarOpen(!sidebarOpen);
  // console.log("statusClients : ",statusClients);
  // console.log("statusArticle : ",statusArticle);
  // console.log("statusDevis : ",statusDevis);
  // console.log("statusCommandes : ",statusCommandes);
  
  const statusUniversign = useAppSelector(universignStatus) ;

  useEffect(() => {
    const checkAuth = async () => {
        try {
          await dispatch(authMe()).unwrap();
        } catch (error) {
          navigate("/login");
        }
    };

    checkAuth();
  }, [dispatch, navigate]);

  useEffect(() => {
    const loadUniversigns = async () => {
        try {
          await dispatch(getUniversigns()).unwrap();
        } catch (error) {
          console.error("Erreur lors du chargement:", error);
        }
    };

    if (statusUniversign === "idle") {
        loadUniversigns();
    }

    const interval = setInterval(() => {
        loadUniversigns();
    }, 5000);

    return () => clearInterval(interval);
  }, [dispatch, statusUniversign]);


  // ✅ Charger les données au montage
  useEffect(() => {
    const load = async () => {
      await dispatch(getClients()).unwrap();
      // await dispatch(getGateways()).unwrap();
      await dispatch(getSociete()).unwrap();
      await dispatch(getDevisList()).unwrap();
      await dispatch(getArticles()).unwrap();
      await dispatch(getFactures()).unwrap();
      await dispatch(getCommercials()).unwrap();
      await dispatch(getCommandes()).unwrap();
      await dispatch(getAvoirs()).unwrap();
    };
    load();
  }, [dispatch]);
  


  
  if (isLoading) return <LoadingPage text={text} value={value}></LoadingPage>
  

  return (
    <GlobalMessageProvider>
      <ModuleProvider>
        <DisplayModeProvider>
          <CompanyProvider>
            <BannerProvider>
              <div className="min-h-screen bg-[#F3F4F6] dark:bg-[#050505] font-sans text-slate-900 dark:text-slate-50">
                <Sidebar 
                  isOpen={sidebarOpen} 
                  onClose={() => setSidebarOpen(false)} 
                  onSystemStatusClick={() => setIsSystemStatusOpen(true)}
                />
                
                <AppContent 
                  children={children} 
                  onMenuClick={toggleSidebar} 
                  isSidebarOpen={sidebarOpen}
                  onCloseSidebar={() => setSidebarOpen(false)}
                />

                <SystemStatusDrawer 
                  isOpen={isSystemStatusOpen} 
                  onClose={() => setIsSystemStatusOpen(false)} 
                />

              </div>
            </BannerProvider>
          </CompanyProvider>
        </DisplayModeProvider>
      </ModuleProvider>
    </GlobalMessageProvider>
  );
};

export default AppLayout;
