import React from "react";
import { StyleSheet, Text, View, TouchableOpacity, FlatList, Alert } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { router, useLocalSearchParams } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import * as Sharing from "expo-sharing";
import { useMedia, resolveMediaUri } from "../../context/MediaContext";
import { useMiniPlayerInset } from "../../hooks/useMiniPlayerInset";

export default function PlaylistDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const { playlists, downloads, removeFromPlaylist, playMedia, activeTrack } =
    useMedia();
  const miniPlayerInset = useMiniPlayerInset();

  const playlist = playlists.find((p) => p.id === id);
  const tracks = playlist
    ? playlist.mediaIds
        .map((mid) => downloads.find((d) => d.id === mid))
        .filter((d): d is NonNullable<typeof d> => Boolean(d))
    : [];

  const handlePlay = async (item: (typeof tracks)[number]) => {
    // Playing from a playlist makes the playlist's own track order the
    // next/previous queue, so shuffle/repeat/skip stay within this playlist.
    // Passing the playlist id keeps the Player screen's filter chip in sync
    // with what's actually playing instead of defaulting to "All", and
    // updates this playlist's lastPlayedAt for the "Recently played" sort.
    await playMedia(item, tracks, playlist?.id);
    router.push("/(tabs)/player");
  };

  const shareFile = async (item: (typeof tracks)[number]) => {
    try {
      const available = await Sharing.isAvailableAsync();
      if (!available) {
        Alert.alert("Not available", "Sharing isn't available on this device.");
        return;
      }
      await Sharing.shareAsync(resolveMediaUri(item.uri));
    } catch (e: any) {
      Alert.alert("Couldn't share file", e?.message || "Unknown error");
    }
  };

  return (
    <SafeAreaView style={styles.container} edges={["top", "left", "right"]}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()}>
          <Ionicons name="chevron-back" size={26} color="#FFF" />
        </TouchableOpacity>
        <Text style={styles.headerTitle} numberOfLines={1}>
          {playlist?.name || "Playlist"}
        </Text>
        <View style={{ width: 26 }} />
      </View>

      <FlatList
        data={tracks}
        keyExtractor={(item) => item.id}
        contentContainerStyle={{ paddingBottom: miniPlayerInset }}
        ListEmptyComponent={
          <Text style={styles.emptyText}>
            No tracks yet. Add some from the Downloads tab.
          </Text>
        }
        renderItem={({ item }) => (
          <TouchableOpacity style={styles.row} onPress={() => handlePlay(item)}>
            <Ionicons
              name={item.type === "video" ? "film-outline" : "musical-notes-outline"}
              size={22}
              color={activeTrack?.id === item.id ? "#1DB954" : "#888"}
            />
            <Text
              style={[
                styles.rowTitle,
                activeTrack?.id === item.id && { color: "#1DB954" },
              ]}
              numberOfLines={1}
            >
              {item.title}
            </Text>
            <TouchableOpacity onPress={() => shareFile(item)} style={{ marginRight: 12 }}>
              <Ionicons name="share-outline" size={19} color="#888" />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => playlist && removeFromPlaylist(playlist.id, item.id)}
            >
              <Ionicons name="remove-circle-outline" size={20} color="#FF5252" />
            </TouchableOpacity>
          </TouchableOpacity>
        )}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#121212", padding: 16 },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 20,
  },
  headerTitle: { color: "#FFF", fontSize: 17, fontWeight: "bold", flex: 1, textAlign: "center" },
  row: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#1E1E1E",
    padding: 12,
    borderRadius: 6,
    marginBottom: 8,
  },
  rowTitle: { color: "#FFF", fontSize: 14, fontWeight: "500", flex: 1, marginLeft: 12 },
  emptyText: { color: "#666", fontSize: 13, textAlign: "center", marginTop: 40 },
});
