// Create a new component: Lightbox.jsx
import React, { useState, useEffect } from 'react';

const Lightbox = ({ 
  isOpen, 
  onClose, 
  mediaUrl, 
  mediaType, 
  fileName, 
  thumbnailUrl 
}) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setLoading(true);
      setError(false);
      // Prevent body scroll when lightbox is open
      document.body.style.overflow = 'hidden';
    } else {
      // Restore body scroll when lightbox is closed
      document.body.style.overflow = 'unset';
    }

    // Cleanup on unmount
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [isOpen]);

  // Handle keyboard events
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const handleOverlayClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  const handleMediaLoad = () => {
    setLoading(false);
  };

  const handleMediaError = () => {
    setLoading(false);
    setError(true);
  };

  const renderMedia = () => {
    if (mediaType === 'image') {
      return (
        <img
          src={mediaUrl}
          alt={fileName}
          style={styles.media}
          onLoad={handleMediaLoad}
          onError={handleMediaError}
        />
      );
    } else if (mediaType === 'video') {
      return (
        <video
          src={mediaUrl}
          controls
          autoPlay={false}
          style={styles.media}
          onLoadedData={handleMediaLoad}
          onError={handleMediaError}
          poster={thumbnailUrl}
        >
          Your browser does not support the video tag.
        </video>
      );
    }
  };

  return (
    <div style={styles.overlay} onClick={handleOverlayClick}>
      <div style={styles.container}>
        {/* Close button */}
        <button style={styles.closeBtn} onClick={onClose} title="Close (Esc)">
          ✕
        </button>

        {/* Loading spinner */}
        {loading && (
          <div style={styles.loading}>
            <div style={styles.spinner}>⏳</div>
            <p>Loading {mediaType}...</p>
          </div>
        )}

        {/* Error state */}
        {error && (
          <div style={styles.error}>
            <div style={styles.errorIcon}>❌</div>
            <p>Failed to load {mediaType}</p>
            <button style={styles.retryBtn} onClick={() => window.open(mediaUrl, '_blank')}>
              Open in new tab
            </button>
          </div>
        )}

        {/* Media content */}
        {!error && (
          <div style={{ ...styles.mediaContainer, opacity: loading ? 0 : 1 }}>
            {renderMedia()}
          </div>
        )}

        {/* File info */}
        <div style={styles.info}>
          <div style={styles.fileName}>{fileName}</div>
          <div style={styles.actions}>
            <button
              style={styles.actionBtn}
              onClick={() => window.open(mediaUrl, '_blank')}
              title="Open in new tab"
            >
              🔗 Open in new tab
            </button>
            <a
              href={mediaUrl}
              download={fileName}
              style={styles.actionBtn}
              title="Download"
            >
              📥 Download
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

// Lightbox styles
const styles = {
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.9)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 9999,
    padding: 20,
    backdropFilter: 'blur(5px)'
  },
  container: {
    position: 'relative',
    maxWidth: '90vw',
    maxHeight: '90vh',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 16
  },
  closeBtn: {
    position: 'absolute',
    top: -50,
    right: 0,
    background: 'rgba(255, 255, 255, 0.2)',
    color: '#fff',
    border: 'none',
    borderRadius: '50%',
    width: 40,
    height: 40,
    fontSize: 18,
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    transition: 'all 0.2s ease',
    zIndex: 10000
  },
  loading: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 16,
    color: '#fff',
    fontSize: 16
  },
  spinner: {
    fontSize: 32,
    animation: 'pulse 1.5s ease-in-out infinite alternate'
  },
  error: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 16,
    color: '#fff',
    fontSize: 16,
    textAlign: 'center'
  },
  errorIcon: {
    fontSize: 48
  },
  retryBtn: {
    background: '#2b62d9',
    color: '#fff',
    border: 'none',
    borderRadius: 8,
    padding: '8px 16px',
    cursor: 'pointer',
    fontSize: 14,
    fontWeight: 600
  },
  mediaContainer: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    transition: 'opacity 0.3s ease'
  },
  media: {
    maxWidth: '85vw',
    maxHeight: '75vh',
    objectFit: 'contain',
    borderRadius: 8,
    boxShadow: '0 10px 30px rgba(0, 0, 0, 0.5)'
  },
  info: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 12,
    background: 'rgba(0, 0, 0, 0.7)',
    padding: '12px 20px',
    borderRadius: 8,
    backdropFilter: 'blur(10px)'
  },
  fileName: {
    color: '#fff',
    fontSize: 14,
    fontWeight: 600,
    textAlign: 'center',
    wordBreak: 'break-word'
  },
  actions: {
    display: 'flex',
    gap: 12,
    alignItems: 'center'
  },
  actionBtn: {
    background: 'rgba(255, 255, 255, 0.2)',
    color: '#fff',
    border: 'none',
    borderRadius: 6,
    padding: '6px 12px',
    cursor: 'pointer',
    fontSize: 12,
    fontWeight: 600,
    textDecoration: 'none',
    transition: 'all 0.2s ease',
    display: 'flex',
    alignItems: 'center',
    gap: 4
  }
};

export default Lightbox;
