import { useEffect, useState } from 'react';
import Typography from '@mui/material/Typography';
import { alpha, useTheme } from '@mui/material/styles';
import Stack, { StackProps } from '@mui/material/Stack';
import Button from '@mui/material/Button';
import { useRouter } from 'next/navigation';
import { paths } from '@/routes/paths';
import Iconify from '@/shared/components/iconify';

import { bgGradient } from '@/shared/theme/css';

// ----------------------------------------------------------------------

type Props = StackProps & {
  title?: string;
  description?: string;
  img?: React.ReactNode;
  action?: React.ReactNode;
  requiresAuth?: boolean;
  adminOnly?: boolean;
};

export default function AppWelcome({ 
  title, 
  description, 
  action, 
  img, 
  requiresAuth = false, 
  adminOnly = false,
  ...other 
}: Props) {
  const theme = useTheme();
  const router = useRouter();
  
  const [hasAccess, setHasAccess] = useState(true);
  const [isAdminOrManager, setIsAdminOrManager] = useState(false);
  
  useEffect(() => {
    const checkAuthorization = () => {
      try {
        const roles = JSON.parse(localStorage.getItem("role") || "[]");
        const isAdmin = roles.includes("ADMIN");
        const isManager = roles.includes("MANAGER");
        const isCollaborator = roles.includes("COLLABORATOR");
        const isClient = roles.includes("CLIENT");
        
        setHasAccess(isAdmin || isManager || isCollaborator || isClient || !requiresAuth);
        setIsAdminOrManager(isAdmin || isManager);
      } catch (error) {
        console.error("Error checking authorization:", error);
        setHasAccess(!requiresAuth);
        setIsAdminOrManager(false);
      }
    };
    
    checkAuthorization();
    
    const handleStorageChange = () => {
      checkAuthorization();
    };
    
    window.addEventListener('storage', handleStorageChange);
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, [requiresAuth]);
  
  if (requiresAuth && !hasAccess) {
    return (
      <Stack
        sx={{
          ...bgGradient({
            direction: '135deg',
            startColor: alpha(theme.palette.error.light, 0.2),
            endColor: alpha(theme.palette.error.main, 0.2),
          }),
          p: 5,
          borderRadius: 2,
          textAlign: 'center',
          color: 'error.darker',
          backgroundColor: 'common.white',
        }}
        {...other}
      >
        <Iconify 
          icon="solar:shield-cross-bold" 
          sx={{ 
            width: 80, 
            height: 80, 
            color: 'error.main',
            mb: 3,
            mx: 'auto'
          }} 
        />
        
        <Typography variant="h4" sx={{ mb: 2 }}>
          Access Denied
        </Typography>
        
        <Typography
          variant="body2"
          sx={{
            opacity: 0.8,
            maxWidth: 480,
            mx: 'auto',
            mb: 5,
          }}
        >
          You don't have permission to view this content.
          Please contact your administrator for access.
        </Typography>
        
        <Button 
          variant="contained" 
          onClick={() => router.push(paths.dashboard.root)}
          sx={{ mx: 'auto' }}
        >
          Go to Dashboard
        </Button>
      </Stack>
    );
  }
  
  const shouldShowAdminContent = !adminOnly || isAdminOrManager;

  return (
    <Stack
      flexDirection={{ xs: 'column', md: 'row' }}
      sx={{
        ...bgGradient({
          direction: '135deg',
          startColor: alpha(theme.palette.primary.light, 0.2),
          endColor: alpha(theme.palette.primary.main, 0.2),
        }),
        height: { md: 1 },
        borderRadius: 2,
        position: 'relative',
        color: 'primary.darker',
        backgroundColor: 'common.white',
      }}
      {...other}
    >
      <Stack
        flexGrow={1}
        justifyContent="center"
        alignItems={{ xs: 'center', md: 'flex-start' }}
        sx={{
          p: {
            xs: theme.spacing(3, 2, 0, 2),
            md: theme.spacing(5),
          },
          textAlign: { xs: 'center', md: 'left' },
        }}
      >
        <Typography variant="h4" sx={{ mb: 2, whiteSpace: 'pre-line' }}>
          {title}
        </Typography>

        <Typography
          variant="body2"
          sx={{
            opacity: 0.8,
            maxWidth: 360,
            mb: { xs: 3, xl: 5 },
          }}
        >
          {description}
        </Typography>

        {shouldShowAdminContent && action && action}
      </Stack>

      {img && (
        <Stack
          component="span"
          justifyContent="center"
          sx={{
            p: { xs: 5, md: 3 },
            maxWidth: 360,
            mx: 'auto',
          }}
        >
          {img}
        </Stack>
      )}
    </Stack>
  );
}
