import { Box, Container, IconButton } from '@chakra-ui/react';
import { ReactNode, useEffect, useState } from 'react';
import { FiChevronUp } from 'react-icons/fi';
import Navbar from '../Navbar';
import Footer from './Footer';
import { useAllPageElementConfigs } from '../../hooks/usePageElementConfig';
import SpartaNavbar from '../elements/SpartaNavbar';

interface MainLayoutProps {
  children: ReactNode;
  headerInsideContainer?: boolean;
}

export const MainLayout: React.FC<MainLayoutProps> = ({ children, headerInsideContainer = false }) => {
  const [showTop, setShowTop] = useState(false);
  const { getStyles, getVariant } = useAllPageElementConfigs('homepage');
  const headerVariant = getVariant('header', 'unified');

  useEffect(() => {
    const onScroll = () => {
      try {
        setShowTop(window.scrollY > 400);
      } catch {}
    };
    window.addEventListener('scroll', onScroll, { passive: true } as any);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll as any);
  }, []);

  const scrollToTop = () => {
    try {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch {
      window.scrollTo(0, 0);
    }
  };

  return (
    <Box minH="100vh" bg="bg.app" overflowX="hidden">
      <Box id="top" position="absolute" top={0} left={0} />
      {headerInsideContainer ? (
        <>
          <Container maxW="container.xl" py={8}>
            <Box as="header" data-element="header" style={{ ...getStyles('header') }}>
              {headerVariant === 'sparta_navbar' ? (
                <SpartaNavbar />
              ) : (
                <Navbar fullWidth={headerVariant === 'fullwidth'} />
              )}
            </Box>
            {children}
          </Container>
          <Box as="footer" data-element="footer" style={{ ...getStyles('footer') }}>
            <Footer />
          </Box>
        </>
      ) : (
        <>
          <Box as="header" data-element="header" style={{ ...getStyles('header') }}>
            {headerVariant === 'sparta_navbar' ? (
              <SpartaNavbar />
            ) : (
              <Navbar fullWidth={headerVariant === 'fullwidth'} />
            )}
          </Box>
          <Container maxW="container.xl" py={8}>
            {children}
          </Container>
          <Box as="footer" data-element="footer" style={{ ...getStyles('footer') }}>
            <Footer />
          </Box>
        </>
      )}
      {showTop && (
        <IconButton
          aria-label="Zpět nahoru"
          icon={<FiChevronUp />}
          position="fixed"
          right={{ base: 4, md: 6 }}
          bottom={{ base: 4, md: 6 }}
          zIndex={1000}
          colorScheme="blue"
          onClick={scrollToTop}
          borderRadius="full"
          shadow="md"
        />
      )}
    </Box>
  );
};

export default MainLayout;
