import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Sidebar, Menu, MenuItem, SubMenu } from 'react-pro-sidebar';
import { FaBars, FaHome, FaFolder, FaVideo, FaPlus, FaList, FaTrash } from 'react-icons/fa';
import VideoPlayer from 'react-player';
import './App.css';

const API_BASE_URL = 'http://192.168.2.220:8000';

function App() {
  const [videoPaths, setVideoPaths] = useState([]);
  const [newPath, setNewPath] = useState('');
  const [videos, setVideos] = useState([]);
  const [loading, setLoading] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [selectedVideo, setSelectedVideo] = useState(null);
  const [showPlayerModal, setShowPlayerModal] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // Fetch initial data on component mount
  useEffect(() => {
    fetchVideoPaths();
    fetchVideos();
  }, []);

  const fetchVideoPaths = async () => {
    try {
      const response = await axios.get(`${API_BASE_URL}/video-paths/`);
      setVideoPaths(response.data.paths);
    } catch (error) {
      console.error('Error fetching video paths:', error);
    }
  };

  const fetchVideos = async (search = '') => {
    try {
      const response = await axios.get(`${API_BASE_URL}/videos/`, {
        params: { search: search }
      });
      setVideos(response.data);
    } catch (error) {
      console.error('Error fetching videos:', error);
    }
  };

  // Add a new useEffect to trigger search when searchQuery changes
  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      fetchVideos(searchQuery);
    }, 500); // Debounce for 500ms

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]); // Re-run when searchQuery changes

  const addVideoPath = async () => {
    if (!newPath.trim()) return;
    
    try {
      await axios.post(`${API_BASE_URL}/video-paths/`, null, {
        params: { path: newPath }
      });
      setNewPath('');
      fetchVideoPaths();
    } catch (error) {
      console.error('Error adding video path:', error);
      alert('Error adding video path: ' + (error.response?.data?.detail || error.message));
    }
  };

  const removeVideoPath = async (pathToRemove) => {
    try {
      await axios.delete(`${API_BASE_URL}/video-paths/`, {
        params: { path: pathToRemove }
      });
      fetchVideoPaths(); // Refresh the list of paths
    } catch (error) {
      console.error('Error removing video path:', error);
      alert('Error removing video path: ' + (error.response?.data?.detail || error.message));
    }
  };

  const scanVideos = async () => {
    setLoading(true);
    try {
      const response = await axios.post(`${API_BASE_URL}/scan-videos/`);
      alert(response.data.message); // Show a message from the backend
      fetchVideos(); // Refetch videos after scanning
    } catch (error) {
      console.error('Error scanning videos:', error);
      alert('Error scanning videos: ' + (error.response?.data?.detail || error.message));
    } finally {
      setLoading(false);
    }
  };

  const openVideoPlayer = (video) => {
    console.log('Attempting to open video player for:', video);
    setSelectedVideo(video);
    setShowPlayerModal(true);
  };

  const closeVideoPlayer = () => {
    console.log('Closing video player modal.');
    setShowPlayerModal(false);
    // Delay setting selectedVideo to null to allow for unmount animation if any
    setTimeout(() => setSelectedVideo(null), 300); 
  };

  return (
    <div className={`App ${collapsed ? 'collapsed' : ''}`}>
      <Sidebar collapsed={collapsed} className="app-sidebar">
        <Menu iconShape="square">
          <MenuItem icon={<FaBars />} onClick={() => setCollapsed(!collapsed)}>
            <h2>{collapsed ? '' : 'Video App'}</h2>
          </MenuItem>
          <MenuItem icon={<FaHome />}>Home</MenuItem>
          <SubMenu icon={<FaFolder />} label="Library">
            <div className="path-section">
              <h2>Video Library Paths</h2>
              <div className="path-form">
                <input
                  type="text"
                  value={newPath}
                  onChange={(e) => setNewPath(e.target.value)}
                  placeholder="Enter video directory path"
                  className="path-input"
                />
                <button onClick={addVideoPath} className="add-path-btn">
                  <FaPlus />
                </button>
              </div>
              
              <div className="path-list">
                <h3>Current Paths:</h3>
                {videoPaths.length > 0 ? (
                  <ul>
                    {videoPaths.map((path, index) => (
                      <li key={index}>
                        <FaList /> {path}
                        <button onClick={() => removeVideoPath(path)} className="remove-path-btn">
                          <FaTrash />
                        </button>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p>No video paths added yet</p>
                )}
              </div>
              <button 
                onClick={scanVideos} 
                disabled={loading}
                className="scan-btn-sidebar"
              >
                {loading ? 'Scanning...' : 'Scan Videos'}
              </button>
            </div>
          </SubMenu>
          <MenuItem icon={<FaVideo />}>Videos</MenuItem>
        </Menu>
      </Sidebar>

      <main className="app-main">
        <section className="videos-section">
          <h2>Video Library</h2>
          <div className="search-bar">
            <input
              type="text"
              placeholder="Search videos by title or path..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="search-input"
            />
          </div>
          {videos.length > 0 ? (
            <div className="video-grid">
              {videos.map((video) => (
                <div key={video.id} className="video-card">
                  <div className="video-thumbnail" onClick={() => openVideoPlayer(video)}>
                    <div className="thumbnail-placeholder">▶</div>
                  </div>
                  <div className="video-info">
                    <div className="video-avatar"></div>
                    <div className="video-details">
                      <h3 className="video-title">{video.title}</h3>
                      <p className="video-path">{video.path}</p>
                      <p className="video-size">{(video.size / (1024 * 1024)).toFixed(2)} MB</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p>No videos found. Add paths and scan to see videos.</p>
          )}
        </section>
      </main>

      {showPlayerModal && selectedVideo && (
        <div className="video-player-modal-overlay" onClick={closeVideoPlayer}>
          <div className="video-player-modal-content" onClick={(e) => e.stopPropagation()}>
            <button className="close-player-modal" onClick={closeVideoPlayer}>&times;</button>
            <h3>{selectedVideo.title}</h3>
            <div className="player-wrapper">
              {selectedVideo && (
                <VideoPlayer
                  url={`${API_BASE_URL}/videos/${selectedVideo.id}/stream`}
                  className="react-player"
                  width="100%"
                  height="100%"
                  controls={true}
                  playing={true}
                  // Removed onReady and onError props
                />
              )}
            </div>
            <p>{selectedVideo.path}</p>
          </div>
        </div>
      )}
    </div>
  );
}

export default App;
