import { Box, Button, Flex, Heading, Input, Spinner, Text } from "@chakra-ui/react";
import { useState } from "react";
import { SongList } from "./components/SongList";
import { PlaylistManager } from "./components/PlaylistManager";
import { useXmlParser } from "./hooks/useXmlParser";
import { exportToXml } from "./services/xmlService";
import { api } from "./services/api";
import "./App.css";

export default function RekordboxReader() {
  const { songs, playlists, setPlaylists, handleFileUpload, loading } = useXmlParser();
  const [selectedItem, setSelectedItem] = useState<string | null>("All Songs");

  const handleCreatePlaylist = async (name: string) => {
    const newPlaylist = { name, tracks: [] };
    const updatedPlaylists = [...playlists, newPlaylist];
    const savedPlaylists = await api.savePlaylists(updatedPlaylists);
    setPlaylists(savedPlaylists);
  };

  const handleAddSongToPlaylist = async (songId: string, playlistName: string) => {
    const updatedPlaylists = playlists.map((playlist) =>
      playlist.name === playlistName
        ? { ...playlist, tracks: [...playlist.tracks, songId] }
        : playlist
    );
    const savedPlaylists = await api.savePlaylists(updatedPlaylists);
    setPlaylists(savedPlaylists);
  };

  const handleExport = () => {
    const xmlContent = exportToXml(songs, playlists);
    const blob = new Blob([xmlContent], { type: "application/xml" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "rekordbox_playlists.xml";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  const displayedSongs = selectedItem === "All Songs"
    ? songs
    : songs.filter((song) =>
        playlists.find((p) => p.name === selectedItem)?.tracks.includes(song.id)
      );

  if (loading) {
    return (
      <Flex height="100vh" align="center" justify="center" direction="column" gap={4}>
        <Spinner size="xl" />
        <Text>Loading your library...</Text>
      </Flex>
    );
  }

  return (
    <Box p={5}>
      <Heading mb={4}>Rekordbox Reader</Heading>
      <Input
        type="file"
        accept=".xml"
        onChange={handleFileUpload}
        mb={4}
      />
      <Flex gap={4}>
        <Box w="250px">
          <PlaylistManager
            playlists={playlists}
            selectedItem={selectedItem}
            onPlaylistCreate={handleCreatePlaylist}
            onPlaylistSelect={setSelectedItem}
          />
        </Box>
        <Box flex={1}>
          <SongList
            songs={displayedSongs}
            onAddToPlaylist={handleAddSongToPlaylist}
            playlists={playlists}
          />
        </Box>
      </Flex>
      {songs.length > 0 && (
        <Button onClick={handleExport} mt={4} colorScheme="blue">
          Export XML
        </Button>
      )}
    </Box>
  );
}
