import { HStack, Image, Text, VStack } from "@chakra-ui/react";
import React, { FC, useContext } from "react";
import { RiNotificationLine } from "react-icons/ri";
import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { nav } from "../Routes/Nav";
import logo from '../assets/logo.svg';
import { AccordionItem, AccordionItemContent, AccordionItemTrigger, AccordionRoot } from "../components/ui/accordion";
import { Avatar } from "../components/ui/avatar";
import { LuLogOut } from "react-icons/lu";
import { logout } from "../Redux/Service/authSlice";
import { useDispatch } from "react-redux";
import GlobalStateContext from "../Contexts/GlobalStateContext";
import { useLogOutMutation } from "../Redux/Service/apiSlice";
import ProgressBar from "../components/ProgressBar/ProgressBar";

const DefaultLayout: FC<{ children: React.ReactNode }> = ({ children }) => {

  const dispatch = useDispatch()
  const navigate = useNavigate()
  const location = useLocation()


  const context = useContext(GlobalStateContext);
  if (!context) {
    throw new Error('App must be used within a GlobalStateProvider');
  }
  const { setIsAuthenticate, isBarLoading } = context;
  const [ logOutAdmin ] = useLogOutMutation()


  // Logout function
  const handleLogout = async () => {
    try {
      // ✅ Call mutation and wait for the response
      const res = await logOutAdmin().unwrap(); 
      console.log("Logout Success:", res);
  
      // ✅ Clear local storage & update authentication state
      dispatch(logout());
      localStorage.removeItem("token"); 
      setIsAuthenticate(false); 
      // ✅ Redirect to login page
      navigate("/login");
    } catch (error) {
      console.error("Logout Failed:", error);
    }
  };

  return (
    <VStack gap={0} w="100%" h="100vh" bg="#F2F2F2">
    <ProgressBar isLoading={isBarLoading}  />
    <HStack overflow={'hidden'} position={'relative'} bg="#F2F2F2" backgroundPosition="center" backgroundRepeat="repeat" backgroundSize="cover" gap={0} w="100%" h="calc(100% - 4px)"  p={0}>
      
      <VStack pt={0} zIndex={1} gap={0} rounded={'lg'} h="100%" w="15%" overflow={'auto'} >
        <HStack w={'100%'} p={3} h={'7%'} justifyContent={'center'}>
          <Image w={55} src={logo} />
        </HStack>
        <VStack  w={'100%'} p={2} pt={0}>
          {nav?.map(({ title, path, Icon, type, children, initPath }, index) => type === 'single' ?
            <NavLink  className="link" key={index} to={path||''} style={{ cursor: 'pointer', borderRadius: '8px', padding: '6px', width: '100%', display: 'flex', alignItems: 'center', gap: 6, border: '1px solid #ffffff', backgroundColor:'#fff', color:'#000', boxShadow:'rgba(99, 99, 99, 0.2) 0px 2px 8px 0px'}} ><Icon style={{ fontSize: '20px' }} /> <Text fontSize={'xs'} w={'100%'}>{title}</Text></NavLink> :
            <AccordionRoot border={location?.pathname.startsWith(initPath ?? path) ? "1px solid #02A0A0" : '1px' } key={index} bg={'#fff'} rounded={'lg'} collapsible>
              <AccordionItem rounded={'lg'} bg={'#fff'} boxShadow={'rgba(99, 99, 99, 0.2) 0px 2px 8px 0px'} borderBottom={'none'} p={0} key={index} value={title}>
                <AccordionItemTrigger className="Oxygen" color={'#fff'}   onClick={() => navigate(path||'')} gap={0} style={{ cursor: 'pointer', borderRadius: '8px', padding: '5px', width: '100%', display: 'flex', alignItems: 'center', border: '1px solid #ffffff', backgroundColor:'#fff',color:'#000',  fontSize: '14px',  }}> <Text fontSize={'xs'} gap={1} display={'flex'} alignItems={'center'} ><Icon style={{ fontSize: '20px' }} />{title}</Text></AccordionItemTrigger>
                {children?.map(({ title, path, Icon }, index) => <AccordionItemContent className={`linkChild Oxygen ${location?.pathname === path && 'activeChild'}`} key={index} onClick={()=>navigate(path)} style={{ marginTop: 6, cursor: 'pointer', borderRadius: '8px', padding: '6px', width: '100%', display: 'flex', alignItems: 'center', gap: 6, border: '1px solid #ffffff', backgroundColor:'#fff',color:'#919198' }} ><Icon style={{ fontSize: '20px' }} /> <Text fontSize={'xs'} w={'100%'}>{title}</Text></AccordionItemContent>)}
              </AccordionItem>
            </AccordionRoot>)}
        </VStack>
        <VStack w={'100%'} p={3} pt={0}>
        <HStack onClick={handleLogout} className="link"  style={{ cursor: 'pointer', borderRadius: '8px', padding: '6px', width: '100%', display: 'flex', alignItems: 'center', gap: 6, border: '1px solid #ffffff', backgroundColor:'#fff', color:'#000', boxShadow:'rgba(99, 99, 99, 0.2) 0px 2px 8px 0px'}} ><LuLogOut style={{ fontSize: '20px' }} /> <Text fontSize={'xs'} w={'100%'}>Logout</Text></HStack>
        </VStack>
      </VStack>
      <VStack  gap={0} h="100%" w="85%" >
     
        <HStack h={'11%'} w={'100%'} justifyContent={'flex-end'} pe={3} gap={6}>
        
          <NavLink to={'/manage-notification'}><RiNotificationLine color="#013e3e" cursor={'pointer'} style={{ fontSize: '22px' }} /></NavLink>
          <HStack cursor={'pointer'} onClick={() => navigate('/profile')} >
            <Avatar size={'sm'} src="https://i.pinimg.com/736x/d6/cd/0f/d6cd0ffd4634b0763d3958a7325ce26e.jpg" />
            <VStack color={'#013e3e'} gap={0} alignItems={'flex-start'}>
              <Text fontSize={'sm'} fontWeight={'bold'}>Ritesh Pandey</Text>
              <Text fontSize={'xs'} >ritesh.pandey@wdimails.com</Text>
            </VStack>
          </HStack>
        </HStack>
        {children}
      </VStack>
    </HStack>
    </VStack>
  );
};

export default DefaultLayout;
