import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  useWindowDimensions,
} from "react-native";
import { BottomSheet, RNHostView } from "@expo/ui";
import { Ionicons } from "@expo/vector-icons";
import { useMedia, type MediaItem } from "../context/MediaContext";

interface Props {
  visible: boolean;
  item: MediaItem | null;
  onClose: () => void;
}

export default function PlaylistPickerModal({ visible, item, onClose }: Props) {
  const { playlists, createPlaylist, addToPlaylist, removeFromPlaylist } =
    useMedia();
  const [newName, setNewName] = useState("");
  // The RN subtree hosted inside @expo/ui's BottomSheet doesn't inherit the
  // sheet's SwiftUI width, so it must be given an explicit one to avoid
  // collapsing to its content's intrinsic size.
  const { width: windowWidth } = useWindowDimensions();

  // Keep rendering the last-selected item while the sheet animates closed.
  // `item` goes null the instant `onClose` fires (same tick `visible` flips
  // false), and unmounting this content immediately yanks it out from under
  // the native sheet's still-playing slide-down animation, which is what
  // caused the flicker on close. Only ever update on a truthy item, so the
  // content stays put through the dismiss animation. (Adjusting state
  // during render, per React's recommended pattern for deriving state from
  // a prop, rather than in an effect.)
  const [displayItem, setDisplayItem] = useState<MediaItem | null>(item);
  if (item && item !== displayItem) {
    setDisplayItem(item);
  }

  if (!displayItem) return null;

  const handleCreate = () => {
    if (!newName.trim()) return;
    createPlaylist(newName);
    setNewName("");
  };

  return (
    <BottomSheet isPresented={visible} onDismiss={onClose}>
      <RNHostView>
      <View style={[styles.sheet, { width: windowWidth - 32 }]}>
        <View style={styles.header}>
          <Text style={styles.title} numberOfLines={1}>
            Add to Playlist · {displayItem.title}
          </Text>
          <TouchableOpacity onPress={onClose}>
            <Ionicons name="close" size={22} color="#FFF" />
          </TouchableOpacity>
        </View>

        <View style={styles.inputRow}>
          <TextInput
            style={styles.input}
            placeholder="New playlist name..."
            placeholderTextColor="#666"
            value={newName}
            onChangeText={setNewName}
            onSubmitEditing={handleCreate}
            returnKeyType="done"
          />
          <TouchableOpacity style={styles.addBtn} onPress={handleCreate}>
            <Ionicons name="add" size={20} color="#FFF" />
          </TouchableOpacity>
        </View>

        <View style={styles.list}>
          {playlists.length === 0 && (
            <Text style={styles.emptyText}>No playlists yet — create one above.</Text>
          )}
          {playlists.map((playlist) => {
            const included = playlist.mediaIds.includes(displayItem.id);
            return (
              <TouchableOpacity
                key={playlist.id}
                style={styles.row}
                onPress={() =>
                  included
                    ? removeFromPlaylist(playlist.id, displayItem.id)
                    : addToPlaylist(playlist.id, displayItem.id)
                }
              >
                <Ionicons
                  name={included ? "checkbox" : "square-outline"}
                  size={20}
                  color={included ? "#1DB954" : "#888"}
                />
                <Text style={styles.rowText}>{playlist.name}</Text>
                <Text style={styles.rowCount}>{playlist.mediaIds.length}</Text>
              </TouchableOpacity>
            );
          })}
        </View>
      </View>
      </RNHostView>
    </BottomSheet>
  );
}

const styles = StyleSheet.create({
  sheet: {
    backgroundColor: "#1E1E1E",
    padding: 16,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 14,
  },
  title: { color: "#FFF", fontSize: 15, fontWeight: "bold", flex: 1, marginRight: 12 },
  inputRow: { flexDirection: "row", marginBottom: 16 },
  input: {
    flex: 1,
    backgroundColor: "#2A2A2A",
    color: "#FFF",
    padding: 12,
    borderRadius: 6,
    marginRight: 8,
  },
  addBtn: {
    backgroundColor: "#1DB954",
    width: 44,
    borderRadius: 6,
    alignItems: "center",
    justifyContent: "center",
  },
  list: {},
  row: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: "#2A2A2A",
  },
  rowText: { color: "#FFF", fontSize: 14, marginLeft: 12, flex: 1 },
  rowCount: { color: "#888", fontSize: 12 },
  emptyText: { color: "#666", fontSize: 13, textAlign: "center", paddingVertical: 20 },
});
