import React, { useMemo } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";
import { useSession } from "../state/session-context";
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 BankerDashboardScreen() {
  const manager = useSession();
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);

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

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{t("banker.dashboard.title")}</Text>
      <FlatList
        data={manager.session.transactions.slice(0, 10)}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.list}
        renderItem={({ item }) => {
          const display = getTransactionDisplay(
            item,
            null,
            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>}
      />
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      padding: 20,
      backgroundColor: theme.colors.background,
    },
    title: {
      fontSize: 20,
      fontWeight: "700",
      marginBottom: 16,
      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,
    },
  });
