import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Alert,
  ScrollView,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as DocumentPicker from 'expo-document-picker';
import { useTheme } from '../theme/ThemeContext';
import { useLibraryStore } from '../store/libraryStore';
import { TrackList } from '../components/TrackList';
import { Track, Playlist } from '../types';

export function LibraryScreen({ navigation }: any) {
  const { colors } = useTheme();
  const { tracks, playlists, loadLibrary, addTrack, createPlaylist } = useLibraryStore();
  const [activeTab, setActiveTab] = useState<'tracks' | 'playlists'>('tracks');

  useEffect(() => {
    loadLibrary();
  }, []);

  const handleAddLocalFiles = async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: 'audio/*',
        multiple: true,
        copyToCacheDirectory: true,
      });

      if (result.canceled) return;

      for (const file of result.assets) {
        const track: Track = {
          id: file.uri,
          url: file.uri,
          title: file.name.replace(/\.[^/.]+$/, ''), // Remove extension
          isLocal: true,
        };
        await addTrack(track);
      }
    } catch (error) {
      Alert.alert('Error', 'Failed to add files');
    }
  };

  const handleCreatePlaylist = () => {
    Alert.prompt(
      'New Playlist',
      'Enter playlist name:',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Create',
          onPress: async (name?: string) => {
            if (name?.trim()) {
              await createPlaylist(name.trim());
            }
          },
        },
      ],
      'plain-text'
    );
  };

  const handlePlaylistPress = (playlist: Playlist) => {
    navigation.navigate('PlaylistDetail', { playlistId: playlist.id });
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]}>
      <View style={styles.header}>
        <Text style={[styles.title, { color: colors.text }]}>Library</Text>
        <TouchableOpacity
          style={[styles.addButton, { backgroundColor: colors.primary }]}
          onPress={handleAddLocalFiles}
        >
          <Text style={styles.addButtonText}>+ Add Files</Text>
        </TouchableOpacity>
      </View>

      {/* Tabs */}
      <View style={[styles.tabs, { borderBottomColor: colors.border }]}>
        <TouchableOpacity
          style={[
            styles.tab,
            activeTab === 'tracks' && { borderBottomColor: colors.primary },
          ]}
          onPress={() => setActiveTab('tracks')}
        >
          <Text
            style={[
              styles.tabText,
              { color: activeTab === 'tracks' ? colors.primary : colors.textSecondary },
            ]}
          >
            Tracks ({tracks.length})
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[
            styles.tab,
            activeTab === 'playlists' && { borderBottomColor: colors.primary },
          ]}
          onPress={() => setActiveTab('playlists')}
        >
          <Text
            style={[
              styles.tabText,
              { color: activeTab === 'playlists' ? colors.primary : colors.textSecondary },
            ]}
          >
            Playlists ({playlists.length})
          </Text>
        </TouchableOpacity>
      </View>

      {/* Content */}
      {activeTab === 'tracks' ? (
        <TrackList
          tracks={tracks}
          emptyMessage="No tracks yet. Tap '+ Add Files' to add music."
        />
      ) : (
        <ScrollView style={styles.playlistList}>
          {playlists.length === 0 ? (
            <View style={styles.emptyContainer}>
              <Text style={[styles.emptyText, { color: colors.textMuted }]}>
                No playlists yet
              </Text>
              <TouchableOpacity
                style={[styles.createPlaylistButton, { backgroundColor: colors.primary }]}
                onPress={handleCreatePlaylist}
              >
                <Text style={styles.createPlaylistText}>Create Playlist</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <>
              <TouchableOpacity
                style={[styles.playlistItem, { backgroundColor: colors.surface }]}
                onPress={handleCreatePlaylist}
              >
                <View style={[styles.playlistIcon, { backgroundColor: colors.primary }]}>
                  <Text style={styles.playlistIconText}>+</Text>
                </View>
                <Text style={[styles.playlistName, { color: colors.text }]}>
                  Create New Playlist
                </Text>
              </TouchableOpacity>
              {playlists.map((playlist) => (
                <TouchableOpacity
                  key={playlist.id}
                  style={[styles.playlistItem, { backgroundColor: colors.surface }]}
                  onPress={() => handlePlaylistPress(playlist)}
                >
                  <View style={[styles.playlistIcon, { backgroundColor: colors.surfaceVariant }]}>
                    <Text style={[styles.playlistIconText, { color: colors.textMuted }]}>
                      {'\u266B'}
                    </Text>
                  </View>
                  <View style={styles.playlistInfo}>
                    <Text style={[styles.playlistName, { color: colors.text }]}>
                      {playlist.name}
                    </Text>
                    <Text style={[styles.playlistCount, { color: colors.textSecondary }]}>
                      {playlist.trackIds.length} tracks
                    </Text>
                  </View>
                </TouchableOpacity>
              ))}
            </>
          )}
        </ScrollView>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
  },
  addButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
  },
  addButtonText: {
    color: '#fff',
    fontWeight: '600',
  },
  tabs: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    marginBottom: 8,
  },
  tab: {
    flex: 1,
    paddingVertical: 12,
    alignItems: 'center',
    borderBottomWidth: 2,
    borderBottomColor: 'transparent',
  },
  tabText: {
    fontSize: 15,
    fontWeight: '600',
  },
  playlistList: {
    flex: 1,
    paddingHorizontal: 12,
  },
  playlistItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    marginVertical: 4,
    borderRadius: 8,
  },
  playlistIcon: {
    width: 48,
    height: 48,
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  playlistIconText: {
    fontSize: 20,
    color: '#fff',
  },
  playlistInfo: {
    marginLeft: 12,
    flex: 1,
  },
  playlistName: {
    fontSize: 15,
    fontWeight: '500',
  },
  playlistCount: {
    fontSize: 13,
    marginTop: 2,
  },
  emptyContainer: {
    alignItems: 'center',
    paddingVertical: 48,
  },
  emptyText: {
    fontSize: 16,
    marginBottom: 16,
  },
  createPlaylistButton: {
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 24,
  },
  createPlaylistText: {
    color: '#fff',
    fontWeight: '600',
  },
});
