import { useEffect, useState } from 'react';
import {
  Box,
  Card,
  Grid,
  Stack,
  Button,
  Container,
  Typography,
  LinearProgress,
  CircularProgress,
} from '@mui/material';
import { alpha } from '@mui/material/styles';
import { useTheme } from '@mui/material/styles';
import Iconify from '@/shared/components/iconify';
import { ITaskItem } from '@/contexts/types/tasks';

type Props = {
  tasks: ITaskItem[];
  onBack: () => void;
};

export default function KanbanOverview({ tasks, onBack }: Props) {
  const theme = useTheme();
  const [isVisible, setIsVisible] = useState(false);

  // Trigger animation after mount
  useEffect(() => {
    setIsVisible(true);
  }, []);

  // Calculate statistics
  const totalTasks = tasks.length;
  const completedTasks = tasks.filter(task => task.status === 'DONE').length;
  const inProgressTasks = tasks.filter(task => task.status === 'IN PROGRESS').length;
  const todoTasks = tasks.filter(task => task.status === 'TO DO').length;

  // Priority statistics
  const highPriorityTasks = tasks.filter(task => task.priority === 'HIGH').length;
  const mediumPriorityTasks = tasks.filter(task => task.priority === 'MEDIUM').length;
  const lowPriorityTasks = tasks.filter(task => task.priority === 'LOW').length;

  const progressPercentage = Math.round((completedTasks / totalTasks) * 100) || 0;

  return (
    <Container 
      maxWidth={false}
      sx={{
        '& .animate-in': {
          opacity: 0,
          transform: 'translateY(20px)',
          transition: 'all 0.6s ease-out',
          '&.visible': {
            opacity: 1,
            transform: 'translateY(0)',
          }
        },
        '& .delay-1': { transitionDelay: '0.1s' },
        '& .delay-2': { transitionDelay: '0.2s' },
        '& .delay-3': { transitionDelay: '0.3s' },
        '& .delay-4': { transitionDelay: '0.4s' },
      }}
    >
      {/* Header */}
      <Box className={`animate-in ${isVisible ? 'visible' : ''}`}>
        <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 3 }}>
          <Typography variant="h4">Project Overview</Typography>
          <Button
            color="inherit"
            onClick={onBack}
            startIcon={<Iconify icon="eva:arrow-back-fill" />}
            sx={{ 
              bgcolor: 'background.neutral',
              '&:hover': { bgcolor: 'background.neutral' }
            }}
          >
            Back to Board
          </Button>
        </Stack>
      </Box>

      <Grid container spacing={3}>
        {/* Quick Stats */}
        <Grid item xs={12}>
          <Grid container spacing={3}>
            {[
              {
                title: 'Total Tasks',
                total: totalTasks,
                icon: 'eva:list-fill',
                color: theme.palette.info.main
              },
              {
                title: 'Completed',
                total: completedTasks,
                icon: 'eva:checkmark-circle-2-fill',
                color: theme.palette.success.main
              },
              {
                title: 'In Progress',
                total: inProgressTasks,
                icon: 'eva:clock-fill',
                color: theme.palette.warning.main
              },
              {
                title: 'To Do',
                total: todoTasks,
                icon: 'eva:file-fill',
                color: theme.palette.error.main
              },
            ].map((item, index) => (
              <Grid key={item.title} item xs={12} sm={6} md={3}>
                <Box className={`animate-in delay-${index + 1} ${isVisible ? 'visible' : ''}`}>
                  <Card sx={{ p: 3 }}>
                    <Stack direction="row" alignItems="center" spacing={2}>
                      <Box sx={{ 
                        width: 48, 
                        height: 48, 
                        borderRadius: 1.5,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        bgcolor: alpha(item.color, 0.16)
                      }}>
                        <Iconify icon={item.icon} sx={{ width: 24, height: 24, color: item.color }} />
                      </Box>
                      <Box>
                        <Typography variant="subtitle2" sx={{ color: 'text.secondary' }}>
                          {item.title}
                        </Typography>
                        <Typography variant="h3">{item.total}</Typography>
                      </Box>
                    </Stack>
                  </Card>
                </Box>
              </Grid>
            ))}
          </Grid>
        </Grid>

        {/* Progress Charts */}
        <Grid item xs={12} md={8}>
          <Box className={`animate-in delay-2 ${isVisible ? 'visible' : ''}`}>
            <Card sx={{ p: 3 }}>
              <Typography variant="h6" sx={{ mb: 3 }}>Task Status</Typography>
              <Stack spacing={3}>
                {[
                  { label: 'Completed', value: completedTasks, color: 'success.main' },
                  { label: 'In Progress', value: inProgressTasks, color: 'warning.main' },
                  { label: 'To Do', value: todoTasks, color: 'info.main' },
                ].map((item) => (
                  <Stack key={item.label} spacing={1}>
                    <Stack direction="row" justifyContent="space-between">
                      <Typography variant="subtitle2">{item.label}</Typography>
                      <Typography variant="subtitle2">{item.value} tasks</Typography>
                    </Stack>
                    <LinearProgress 
                      variant="determinate" 
                      value={(item.value / totalTasks) * 100}
                      sx={{ 
                        height: 8,
                        bgcolor: 'background.neutral',
                        '& .MuiLinearProgress-bar': {
                          bgcolor: item.color,
                          transition: 'transform 1s ease-in-out',
                        },
                      }} 
                    />
                  </Stack>
                ))}
              </Stack>
            </Card>
          </Box>
        </Grid>

        {/* Overall Progress */}
        <Grid item xs={12} md={4}>
          <Box className={`animate-in delay-3 ${isVisible ? 'visible' : ''}`}>
            <Card sx={{ p: 3, height: '100%' }}>
              <Typography variant="h6" sx={{ mb: 3 }}>Overall Progress</Typography>
              <Stack 
                alignItems="center" 
                justifyContent="center" 
                sx={{ height: '100%', py: 5 }}
              >
                <Box sx={{ position: 'relative', display: 'inline-flex' }}>
                  <CircularProgress
                    variant="determinate"
                    value={progressPercentage}
                    size={120}
                    thickness={4}
                    sx={{
                      color: theme.palette.primary.main,
                      transition: 'all 1s ease-in-out',
                    }}
                  />
                  <Box
                    sx={{
                      top: 0,
                      left: 0,
                      right: 0,
                      bottom: 0,
                      position: 'absolute',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <Typography variant="h4" component="div">
                      {progressPercentage}%
                    </Typography>
                  </Box>
                </Box>
              </Stack>
            </Card>
          </Box>
        </Grid>
      </Grid>
    </Container>
  );
}