import React, { useMemo } from 'react';
import { View, Text, StyleSheet, FlatList, Pressable, Image } from 'react-native';
import { Ionicons } from "@expo/vector-icons";
import { SafeAreaView } from "react-native-safe-area-context";
import TrackRow from '../components/TrackRow';
import { useLibrary } from '../contexts/LibraryContext';
import { durationFormatter } from '../components/DurationFormatter';
import Header from "../components/Header";

export default function AlbumScreen({ route, navigation }) {
  const { album: routeAlbum } = route.params;
  const { albums, toggleLike, likedTracks } = useLibrary();

  const album = useMemo(
    () => albums.find((a) => a.id === routeAlbum.id) ?? routeAlbum,
    [albums, routeAlbum]
  );

  const likedSet = useMemo(
    () => new Set(likedTracks.map((t) => t.id)),
    [likedTracks]
  );

  return (
    <SafeAreaView style={styles.container}>
      <Pressable onPress={() => navigation.goBack()} style={styles.backBtn}>
        <Text style={styles.backText}>← Back</Text>
      </Pressable>

      <View style={styles.header}>
        {album.cover ? (
          <Image source={album.cover} style={styles.cover} resizeMode="cover" />
        ) : (
          <View style={[styles.cover, styles.coverPlaceholder]}>
            <Ionicons name="musical-notes" size={40} color="#555" />
          </View>
        )}
        <Text style={styles.title}>{album.title}</Text>
        <Text style={styles.artist}>{album.artist}</Text>
        <Text style={styles.meta}>
          {album.date} · {album.label || album.type || ""} · {durationFormatter(album.duration || album.tracks?.reduce((s, t) => s + (t.duration || 0), 0))}
        </Text>
        {album.genres?.length > 0 && (
          <Text style={styles.meta}>{album.genres.join(", ")}</Text>
        )}
      </View>

      <FlatList
        data={album.tracks}
        keyExtractor={(item, index) => item.id ?? index.toString()}
        renderItem={({ item }) => (
          <TrackRow
            title={typeof item === 'string' ? item : item.title}
            artist={item.artists?.length > 0 ? item.artists.join(", ") : album.artist}
            duration={item.duration}
            cover={album.cover}
            onPress={() => {}}
            showHeart={true}
            liked={likedSet.has(item.id)}
            onToggleLike={() => toggleLike(album.id, item.id)}
          />
        )}
        contentContainerStyle={styles.trackList}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
    paddingTop: 24,
    paddingHorizontal: 16,
    paddingBottom: 24,
  },
  backBtn: {
    marginBottom: 8,
    alignSelf: 'flex-start',
  },
  backText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  header: {
    alignItems: 'center',
    marginBottom: 10,
  },
  cover: {
    width: 140,
    height: 140,
    borderRadius: 8,
    marginBottom: 8,
  },
  coverPlaceholder: {
    backgroundColor: '#222',
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    color: '#fff',
    fontSize: 24,
    fontWeight: '700',
    textAlign: 'center',
    marginBottom: 0,
  },
  artist: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '500',
    textAlign: 'center',
    marginTop: 1,
  },
  meta: {
    color: '#cfcfcf',
    fontSize: 12,
    fontWeight: '500',
    textAlign: 'center',
    marginTop: 6,
    marginBottom: 10,
  },
  trackList: {
    width: '100%',
    paddingHorizontal: 4,
    paddingBottom: 180,
  },
});
