import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Chip,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  LinearProgress,
} from '@mui/material';
import {
  Add as AddIcon,
  Assignment as AssignmentIcon,
  Folder as FolderIcon,
  People as PeopleIcon,
  TrendingUp as TrendingUpIcon,
  MoreVert as MoreVertIcon,
} from '@mui/icons-material';
import { useAuth } from '../contexts/AuthContext';
import { Project, Task, projectsAPI } from '../services/api';
import { useNavigate } from 'react-router-dom';

const Dashboard: React.FC = () => {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const { user } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    fetchProjects();
  }, []);

  const fetchProjects = async () => {
    try {
      const response = await projectsAPI.getProjects();
      if (response.success && response.data) {
        setProjects(response.data);
      }
    } catch (error) {
      console.error('Failed to fetch projects:', error);
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'success';
      case 'completed': return 'default';
      case 'on_hold': return 'warning';
      default: return 'primary';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent': return 'error';
      case 'high': return 'warning';
      case 'medium': return 'info';
      case 'low': return 'success';
      default: return 'default';
    }
  };

  if (loading) {
    return <LinearProgress />;
  }

  return (
    <Box>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          Welcome back, {user?.first_name}!
        </Typography>
        <Typography variant="subtitle1" color="text.secondary">
          Here's what's happening with your projects today.
        </Typography>
      </Box>

      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 3, mb: 4 }}>
        {/* Stats Cards */}
        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <FolderIcon color="primary" sx={{ mr: 1 }} />
              <Typography variant="h6">Projects</Typography>
            </Box>
            <Typography variant="h4">{projects.length}</Typography>
            <Typography color="text.secondary">Active projects</Typography>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <AssignmentIcon color="secondary" sx={{ mr: 1 }} />
              <Typography variant="h6">Tasks</Typography>
            </Box>
            <Typography variant="h4">
              {projects.reduce((total, project) => total + (project.tasks?.length || 0), 0)}
            </Typography>
            <Typography color="text.secondary">Total tasks</Typography>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <PeopleIcon color="success" sx={{ mr: 1 }} />
              <Typography variant="h6">Team</Typography>
            </Box>
            <Typography variant="h4">
              {new Set(projects.flatMap(p => p.members?.map(m => m.id) || [])).size}
            </Typography>
            <Typography color="text.secondary">Team members</Typography>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <TrendingUpIcon color="info" sx={{ mr: 1 }} />
              <Typography variant="h6">Progress</Typography>
            </Box>
            <Typography variant="h4">85%</Typography>
            <Typography color="text.secondary">Overall progress</Typography>
          </CardContent>
        </Card>
      </Box>

      <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '2fr 1fr' }, gap: 3 }}>
        {/* Recent Projects */}
        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6">Recent Projects</Typography>
              <Button
                startIcon={<AddIcon />}
                onClick={() => navigate('/projects/new')}
                variant="outlined"
                size="small"
              >
                New Project
              </Button>
            </Box>
            
            {projects.length === 0 ? (
              <Box sx={{ textAlign: 'center', py: 4 }}>
                <FolderIcon sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
                <Typography variant="h6" color="text.secondary">
                  No projects yet
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  Create your first project to get started
                </Typography>
                <Button
                  variant="contained"
                  startIcon={<AddIcon />}
                  onClick={() => navigate('/projects/new')}
                >
                  Create Project
                </Button>
              </Box>
            ) : (
              <List>
                {projects.slice(0, 5).map((project) => (
                  <ListItem
                    key={project.id}
                    component="div"
                    onClick={() => navigate(`/projects/${project.id}`)}
                    sx={{ cursor: 'pointer' }}
                  >
                    <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: project.color, mr: 2 }} />
                    <ListItemText
                      primary={project.name}
                      secondary={
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
                          <Chip
                            label={project.status}
                            size="small"
                            color={getStatusColor(project.status) as any}
                            variant="outlined"
                          />
                          <Typography variant="caption" color="text.secondary">
                            {project.tasks?.length || 0} tasks
                          </Typography>
                        </Box>
                      }
                    />
                    <ListItemSecondaryAction>
                      <IconButton edge="end">
                        <MoreVertIcon />
                      </IconButton>
                    </ListItemSecondaryAction>
                  </ListItem>
                ))}
              </List>
            )}
          </CardContent>
        </Card>

        {/* Recent Tasks */}
        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>Recent Tasks</Typography>
            
            {projects.flatMap(p => p.tasks || []).length === 0 ? (
              <Box sx={{ textAlign: 'center', py: 4 }}>
                <AssignmentIcon sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
                <Typography variant="body2" color="text.secondary">
                  No tasks yet
                </Typography>
              </Box>
            ) : (
              <List dense>
                {projects
                  .flatMap(p => p.tasks?.map((task: Task) => ({ ...task, projectName: p.name })) || [])
                  .slice(0, 5)
                  .map((task: any) => (
                    <ListItem key={task.id} dense>
                      <ListItemText
                        primary={
                          <Typography variant="body2" noWrap>
                            {task.title}
                          </Typography>
                        }
                        secondary={
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
                            <Chip
                              label={task.priority}
                              size="small"
                              color={getPriorityColor(task.priority) as any}
                              variant="outlined"
                            />
                            <Typography variant="caption" color="text.secondary">
                              {task.projectName}
                            </Typography>
                          </Box>
                        }
                      />
                    </ListItem>
                  ))}
              </List>
            )}
          </CardContent>
        </Card>
      </Box>
    </Box>
  );
};

export default Dashboard;
