import React, { useState, useEffect, useContext } from 'react';
import { Container, Row, Col, Card, ProgressBar, Badge, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { FaEye, FaEdit, FaTrash, FaShareAlt } from 'react-icons/fa';
import AuthContext from '../../context/AuthContext';
import api from '../../utils/api';
import LoadingSpinner from '../common/LoadingSpinner';
import AlertMessage from '../common/AlertMessage';

const Dashboard = () => {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { user, hasRole } = useContext(AuthContext);

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

  const fetchProjects = async () => {
    try {
      setLoading(true);
      const response = await api.get('/projects');
      setProjects(response.data);
      setError(null);
    } catch (err) {
      console.error('Error fetching projects:', err);
      setError('Failed to load projects. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteProject = async (id) => {
    if (window.confirm('Are you sure you want to delete this project?')) {
      try {
        await api.delete(`/projects/${id}`);
        setProjects(projects.filter(project => project.id !== id));
      } catch (err) {
        console.error('Error deleting project:', err);
        setError('Failed to delete project.');
      }
    }
  };

  const getProgressVariant = (percentage) => {
    if (percentage < 25) return 'danger';
    if (percentage < 50) return 'warning';
    if (percentage < 75) return 'info';
    return 'success';
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString();
  };

  if (loading) return <LoadingSpinner />;

  return (
    <Container>
      <h1 className="mb-4">Project Dashboard</h1>
      
      {error && <AlertMessage variant="danger" message={error} />}
      
      {projects.length === 0 ? (
        <Card className="text-center p-5">
          <Card.Body>
            <h4>No projects found</h4>
            {(hasRole('super_admin') || hasRole('admin')) && (
              <Button as={Link} to="/projects/new" variant="primary" className="mt-3">
                Create Your First Project
              </Button>
            )}
          </Card.Body>
        </Card>
      ) : (
        <Row>
          {projects.map(project => (
            <Col md={6} lg={4} key={project.id} className="mb-4">
              <Card className="h-100 shadow-sm">
                <Card.Header className="d-flex justify-content-between align-items-center">
                  <h5 className="mb-0 text-truncate" style={{ maxWidth: '80%' }}>
                    {project.name}
                  </h5>
                  <Badge 
                    bg={getProgressVariant(project.completion_percentage)}
                    className="ms-auto"
                  >
                    {project.completion_percentage}%
                  </Badge>
                </Card.Header>
                <Card.Body>
                  <ProgressBar 
                    variant={getProgressVariant(project.completion_percentage)} 
                    now={project.completion_percentage} 
                    className="mb-3"
                  />
                  
                  <div className="mb-3">
                    <small className="text-muted">
                      Timeline: {project.start_date ? formatDate(project.start_date) : 'Not set'} 
                      {project.end_date ? ` - ${formatDate(project.end_date)}` : ''}
                    </small>
                  </div>
                  
                  <p className="card-text text-truncate">
                    {project.description || 'No description provided'}
                  </p>
                  
                  <div className="d-flex justify-content-between">
                    <small className="text-muted">
                      Last updated: {formatDate(project.updated_at)}
                    </small>
                  </div>
                </Card.Body>
                <Card.Footer className="bg-white">
                  <div className="d-flex justify-content-between dashboard-action-buttons">
                    <Button 
                      as={Link} 
                      to={`/projects/${project.id}`}
                      variant="outline-primary" 
                      size="sm"
                    >
                      <FaEye className="me-1" /> View
                    </Button>
                    
                    {(hasRole('super_admin') || hasRole('admin')) && (
                      <>
                        <Button 
                          as={Link} 
                          to={`/projects/${project.id}/edit`}
                          variant="outline-secondary" 
                          size="sm"
                        >
                          <FaEdit className="me-1" /> Edit
                        </Button>
                        
                        <Button 
                          variant="outline-danger" 
                          size="sm"
                          onClick={() => handleDeleteProject(project.id)}
                        >
                          <FaTrash className="me-1" /> Delete
                        </Button>

                        <Button 
                          as={Link} 
                          to={`/projects/${project.id}/share`}
                          variant="outline-info" 
                          size="sm"
                        >
                          <FaShareAlt className="me-1" /> Share
                        </Button>
                      </>
                    )}
                  </div>
                </Card.Footer>
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </Container>
  );
};

export default Dashboard;
