import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../theme/ThemeContext';
import { useLibraryStore } from '../store/libraryStore';
import { usePlayerControls } from '../hooks/usePlayer';
import { Track } from '../types';

export function SearchScreen() {
  const { colors } = useTheme();
  const { tracks, addTrack } = useLibraryStore();
  const { playTrack } = usePlayerControls();
  const [url, setUrl] = useState('');
  const [searchQuery, setSearchQuery] = useState('');

  // Filter library tracks by search query
  const filteredTracks = searchQuery.trim()
    ? tracks.filter(
        (t) =>
          t.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          t.artist?.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : [];

  const handleAddUrl = async () => {
    const trimmedUrl = url.trim();
    if (!trimmedUrl) {
      Alert.alert('Error', 'Please enter a URL');
      return;
    }

    // Basic URL validation
    if (!trimmedUrl.startsWith('http://') && !trimmedUrl.startsWith('https://')) {
      Alert.alert('Error', 'Please enter a valid URL starting with http:// or https://');
      return;
    }

    // Extract filename from URL for title
    const urlParts = trimmedUrl.split('/');
    const filename = urlParts[urlParts.length - 1].split('?')[0];
    const title = decodeURIComponent(filename.replace(/\.[^/.]+$/, '')) || 'Unknown Track';

    const track: Track = {
      id: trimmedUrl,
      url: trimmedUrl,
      title,
      isLocal: false,
    };

    await addTrack(track);
    setUrl('');

    Alert.alert(
      'Track Added',
      `"${title}" has been added to your library.`,
      [
        { text: 'OK' },
        {
          text: 'Play Now',
          onPress: () => playTrack(track),
        },
      ]
    );
  };

  const handlePlayUrl = async () => {
    const trimmedUrl = url.trim();
    if (!trimmedUrl) {
      Alert.alert('Error', 'Please enter a URL');
      return;
    }

    if (!trimmedUrl.startsWith('http://') && !trimmedUrl.startsWith('https://')) {
      Alert.alert('Error', 'Please enter a valid URL');
      return;
    }

    const urlParts = trimmedUrl.split('/');
    const filename = urlParts[urlParts.length - 1].split('?')[0];
    const title = decodeURIComponent(filename.replace(/\.[^/.]+$/, '')) || 'Unknown Track';

    const track: Track = {
      id: trimmedUrl,
      url: trimmedUrl,
      title,
      isLocal: false,
    };

    playTrack(track);
    setUrl('');
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardView}
      >
        <ScrollView style={styles.scrollView} keyboardShouldPersistTaps="handled">
          <Text style={[styles.title, { color: colors.text }]}>Add Music</Text>

          {/* URL Input Section */}
          <View style={[styles.section, { backgroundColor: colors.surface }]}>
            <Text style={[styles.sectionTitle, { color: colors.text }]}>
              Play from URL
            </Text>
            <Text style={[styles.sectionDescription, { color: colors.textSecondary }]}>
              Paste a direct link to an audio file (MP3, M4A, WAV, etc.)
            </Text>

            <TextInput
              style={[
                styles.input,
                {
                  backgroundColor: colors.surfaceVariant,
                  color: colors.text,
                  borderColor: colors.border,
                },
              ]}
              placeholder="https://example.com/song.mp3"
              placeholderTextColor={colors.textMuted}
              value={url}
              onChangeText={setUrl}
              autoCapitalize="none"
              autoCorrect={false}
              keyboardType="url"
            />

            <View style={styles.buttonRow}>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: colors.surfaceVariant }]}
                onPress={handleAddUrl}
              >
                <Text style={[styles.buttonText, { color: colors.text }]}>
                  Add to Library
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.button, { backgroundColor: colors.primary }]}
                onPress={handlePlayUrl}
              >
                <Text style={[styles.buttonText, { color: '#fff' }]}>
                  Play Now
                </Text>
              </TouchableOpacity>
            </View>
          </View>

          {/* Search Library Section */}
          <View style={[styles.section, { backgroundColor: colors.surface }]}>
            <Text style={[styles.sectionTitle, { color: colors.text }]}>
              Search Library
            </Text>

            <TextInput
              style={[
                styles.input,
                {
                  backgroundColor: colors.surfaceVariant,
                  color: colors.text,
                  borderColor: colors.border,
                },
              ]}
              placeholder="Search tracks..."
              placeholderTextColor={colors.textMuted}
              value={searchQuery}
              onChangeText={setSearchQuery}
            />

            {searchQuery.trim() && (
              <View style={styles.searchResults}>
                {filteredTracks.length === 0 ? (
                  <Text style={[styles.noResults, { color: colors.textMuted }]}>
                    No tracks found
                  </Text>
                ) : (
                  filteredTracks.slice(0, 5).map((track) => (
                    <TouchableOpacity
                      key={track.id}
                      style={[styles.resultItem, { borderBottomColor: colors.border }]}
                      onPress={() => playTrack(track)}
                    >
                      <Text style={[styles.resultTitle, { color: colors.text }]}>
                        {track.title}
                      </Text>
                      <Text style={[styles.resultArtist, { color: colors.textSecondary }]}>
                        {track.artist || 'Unknown Artist'}
                      </Text>
                    </TouchableOpacity>
                  ))
                )}
              </View>
            )}
          </View>

          {/* Tips Section */}
          <View style={[styles.section, { backgroundColor: colors.surface }]}>
            <Text style={[styles.sectionTitle, { color: colors.text }]}>Tips</Text>
            <Text style={[styles.tip, { color: colors.textSecondary }]}>
              {'\u2022'} Direct audio file URLs work best (ending in .mp3, .m4a, etc.)
            </Text>
            <Text style={[styles.tip, { color: colors.textSecondary }]}>
              {'\u2022'} Google Drive: Use "Get shareable link" and replace /view with /uc?export=download
            </Text>
            <Text style={[styles.tip, { color: colors.textSecondary }]}>
              {'\u2022'} Dropbox: Change dl=0 to dl=1 in the URL
            </Text>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardView: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  section: {
    marginHorizontal: 16,
    marginBottom: 16,
    padding: 16,
    borderRadius: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 4,
  },
  sectionDescription: {
    fontSize: 14,
    marginBottom: 12,
  },
  input: {
    height: 48,
    borderRadius: 8,
    paddingHorizontal: 12,
    fontSize: 15,
    borderWidth: 1,
  },
  buttonRow: {
    flexDirection: 'row',
    marginTop: 12,
    gap: 12,
  },
  button: {
    flex: 1,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 15,
    fontWeight: '600',
  },
  searchResults: {
    marginTop: 12,
  },
  resultItem: {
    paddingVertical: 12,
    borderBottomWidth: 1,
  },
  resultTitle: {
    fontSize: 15,
    fontWeight: '500',
  },
  resultArtist: {
    fontSize: 13,
    marginTop: 2,
  },
  noResults: {
    textAlign: 'center',
    paddingVertical: 16,
  },
  tip: {
    fontSize: 13,
    marginTop: 8,
    lineHeight: 18,
  },
});
