import { useState, useEffect, useCallback, type ReactNode } from "react";
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  RefreshControl,
} from "react-native";
import { fetchBooks } from "../api/books";
import type { Book, PaginatedResponse } from "@cloud-reader/shared";

export default function LibraryScreen({ navigation }: { navigation: any }): ReactNode {
  const [books, setBooks] = useState<Book[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  const loadBooks = useCallback(async (pageNum: number, isRefresh = false) => {
    try {
      const data: PaginatedResponse<Book> = await fetchBooks(pageNum);
      if (isRefresh) {
        setBooks(data.results);
      } else {
        setBooks((prev) => [...prev, ...data.results]);
      }
      setHasMore(data.next !== null);
      setPage(pageNum);
    } catch {
      // Silent error for now
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    loadBooks(1, true);
  }, [loadBooks]);

  const onRefresh = () => {
    setRefreshing(true);
    loadBooks(1, true);
  };

  const loadMore = () => {
    if (hasMore && !loading) {
      loadBooks(page + 1);
    }
  };

  const renderBook = ({ item }: { item: Book }) => (
    <TouchableOpacity
      style={styles.bookCard}
      onPress={() =>
        navigation.navigate("BookDetail", { bookId: item.id })
      }
    >
      <View style={styles.bookCover}>
        <Text style={styles.coverText}>
          {item.title.charAt(0).toUpperCase()}
        </Text>
      </View>
      <View style={styles.bookInfo}>
        <Text style={styles.bookTitle} numberOfLines={1}>
          {item.title}
        </Text>
        <Text style={styles.bookAuthor} numberOfLines={1}>
          {item.author}
        </Text>
        <Text style={styles.bookPages}>{item.total_pages} pages</Text>
      </View>
    </TouchableOpacity>
  );

  if (loading && books.length === 0) {
    return (
      <View style={styles.centered}>
        <ActivityIndicator size="large" color="#4f8ef7" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={books}
        renderItem={renderBook}
        keyExtractor={(item) => item.id}
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        contentContainerStyle={styles.list}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor="#4f8ef7"
          />
        }
        ListEmptyComponent={
          <View style={styles.centered}>
            <Text style={styles.emptyText}>Your library is empty</Text>
            <Text style={styles.emptySubtext}>
              Add books to get started
            </Text>
          </View>
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#0f0f23",
  },
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 24,
  },
  list: {
    padding: 16,
  },
  bookCard: {
    flexDirection: "row",
    backgroundColor: "#1a1a2e",
    borderRadius: 12,
    padding: 12,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: "#333",
  },
  bookCover: {
    width: 60,
    height: 80,
    backgroundColor: "#2a2a4e",
    borderRadius: 8,
    justifyContent: "center",
    alignItems: "center",
  },
  coverText: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#4f8ef7",
  },
  bookInfo: {
    flex: 1,
    marginLeft: 12,
    justifyContent: "center",
  },
  bookTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: "#fff",
    marginBottom: 4,
  },
  bookAuthor: {
    fontSize: 14,
    color: "#888",
    marginBottom: 4,
  },
  bookPages: {
    fontSize: 12,
    color: "#666",
  },
  emptyText: {
    fontSize: 18,
    fontWeight: "600",
    color: "#888",
    marginBottom: 8,
  },
  emptySubtext: {
    fontSize: 14,
    color: "#666",
  },
});