import React, { useState, useEffect, useCallback } from 'react';
import { createClient } from 'pexels';

const PEXELS_API_KEY = process.env.REACT_APP_PEXELS_API_KEY;
const client = createClient(PEXELS_API_KEY);

function FullscreenGallery() {
  const [showInput, setShowInput] = useState(false);
  const [query, setQuery] = useState('nature');
  const [tempQuery, setTempQuery] = useState('');
  const [currentImage, setCurrentImage] = useState(null);
  const [orientation, setOrientation] = useState('landscape');

  const fetchRandomImage = useCallback(async () => {
    try {
      const randomPage = Math.floor(Math.random() * 100) + 1;
      const response = await client.photos.search({ 
        query: query, 
        per_page: 1, 
        page: randomPage,
        orientation: orientation
      });
      if (response.photos.length > 0) {
        setCurrentImage(response.photos[0].src.original);
      }
    } catch (error) {
      console.error('Error fetching image:', error);
    }
  }, [query, orientation]);
  
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  };
  

  useEffect(() => {
    fetchRandomImage();
    const interval = setInterval(fetchRandomImage, 3600000); // 1 hour in milliseconds
    return () => clearInterval(interval);
  }, [query, fetchRandomImage]);
  

  const toggleInput = () => setShowInput(!showInput);
  const handleInputChange = (e) => setTempQuery(e.target.value);
  const handleSave = () => {
    setQuery(tempQuery);
    setShowInput(false);
    fetchRandomImage();
    toggleFullscreen();
    console.log('Query updated to:', tempQuery);
  };
  

  return (
    <div style={{
      width: '100vw',
      height: '100vh',
      backgroundImage: `url(${currentImage})`,
      backgroundSize: 'contain',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      backgroundColor: 'black'
    }}>
      <button 
        onClick={toggleInput}
        style={{
          position: 'absolute',
          bottom: '0',
          right: '0',
          width: '100px',
          height: '100px',
          background: 'transparent',
          border: 'none',
          cursor: 'pointer'
        }}
        aria-label="Toggle Fullscreen and Input"
      />
      {showInput && (
        <div style={{
          position: 'absolute',
          bottom: '20px',
          right: '20px',
          background: 'rgba(0, 0, 0, 0.8)',
          padding: '20px',
          borderRadius: '10px',
          boxShadow: '0 4px 6px rgba(0, 0, 0, 0.3)',
          display: 'flex',
          flexDirection: 'column',
          gap: '10px',
          maxWidth: '300px'
        }}>
          <input 
            type="text" 
            value={tempQuery} 
            onChange={handleInputChange} 
            placeholder="Enter new query"
            style={{
              padding: '10px',
              borderRadius: '5px',
              border: '1px solid #ccc',
              fontSize: '16px'
            }}
          />
          <select
            value={orientation}
            onChange={(e) => setOrientation(e.target.value)}
            style={{
              padding: '10px',
              borderRadius: '5px',
              border: '1px solid #ccc',
              fontSize: '16px',
              marginTop: '10px'
            }}
          >
            <option value="landscape">Landscape</option>
            <option value="portrait">Portrait</option>
          </select>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <button 
              onClick={handleSave}
              style={{
                padding: '10px 20px',
                borderRadius: '5px',
                border: 'none',
                background: '#4CAF50',
                color: 'white',
                cursor: 'pointer',
                fontSize: '16px'
              }}
            >
              Save
            </button>
            <button 
            onClick={toggleFullscreen}
            style={{
              padding: '10px 20px',
              borderRadius: '5px',
              border: 'none',
              background: '#2196F3',
              color: 'white',
              cursor: 'pointer',
              fontSize: '16px'
            }}
          >
            Fullscreen
          </button>
            <button 
              onClick={toggleInput}
              style={{
                padding: '10px 20px',
                borderRadius: '5px',
                border: 'none',
                background: '#f44336',
                color: 'white',
                cursor: 'pointer',
                fontSize: '16px'
              }}
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
  
}
  

export default FullscreenGallery;