import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Container, Card, Row, Col, ProgressBar, Badge, Form, Button, Alert } from 'react-bootstrap';
import { FaLock, FaUnlock } from 'react-icons/fa';
import api from '../../utils/api';
import LoadingSpinner from '../common/LoadingSpinner';

const SharedProjectView = () => {
  const { shareId } = useParams();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [password, setPassword] = useState('');
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    fetchSharedProject();
  }, [shareId]);

  const fetchSharedProject = async () => {
    try {
      setLoading(true);
      const response = await api.get(`/projects/shared/${shareId}`);
      setProject(response.data);
      setError(null);
      // The project info returned without password verification is limited
      // Full project details require password verification
    } catch (err) {
      console.error('Error fetching shared project:', err);
      setError('This shared project link is invalid or has expired.');
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async (e) => {
    e.preventDefault();
    try {
      setLoading(true);
      const response = await api.post(`/projects/shared/${shareId}/verify`, { password });
      setProject(response.data);
      setAuthenticated(true);
      setError(null);
    } catch (err) {
      console.error('Error verifying password:', err);
      setError('Invalid password. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  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 <Alert variant="danger">Shared project not found</Alert>;

  return (
    <Container className="mt-5">
      <Card className="shadow-sm">
        <Card.Header className="bg-primary text-white">
          <h3 className="mb-0">
            {authenticated ? (
              <><FaUnlock className="me-2" /> {project.name}</>
            ) : (
              <><FaLock className="me-2" /> Protected Project: {project.name}</>
            )}
          </h3>
        </Card.Header>
        
        <Card.Body>
          {error && <Alert variant="danger">{error}</Alert>}
          
          {!authenticated ? (
            <div className="p-4 text-center">
              <FaLock size={50} className="text-muted mb-3" />
              <h4>This project is password protected</h4>
              <p className="mb-4">Enter the password provided by the project owner to view the details.</p>
              
              <Row className="justify-content-center">
                <Col md={6}>
                  <Form onSubmit={handlePasswordSubmit}>
                    <Form.Group className="mb-3">
                      <Form.Control
                        type="password"
                        placeholder="Enter password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                      />
                    </Form.Group>
                    
                    <Button type="submit" variant="primary" className="w-100">
                      Access Project
                    </Button>
                  </Form>
                </Col>
              </Row>
            </div>
          ) : (
            <>
              <Row className="mb-4">
                <Col md={12}>
                  <h5>Project Progress</h5>
                  <div className="d-flex align-items-center mb-2">
                    <h2 className="me-2 mb-0">
                      {project.completion_percentage}%
                    </h2>
                    <Badge 
                      bg={getProgressVariant(project.completion_percentage)}
                      className="py-2 px-3"
                      style={{ fontSize: '1rem' }}
                    >
                      {project.completion_percentage < 25 ? 'Just Started' : 
                       project.completion_percentage < 50 ? 'In Progress' :
                       project.completion_percentage < 75 ? 'Well Advanced' :
                       project.completion_percentage < 100 ? 'Almost Complete' : 'Completed'}
                    </Badge>
                  </div>
                  <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}>
                  <Card>
                    <Card.Header>Project Timeline</Card.Header>
                    <Card.Body>
                      <p><strong>Start Date:</strong> {formatDate(project.start_date)}</p>
                      <p><strong>End Date:</strong> {formatDate(project.end_date)}</p>
                      <p><strong>Last Updated:</strong> {formatDate(project.updated_at)}</p>
                    </Card.Body>
                  </Card>
                </Col>
                
                <Col md={6}>
                  <Card>
                    <Card.Header>Project Description</Card.Header>
                    <Card.Body>
                      <p>{project.description || 'No description provided'}</p>
                    </Card.Body>
                  </Card>
                </Col>
              </Row>
              
              {project.notes && (
                <Row>
                  <Col md={12}>
                    <Card>
                      <Card.Header>Additional Notes</Card.Header>
                      <Card.Body>
                        <p>{project.notes}</p>
                      </Card.Body>
                    </Card>
                  </Col>
                </Row>
              )}
            </>
          )}
        </Card.Body>
        
        <Card.Footer className="text-center text-muted">
          <small>
            This is a shared view of a project from Project Progress Tracker.
            {!authenticated && ' Enter the correct password to see full project details.'}
          </small>
        </Card.Footer>
      </Card>
    </Container>
  );
};

export default SharedProjectView;
