import React, { useState, useEffect } from 'react';
import { Container, Row, Col, Card, Table, Button, Alert, Badge, ProgressBar, InputGroup, FormControl } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { FaEye, FaEdit, FaShareAlt, FaCopy, FaKey, FaLink } from 'react-icons/fa';
import api from '../../utils/api';
import LoadingSpinner from '../common/LoadingSpinner';

const ShareableProjects = () => {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [shareUrls, setShareUrls] = useState({});
  const [copiedId, setCopiedId] = useState(null);
  const [successMessage, setSuccessMessage] = useState('');

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

  const fetchShareableProjects = async () => {
    try {
      setLoading(true);
      const response = await api.get('/projects/shareable/all');
      setProjects(response.data);
      
      // Pre-generate share URLs for projects that already have shareInfo
      const urls = {};
      response.data.forEach(project => {
        if (project.shareInfo) {
          urls[project.id] = generateShareUrl(project.shareInfo.shareId);
        }
      });
      setShareUrls(urls);
      
      setError(null);
    } catch (err) {
      console.error('Error fetching shareable projects:', err);
      setError('Failed to load shareable projects. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  const generateShareUrl = (shareId) => {
    return `${window.location.origin}/projects/shared/${shareId}`;
  };

  const handleGenerateShareLink = async (projectId) => {
    try {
      // Generate a random password for the share link
      const randomPassword = Math.random().toString(36).substring(2, 10);
      
      const response = await api.post(`/projects/${projectId}/share`, {
        password: randomPassword
      });
      
      if (response.data.shareId) {
        // Update the project in state with new share info
        setProjects(projects.map(project => 
          project.id === projectId 
            ? { 
                ...project, 
                shareInfo: {
                  shareId: response.data.shareId,
                  createdAt: response.data.createdAt
                }
              } 
            : project
        ));
        
        // Generate and store the share URL
        const url = generateShareUrl(response.data.shareId);
        setShareUrls({
          ...shareUrls,
          [projectId]: url
        });
        
        setSuccessMessage(`Share link generated for project! Password: ${randomPassword}`);
        setTimeout(() => setSuccessMessage(''), 5000);
      }
    } catch (err) {
      console.error('Error generating share link:', err);
      setError('Failed to generate share link.');
    }
  };

  const handleCopyUrl = (projectId) => {
    const url = shareUrls[projectId];
    if (url) {
      navigator.clipboard.writeText(url);
      setCopiedId(projectId);
      setTimeout(() => setCopiedId(null), 2000);
    }
  };

  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">All Shareable Projects</h1>
      
      {error && <Alert variant="danger">{error}</Alert>}
      {successMessage && <Alert variant="success">{successMessage}</Alert>}
      
      {projects.length === 0 ? (
        <Card className="text-center p-5">
          <Card.Body>
            <h4>No projects found</h4>
            <Button as={Link} to="/dashboard" variant="primary" className="mt-3">
              Return to Dashboard
            </Button>
          </Card.Body>
        </Card>
      ) : (
        <Card className="shadow-sm">
          <Card.Header>
            <h4 className="mb-0">Your Shareable Projects</h4>
            <p className="text-muted mb-0 mt-2">Share multiple projects with clients or stakeholders</p>
          </Card.Header>
          <Card.Body>
            <Row>
              {projects.map(project => (
                <Col md={6} xl={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"
                      />
                      
                      <p className="card-text text-truncate mb-3">
                        {project.description || 'No description provided'}
                      </p>
                      
                      {project.shareInfo ? (
                        <div className="mb-3">
                          <InputGroup size="sm">
                            <FormControl
                              value={shareUrls[project.id] || ''}
                              readOnly
                              aria-label="Share URL"
                            />
                            <Button 
                              variant="outline-success"
                              onClick={() => handleCopyUrl(project.id)}
                            >
                              {copiedId === project.id ? 'Copied!' : <FaCopy />} 
                            </Button>
                          </InputGroup>
                          <small className="text-muted">
                            Shared on: {formatDate(project.shareInfo.createdAt)}
                          </small>
                        </div>
                      ) : (
                        <Button 
                          variant="outline-primary"
                          className="w-100 mb-3"
                          onClick={() => handleGenerateShareLink(project.id)}
                        >
                          <FaLink className="me-1" /> Generate Share Link
                        </Button>
                      )}
                    </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>
                        
                        <Button 
                          as={Link} 
                          to={`/projects/${project.id}/edit`}
                          variant="outline-secondary" 
                          size="sm"
                        >
                          <FaEdit className="me-1" /> Edit
                        </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>
          </Card.Body>
        </Card>
      )}
    </Container>
  );
};

export default ShareableProjects;
