import React, { useState, useEffect, useCallback } from 'react';
import SongTable from './SongTable';
import NowPlaying from './NowPlaying';
import AddSongPanel from './AddSongPanel';
import { TabView, Tab } from './TabView';
import { API, getDisplayTitle, PlaylistItem } from '../api/player';
import { useEventWebSocket } from '../hooks/useEventWebsocket';
import { FaMusic, FaHeart } from 'react-icons/fa';

enum Tabs {
  Playlist = "playlist",
  Favorites = "favorites",
}

const EmptyContent: React.FC<{ label: string}> = ({label}) => (
  <div className="flex items-center justify-center h-full">
    <div className="text-white text-2xl font-bold">{label}</div>
  </div>
);

const App: React.FC = () => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [nowPlayingSong, setNowPlayingSong] = useState<string | null>(null);
  const [nowPlayingFileName, setNowPlayingFileName] = useState<string | null>(null);
  const [volume, setVolume] = useState(100);
  const [volumeSettingIsLocked, setVolumeSettingIsLocked] = useState(false);
  const [songs, setSongs] = useState<PlaylistItem[]>([]);
  const [selectedTab, setSelectedTab] = useState<Tabs>(Tabs.Playlist);

  const fetchPlaylist = useCallback(async () => {
    const playlist = await API.getPlaylist();
    setSongs(playlist);
  }, []);

  const fetchNowPlaying = useCallback(async () => {
    const nowPlaying = await API.getNowPlaying();
    setNowPlayingSong(getDisplayTitle(nowPlaying.playingItem));
    setNowPlayingFileName(nowPlaying.playingItem.filename);
    setIsPlaying(!nowPlaying.isPaused);

    if (!volumeSettingIsLocked) {
      setVolume(nowPlaying.volume);
    }
  }, [volumeSettingIsLocked]);

  const handleAddURL = async (url: string) => {
    const urlToAdd = url.trim();
    if (urlToAdd) {
      await API.addToPlaylist(urlToAdd);
      fetchPlaylist();

      if (!isPlaying) {
        await API.play();
      }
    }
  };

  const handleDelete = (index: number) => {
    setSongs(songs.filter((_, i) => i !== index));
    API.removeFromPlaylist(index);
    fetchPlaylist();
    fetchNowPlaying();
  };

  const handleSkipTo = async (index: number) => {
    const song = songs[index];
    if (song.playing) {
      togglePlayPause();
    } else {
      await API.skipTo(index);
      await API.play();
    }

    fetchNowPlaying();
    fetchPlaylist();
  };

  const togglePlayPause = async () => {
    if (isPlaying) {
      await API.pause();
    } else {
      await API.play();
    }

    fetchNowPlaying();
  };

  const handleSkip = async () => {
    await API.skip();
    fetchNowPlaying();
  };

  const handlePrevious = async () => {
    await API.previous();
    fetchNowPlaying();
  };

  const handleVolumeSettingChange = async (volume: number) => {
    setVolume(volume);
    await API.setVolume(volume);
  };

  const handleWebSocketEvent = useCallback((event: any) => {
    switch (event.event) {
      case 'user_modify':
      case 'end-file':
      case 'playback-restart':
      case 'metadata_update':
        fetchPlaylist();
        fetchNowPlaying();
        break;
    }
  }, [fetchPlaylist, fetchNowPlaying]);

  // Use the hook
  useEventWebSocket(handleWebSocketEvent);

  // Handle visibility changes
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'visible') {
        fetchPlaylist();
        fetchNowPlaying();
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [fetchPlaylist, fetchNowPlaying]);

  // Initial data fetch
  useEffect(() => {
    fetchPlaylist();
    fetchNowPlaying();
  }, [fetchPlaylist, fetchNowPlaying]);

  const playlistContent = (
    songs.length > 0 ? (
      <SongTable 
        songs={songs}
        isPlaying={isPlaying}
        onDelete={handleDelete} 
        onSkipTo={handleSkipTo} 
      />
    ) : (
      <EmptyContent label="Playlist is empty" />
    )
  );

  return (
    <div className="flex items-center justify-center h-screen w-screen bg-black md:py-10">
      <div className="bg-violet-900 w-full md:max-w-2xl h-full md:max-h-xl md:border md:rounded-2xl flex flex-col">
        <NowPlaying 
          className="flex flex-row md:rounded-t-2xl" 
          songName={nowPlayingSong || "(Not Playing)"} 
          fileName={nowPlayingFileName || ""} 
          isPlaying={isPlaying} 
          onPlayPause={togglePlayPause} 
          onSkip={handleSkip} 
          onPrevious={handlePrevious} 
          volume={volume}
          onVolumeSettingChange={handleVolumeSettingChange}
          onVolumeWillChange={() => setVolumeSettingIsLocked(true)}
          onVolumeDidChange={() => setVolumeSettingIsLocked(false)}
        />

        <TabView selectedTab={selectedTab} onTabChange={setSelectedTab}>
          <Tab label="Playlist" identifier={Tabs.Playlist} icon={<FaMusic />}>
            {playlistContent}
          </Tab>
          <Tab label="Favorites" identifier={Tabs.Favorites} icon={<FaHeart />}>
            <EmptyContent label="Favorites are not implemented yet" />
          </Tab>
        </TabView>

        <AddSongPanel onAddURL={handleAddURL} />
      </div>
    </div>
  );
};

export default App;