import React, { useState, useEffect, useContext } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { Container, Card, Row, Col, ProgressBar, Badge, Button, ListGroup } from 'react-bootstrap';
import { FaEdit, FaTrash, FaShareAlt, FaArrowLeft } 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 ProjectDetail = () => {
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { id } = useParams();
  const { hasRole } = useContext(AuthContext);
  const navigate = useNavigate();

  useEffect(() => {
    fetchProject();
  }, [id]);

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

  const handleDeleteProject = async () => {
    if (window.confirm('Are you sure you want to delete this project?')) {
      try {
        await api.delete(`/projects/${id}`);
        navigate('/dashboard');
      } 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) => {
    if (!dateString) return 'Not set';
    return new Date(dateString).toLocaleDateString();
  };

  if (loading) return <LoadingSpinner />;
  if (!project) return <AlertMessage variant="danger" message="Project not found" />;

  return (
    <Container>
      <Button 
        as={Link} 
        to="/dashboard" 
        variant="outline-secondary" 
        className="mb-3"
      >
        <FaArrowLeft className="me-1" /> Back to Dashboard
      </Button>

      {error && <AlertMessage variant="danger" message={error} />}
      
      <Card className="shadow-sm mb-4">
        <Card.Header className="bg-primary text-white d-flex justify-content-between align-items-center">
          <h3 className="mb-0">{project.name}</h3>
          <Badge 
            bg={getProgressVariant(project.completion_percentage)}
            style={{ fontSize: '1rem' }}
          >
            {project.completion_percentage}% Complete
          </Badge>
        </Card.Header>
        
        <Card.Body>
          <Row className="mb-4">
            <Col md={12}>
              <h5>Progress</h5>
              <ProgressBar 
                variant={getProgressVariant(project.completion_percentage)} 
                now={project.completion_percentage} 
                className="mb-2"
                style={{ height: '25px' }}
              />
            </Col>
          </Row>
          
          <Row className="mb-4">
            <Col md={6}>
              <h5>Project Details</h5>
              <Card className="border">
                <Card.Body className="details-card">
                  <div className="mb-2">
                    <strong>Start Date:</strong> {formatDate(project.start_date)}
                  </div>
                  <div className="mb-2">
                    <strong>End Date:</strong> {formatDate(project.end_date)}
                  </div>
                  <div>
                    <strong>Last Updated:</strong> {formatDate(project.updated_at)}
                  </div>
                </Card.Body>
              </Card>
            </Col>
            
            <Col md={6}>
              <h5>Description</h5>
              <Card className="border">
                <Card.Body className="description-card">
                  {project.description || 'No description provided'}
                </Card.Body>
              </Card>
            </Col>
          </Row>
          
          {project.notes && (
            <Row className="mb-3">
              <Col md={12}>
                <h5>Additional Notes</h5>
                <Card className="border">
                  <Card.Body className="notes-card">
                    {project.notes}
                  </Card.Body>
                </Card>
              </Col>
            </Row>
          )}
        </Card.Body>
        
        {(hasRole('super_admin') || hasRole('admin')) && (
          <Card.Footer className="bg-white">
            <div className="d-flex justify-content-end gap-2">
              <Button 
                as={Link} 
                to={`/projects/${project.id}/edit`}
                variant="primary" 
              >
                <FaEdit className="me-1" /> Edit Project
              </Button>
              
              <Button 
                variant="danger" 
                onClick={handleDeleteProject}
              >
                <FaTrash className="me-1" /> Delete Project
              </Button>
              
              <Button 
                as={Link} 
                to={`/projects/${project.id}/share`}
                variant="info" 
                className="text-white"
              >
                <FaShareAlt className="me-1" /> Share Project
              </Button>
            </div>
          </Card.Footer>
        )}
      </Card>
    </Container>
  );
};

export default ProjectDetail;
