import { 
  Box, 
  Flex, 
  useDisclosure, 
  useColorModeValue, 
  useColorMode,
  IconButton,
  Container,
  Skeleton,
  Text,
  HStack,
  
} from '@chakra-ui/react';
import { ReactNode, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import AdminSidebar from '../components/admin/AdminSidebar';
import AdminHeader from '../components/admin/AdminHeader';
import { FiMenu } from 'react-icons/fi';
import { MoonIcon, SunIcon } from '@chakra-ui/icons';
import { FaSearch } from 'react-icons/fa';
import AdminSearchModal from '../components/admin/AdminSearchModal';

interface AdminLayoutProps {
  children: ReactNode;
  requireAdmin?: boolean; // when false, allow any authenticated role
}

const AdminLayout = ({ children, requireAdmin = true }: AdminLayoutProps) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const { isOpen: isSearchOpen, onOpen: onSearchOpen, onClose: onSearchClose } = useDisclosure();
  const { isAuthenticated, isLoading, user } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const { colorMode, toggleColorMode } = useColorMode();
  
  // Color values - Matching admin-enhancements.css dark mode colors
  const bg = useColorModeValue('gray.50', '#0f1115');
  const contentBg = useColorModeValue('white', '#1a1d29');
  const borderColor = useColorModeValue('gray.200', 'rgba(255, 255, 255, 0.12)');
  const sidebarBg = useColorModeValue('white', '#1a1d29');

  // Redirect to login if not authenticated
  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      navigate('/login', { state: { from: location.pathname } });
    }
  }, [isAuthenticated, isLoading, navigate, location]);

  // Keyboard shortcut: Ctrl/Cmd+K opens admin search
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      const key = e.key.toLowerCase();
      if ((e.ctrlKey || e.metaKey) && key === 'k') {
        e.preventDefault();
        onSearchOpen();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onSearchOpen]);

  // Redirect non-admin users only when page requires admin
  useEffect(() => {
    if (!isLoading && isAuthenticated && requireAdmin) {
      const role = (user as any)?.role;
      if (role && role !== 'admin') {
        navigate('/403', { replace: true, state: { from: location.pathname } });
      }
    }
  }, [isLoading, isAuthenticated, user, navigate, requireAdmin]);

  if (isLoading) {
    return (
      <Flex minH="100vh" bg={bg}>
        <Skeleton width="250px" height="100vh" position="fixed" />
        <Box ml={{ base: 0, md: '250px' }} flex={1} p={6}>
          <Skeleton height="60px" mb={6} />
          <Skeleton height="400px" />
        </Box>
      </Flex>
    );
  }

  if (!isAuthenticated) {
    return null; // Will redirect in useEffect
  }

  return (
    <Box minH="100vh" bg={bg} className="admin-layout">
      <AdminSidebar 
        isOpen={isOpen} 
        onClose={onClose} 
        bg={sidebarBg}
        borderRight="1px"
        borderColor={borderColor}
      />
      <Box 
        ml={{ base: 0, md: '260px' }} 
        transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
        minH="100vh"
      >
        <AdminHeader 
          onMenuToggle={onOpen} 
          rightContent={
            <HStack spacing={3}>
              <IconButton
                aria-label="Vyhledávání v administraci"
                icon={<FaSearch />}
                onClick={onSearchOpen}
                variant="ghost"
                size="sm"
                borderRadius="full"
                _hover={{ bg: useColorModeValue('gray.100', 'gray.700'), transform: 'scale(1.05)' }}
                transition="all 0.2s"
              />
              <IconButton
                aria-label={`Switch to ${colorMode === 'light' ? 'dark' : 'light'} mode`}
                icon={colorMode === 'light' ? <MoonIcon /> : <SunIcon />}
                onClick={toggleColorMode}
                variant="ghost"
                size="sm"
                borderRadius="full"
                _hover={{ bg: useColorModeValue('gray.100', 'gray.700'), transform: 'scale(1.05)' }}
                transition="all 0.2s"
              />
            </HStack>
          }
        />
        <Box as="main" className="admin-main" p={{ base: 4, md: 8 }} pb={{ base: 8, md: 12 }}>
          {children}
        </Box>
        {/* Admin Search Modal */}
        <AdminSearchModal
          isOpen={isSearchOpen}
          onClose={onSearchClose}
          onSelectPath={(path: string) => navigate(path)}
        />
      </Box>
    </Box>
  );
};

export default AdminLayout;
