import React, { useCallback, useEffect } from "react";
import {
  FlatList,
  StyleSheet,
  Text,
  RefreshControl,
  ActivityIndicator,
  View,
} from "react-native";
import { colors, spacing } from "@/src/lib/theme";
import { PortfolioNode } from "@/src/components/PortfolioNode";
import { usePortfolioStore } from "@/src/features/portfolio/portfolio.store";
import type { Portfolio } from "@dpf/types";

export default function PortfolioScreen() {
  const { portfolios, isLoading, error, fetchTree } = usePortfolioStore();

  const refresh = useCallback(() => {
    return fetchTree();
  }, [fetchTree]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  return (
    <FlatList<Portfolio>
      style={styles.screen}
      contentContainerStyle={styles.content}
      data={portfolios}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => <PortfolioNode portfolio={item} />}
      refreshControl={
        <RefreshControl
          refreshing={isLoading}
          onRefresh={refresh}
          tintColor={colors.primary}
          colors={[colors.primary]}
        />
      }
      ListHeaderComponent={
        <View>
          <Text style={styles.heading}>Portfolios</Text>
          {error ? (
            <View style={styles.errorBanner}>
              <Text style={styles.errorText}>{error}</Text>
            </View>
          ) : null}
        </View>
      }
      ListEmptyComponent={
        !isLoading ? (
          <Text style={styles.emptyText}>No portfolios found</Text>
        ) : (
          <ActivityIndicator
            size="large"
            color={colors.primary}
            style={styles.loader}
          />
        )
      }
    />
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    backgroundColor: colors.surface1,
  },
  content: {
    paddingBottom: spacing.xl,
  },
  heading: {
    color: colors.text,
    fontSize: 22,
    fontWeight: "700",
    marginHorizontal: spacing.md,
    marginTop: spacing.md,
    marginBottom: spacing.sm,
  },
  errorBanner: {
    backgroundColor: colors.error + "22",
    padding: spacing.md,
    margin: spacing.md,
    borderRadius: 8,
  },
  errorText: {
    color: colors.error,
    fontSize: 13,
    textAlign: "center",
  },
  emptyText: {
    color: colors.textMuted,
    fontSize: 14,
    textAlign: "center",
    marginTop: spacing.lg,
  },
  loader: {
    marginTop: spacing.xl,
  },
});
