import React, { useMemo, useState } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";
import { useSession } from "../state/session-context";
import EmpOverlay from "../components/EmpOverlay";
import { formatTransactionKind, getLocale, useI18n } from "../i18n";
import { useTheme } from "../theme";
import type { AppTheme } from "../theme";
import type { Player, Transaction } from "../shared/types";

function formatMoney(amount: number) {
  const value = new Intl.NumberFormat(getLocale(), {
    maximumFractionDigits: 0,
  }).format(amount);
  return `₦${value}`;
}

function formatTransactionTimestamp(value: number) {
  const date = new Date(value);
  const now = new Date();
  const sameDay =
    date.getFullYear() === now.getFullYear() &&
    date.getMonth() === now.getMonth() &&
    date.getDate() === now.getDate();
  const time = date.toLocaleTimeString(getLocale(), { hour: "2-digit", minute: "2-digit" });
  if (sameDay) return time;
  const day = date.toLocaleDateString(getLocale(), { month: "short", day: "numeric" });
  return `${day} ${time}`;
}

function getTransactionLabel(
  kind: Transaction["kind"],
  note: string | null | undefined,
  t: ReturnType<typeof useI18n>["t"],
): string {
  if (kind === "banker_adjust" || kind === "banker_force_transfer") {
    const trimmed = note?.trim();
    return trimmed || t("common.noReason");
  }
  return formatTransactionKind(kind, t);
}

function getTransactionDisplay(
  transaction: Transaction,
  viewerId: string | null | undefined,
  players: Player[],
  t: ReturnType<typeof useI18n>["t"],
): { label: string; subtitle: string; amount: string; outgoing: boolean } {
  const absAmount = Math.abs(transaction.amount);
  const label = getTransactionLabel(transaction.kind, transaction.note, t);
  const findPlayer = (id: string | null) => players.find((player) => player.id === id);
  const from = findPlayer(transaction.fromId);
  const to = findPlayer(transaction.toId);
  let outgoing = false;
  let counterparty: string = t("common.bank");
  const timeLabel: string = formatTransactionTimestamp(transaction.createdAt);

  if (transaction.kind === "banker_adjust") {
    outgoing = transaction.amount < 0;
    counterparty = t("common.bank");
  } else if (transaction.kind === "transfer" || transaction.kind === "banker_force_transfer") {
    if (viewerId && transaction.fromId === viewerId) {
      outgoing = true;
      counterparty = to?.name ?? t("common.player");
    } else if (viewerId && transaction.toId === viewerId) {
      outgoing = false;
      counterparty = from?.name ?? t("common.player");
    } else {
      outgoing = true;
      counterparty = to?.name ?? t("common.player");
    }
  }

  return {
    label,
    subtitle: viewerId
      ? `${outgoing ? t("common.to") : t("common.from")} ${counterparty} · ${timeLabel}`
      : transaction.kind === "banker_adjust"
      ? outgoing
        ? `${to?.name ?? t("common.player")} → ${t("common.bank")} · ${timeLabel}`
        : `${t("common.bank")} → ${to?.name ?? t("common.player")} · ${timeLabel}`
      : `${from?.name ?? t("common.player")} → ${to?.name ?? t("common.player")} · ${timeLabel}`,
    amount: `${outgoing ? "-" : ""}${formatMoney(absAmount)}`,
    outgoing,
  };
}

export default function PlayerHomeScreen() {
  const manager = useSession();
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const [visibleCount, setVisibleCount] = useState(20);

  if (!manager.session || !manager.me) {
    return (
      <View style={styles.container}>
        <Text style={styles.helper}>{t("common.loading")}</Text>
      </View>
    );
  }

  const myTransactions = manager.session.transactions.filter(
    (tx) => tx.fromId === manager.me?.id || tx.toId === manager.me?.id,
  );
  const visibleTransactions = myTransactions.slice(0, visibleCount);

  const showEmp = manager.session.blackoutActive && !manager.isBanker;

  return (
    <View style={styles.container}>
      <View style={styles.balanceCard}>
        <Text style={styles.balanceLabel}>{t("home.balance")}</Text>
        <Text style={styles.balanceValue}>{formatMoney(manager.me.balance)}</Text>
      </View>

      <Text style={styles.sectionTitle}>{t("home.recent")}</Text>
      <FlatList
        data={visibleTransactions}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.list}
        initialNumToRender={20}
        windowSize={7}
        onEndReachedThreshold={0.4}
        onEndReached={() => {
          if (visibleCount >= myTransactions.length) return;
          setVisibleCount((count) => Math.min(count + 20, myTransactions.length));
        }}
        renderItem={({ item }) => {
          const display = getTransactionDisplay(
            item,
            manager.me?.id,
            manager.session?.players ?? [],
            t,
          );
          return (
            <View style={styles.listItem}>
              <View style={styles.listContent}>
                <Text style={styles.listTitle}>{display.label}</Text>
                <Text style={styles.listSubtitle}>{display.subtitle}</Text>
              </View>
              <Text
                style={[styles.listAmount, display.outgoing ? styles.amountNegative : null]}
              >
                {display.amount}
              </Text>
            </View>
          );
        }}
        ListEmptyComponent={<Text style={styles.helper}>{t("home.noActivity")}</Text>}
      />
      <EmpOverlay
        visible={showEmp}
        reason={manager.session.blackoutReason}
      />
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      padding: 20,
      backgroundColor: theme.colors.background,
      position: "relative",
    },
    balanceCard: {
      backgroundColor: theme.colors.surface,
      borderRadius: 16,
      padding: 18,
      marginBottom: 20,
    },
    balanceLabel: {
      fontSize: 14,
      color: theme.colors.textMuted,
    },
    balanceValue: {
      fontSize: 28,
      fontWeight: "700",
      color: theme.colors.text,
    },
    sectionTitle: {
      fontSize: 16,
      fontWeight: "600",
      marginBottom: 12,
      color: theme.colors.text,
    },
    list: {
      gap: 10,
    },
    listItem: {
      backgroundColor: theme.colors.surface,
      borderRadius: 12,
      padding: 12,
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
    },
    listContent: {
      flex: 1,
      paddingRight: 12,
    },
    listTitle: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    listSubtitle: {
      marginTop: 2,
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    listAmount: {
      fontWeight: "600",
      color: theme.colors.primary,
    },
    amountNegative: {
      color: theme.colors.danger,
    },
    helper: {
      color: theme.colors.textMuted,
    },
  });
