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 } from 'react-icons/fa';
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);

  // 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 () => {
    try {
      const response = await axios.get(`${API_BASE_URL}/videos/`);
      setVideos(response.data);
    } catch (error) {
      console.error('Error fetching videos:', error);
    }
  };

  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 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);
    }
  };

  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}</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>
          {videos.length > 0 ? (
            <div className="video-grid">
              {videos.map((video) => (
                <div key={video.id} className="video-card">
                  <div className="video-thumbnail">
                    <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>
    </div>
  );
}

export default App;
