import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Container, Card, Form, Button, InputGroup, Alert } from 'react-bootstrap';
import { FaArrowLeft, FaCopy, FaKey } from 'react-icons/fa';
import api from '../../utils/api';
import LoadingSpinner from '../common/LoadingSpinner';

const ProjectShare = () => {
  const { id } = useParams();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [shareId, setShareId] = useState('');
  const [password, setPassword] = useState('');
  const [shareUrl, setShareUrl] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [copied, setCopied] = useState(false);

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

  const fetchProject = async () => {
    try {
      setLoading(true);
      const response = await api.get(`/projects/${id}`);
      setProject(response.data);
      
      // Check if project already has a share link
      try {
        const sharesResponse = await api.get(`/projects/${id}/share`);
        if (sharesResponse.data.shareId) {
          setShareId(sharesResponse.data.shareId);
          generateShareUrl(sharesResponse.data.shareId);
        }
      } catch (err) {
        // API returned 404, which means no share exists - this is fine
        if (err.response && err.response.status !== 404) {
          console.error('Error checking for existing share:', err);
        }
      }
      
      setError(null);
    } catch (err) {
      console.error('Error fetching project:', err);
      setError('Failed to load project details.');
    } finally {
      setLoading(false);
    }
  };

  const generateShareUrl = (sid) => {
    const baseUrl = window.location.origin;
    setShareUrl(`${baseUrl}/shared/${sid}`);
  };

  const handleGenerateShare = async (e) => {
    e.preventDefault();
    if (!password) {
      setError('Please enter a password for the shared link');
      return;
    }

    try {
      setLoading(true);
      const response = await api.post(`/projects/${id}/share`, { password });
      setShareId(response.data.shareId);
      generateShareUrl(response.data.shareId);
      setSuccessMessage('Share link generated successfully!');
      setError(null);
    } catch (err) {
      console.error('Error generating share link:', err);
      setError('Failed to generate share link.');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(shareUrl).then(
      () => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      },
      (err) => {
        console.error('Could not copy text: ', err);
      }
    );
  };

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

  return (
    <Container>
      <Button 
        as={Link} 
        to={`/projects/${id}`} 
        variant="outline-secondary" 
        className="mb-3"
      >
        <FaArrowLeft className="me-1" /> Back to Project
      </Button>

      <Card className="shadow-sm">
        <Card.Header className="bg-primary text-white">
          <h3 className="mb-0">Share Project: {project.name}</h3>
        </Card.Header>
        
        <Card.Body>
          {error && <Alert variant="danger">{error}</Alert>}
          {successMessage && <Alert variant="success">{successMessage}</Alert>}
          
          {!shareId ? (
            <Form onSubmit={handleGenerateShare}>
              <Form.Group className="mb-3">
                <Form.Label>
                  <FaKey className="me-2" />
                  Create a password for viewers
                </Form.Label>
                <Form.Text className="d-block mb-2">
                  This password will be required for anyone accessing the shared link.
                </Form.Text>
                <Form.Control
                  type="password"
                  placeholder="Enter a secure password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
              </Form.Group>
              
              <Button type="submit" variant="primary" className="mt-2">
                Generate Share Link
              </Button>
            </Form>
          ) : (
            <>
              <Alert variant="info">
                <p className="mb-1">Your project can now be accessed via the link below:</p>
                <p className="mb-0">Share this link and the password with people you want to give access to.</p>
              </Alert>
              
              <Form.Group className="mb-3">
                <Form.Label>Share Link</Form.Label>
                <InputGroup>
                  <Form.Control
                    type="text"
                    value={shareUrl}
                    readOnly
                  />
                  <Button 
                    variant={copied ? "success" : "outline-secondary"}
                    onClick={copyToClipboard}
                  >
                    <FaCopy className="me-1" />
                    {copied ? 'Copied!' : 'Copy'}
                  </Button>
                </InputGroup>
              </Form.Group>
              
              <p>To generate a new link and password, simply enter a new password below:</p>
              
              <Form onSubmit={handleGenerateShare}>
                <Form.Group className="mb-3">
                  <Form.Label>New Password</Form.Label>
                  <Form.Control
                    type="password"
                    placeholder="Enter a new password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </Form.Group>
                
                <Button type="submit" variant="primary">
                  Generate New Link
                </Button>
              </Form>
            </>
          )}
        </Card.Body>
      </Card>
    </Container>
  );
};

export default ProjectShare;
