import React, { useEffect, useMemo, useState } from "react";
import {
  Keyboard,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { useSession } from "../state/session-context";
import { useI18n } from "../i18n";
import { useTheme } from "../theme";
import type { AppTheme } from "../theme";
import EmpOverlay from "../components/EmpOverlay";

function initials(value: string) {
  return value
    .split(" ")
    .filter(Boolean)
    .map((part) => part[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();
}

export default function PlayerTransfersScreen() {
  const manager = useSession();
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const placeholderColor = theme.colors.placeholder;
  const screenshotDraft = manager.screenshot?.transferDraft;
  const [targetId, setTargetId] = useState("");
  const [amount, setAmount] = useState(() => screenshotDraft?.amount ?? "");
  const [note, setNote] = useState(() => screenshotDraft?.note ?? "");
  const [errorText, setErrorText] = useState("");

  const eligible = useMemo(
    () =>
      manager.session?.players.filter(
        (player) => player.role !== "banker" && player.id !== manager.me?.id,
      ) ?? [],
    [manager.session, manager.me?.id],
  );

  useEffect(() => {
    if (!targetId && eligible.length > 0) {
      setTargetId(eligible[0].id);
    }
  }, [eligible, targetId]);

  useEffect(() => {
    if (!screenshotDraft?.targetId) return;
    if (!eligible.some((player) => player.id === screenshotDraft.targetId)) return;
    setTargetId(screenshotDraft.targetId);
  }, [eligible, screenshotDraft?.targetId]);

  useEffect(() => {
    if (!screenshotDraft) return;
    setAmount(screenshotDraft.amount);
    setNote(screenshotDraft.note);
  }, [screenshotDraft]);

  const selectedPlayer = eligible.find((player) => player.id === targetId);
  const quickAmounts = [10, 25, 50, 100];
  const normalizedAmount = amount.replace(",", ".");
  const amountValue = Number(normalizedAmount);
  const canSend = Boolean(targetId) && Number.isFinite(amountValue) && amountValue > 0;
  const showEmp = Boolean(manager.session?.blackoutActive) && !manager.isBanker;

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

  return (
    <View style={styles.wrapper}>
      <ScrollView
        style={styles.scroll}
        contentContainerStyle={styles.container}
        keyboardShouldPersistTaps="handled"
        keyboardDismissMode="on-drag"
      >
        <View style={styles.hero}>
          <Text style={styles.title}>{t("transfers.title")}</Text>
          <Text style={styles.subtitle}>{t("transfers.subtitle")}</Text>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t("transfers.from")}</Text>
          <View style={styles.profileCard}>
            <View style={styles.avatarBadge}>
              <Text style={styles.avatarText}>
                {initials(manager.me.name || t("common.you"))}
              </Text>
            </View>
            <View style={styles.profileMeta}>
              <Text style={styles.profileName}>{manager.me.name || t("common.you")}</Text>
              <Text style={styles.profileSub}>{t("transfers.availableBalance")}</Text>
            </View>
            <View style={styles.balancePill}>
              <Text style={styles.balanceText}>₦{manager.me.balance ?? 0}</Text>
            </View>
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t("transfers.to")}</Text>
          {eligible.length === 0 ? (
            <Text style={styles.helper}>{t("transfers.noPlayers")}</Text>
          ) : (
            <View style={styles.recipientList}>
              {eligible.map((player) => {
                const active = player.id === targetId;
                return (
                  <Pressable
                    key={player.id}
                    onPress={() => setTargetId(player.id)}
                    style={({ pressed }) => [
                      styles.recipientCard,
                      active ? styles.recipientCardActive : null,
                      pressed ? styles.recipientCardPressed : null,
                    ]}
                  >
                    <View style={styles.recipientRow}>
                      <View style={styles.recipientAvatar}>
                        <Text style={styles.recipientInitials}>{initials(player.name)}</Text>
                      </View>
                      <View style={styles.recipientMeta}>
                        <Text style={styles.recipientName}>{player.name}</Text>
                        <Text style={styles.recipientSub}>
                          {player.isDummy ? t("transfers.dummy") : t("transfers.player")}
                        </Text>
                      </View>
                      <View style={[styles.radio, active ? styles.radioActive : null]} />
                    </View>
                  </Pressable>
                );
              })}
            </View>
          )}
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t("transfers.amount")}</Text>
          <View style={styles.amountRow}>
            <Text style={styles.currency}>₦</Text>
            <TextInput
              style={styles.amountInput}
              placeholder="0"
              placeholderTextColor={placeholderColor}
              keyboardType="decimal-pad"
              value={amount}
              onChangeText={(value) => setAmount(value.replace(/[^0-9.,]/g, ""))}
            />
            <TouchableOpacity
              style={styles.dismissButton}
              onPress={() => Keyboard.dismiss()}
              accessibilityRole="button"
            >
              <Text style={styles.dismissButtonText}>{t("common.done")}</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.chipRow}>
            {quickAmounts.map((value) => {
              const active = Number.isFinite(amountValue) && amountValue === value;
              return (
                <Pressable
                  key={value}
                  onPress={() => setAmount(String(value))}
                  style={[styles.chip, active ? styles.chipActive : null]}
                >
                  <Text style={[styles.chipText, active ? styles.chipTextActive : null]}>
                    ₦{value}
                  </Text>
                </Pressable>
              );
            })}
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{t("transfers.note")}</Text>
          <TextInput
            style={styles.noteInput}
            placeholder={t("transfers.notePlaceholder")}
            placeholderTextColor={placeholderColor}
            value={note}
            onChangeText={setNote}
          />
        </View>

        {errorText ? <Text style={styles.error}>{errorText}</Text> : null}

        <View style={styles.summary}>
          <Text style={styles.summaryLabel}>{t("transfers.sending")}</Text>
          <Text style={styles.summaryValue}>
            {canSend
              ? t("transfers.summary", {
                  amount: amountValue,
                  name: selectedPlayer?.name ?? t("common.player"),
                })
              : t("transfers.selectPlayer")}
          </Text>
        </View>

        <TouchableOpacity
          style={[styles.button, !canSend ? styles.buttonDisabled : null]}
          disabled={!canSend}
          onPress={() => {
            if (!targetId || !Number.isFinite(amountValue) || amountValue <= 0) {
              setErrorText(t("transfers.error"));
              return;
            }
            manager.sendMessage({
              type: "transfer",
              sessionId: manager.sessionId,
              playerId: manager.me?.id,
              toPlayerId: targetId,
              amount: amountValue,
              note,
            });
            setErrorText("");
            setAmount("");
            setNote("");
          }}
        >
          <Text style={styles.buttonText}>{t("transfers.send")}</Text>
        </TouchableOpacity>
      </ScrollView>
      <EmpOverlay visible={showEmp} reason={manager.session.blackoutReason} />
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    wrapper: {
      flex: 1,
      position: "relative",
    },
    scroll: {
      flex: 1,
      backgroundColor: theme.colors.background,
    },
    container: {
      padding: 20,
      gap: 18,
      backgroundColor: theme.colors.background,
    },
    hero: {
      gap: 4,
    },
    title: {
      fontSize: 26,
      fontWeight: "700",
      color: theme.colors.text,
    },
    subtitle: {
      color: theme.colors.textMuted,
    },
    section: {
      gap: 10,
    },
    sectionTitle: {
      fontSize: 12,
      fontWeight: "700",
      letterSpacing: 1,
      textTransform: "uppercase",
      color: theme.colors.textMuted,
    },
    profileCard: {
      backgroundColor: theme.colors.brandSurface,
      borderRadius: 18,
      padding: 16,
      flexDirection: "row",
      alignItems: "center",
      gap: 12,
    },
    avatarBadge: {
      width: 44,
      height: 44,
      borderRadius: 16,
      backgroundColor: theme.colors.brandSurfaceAlt,
      alignItems: "center",
      justifyContent: "center",
    },
    avatarText: {
      color: theme.colors.brandTextMuted,
      fontWeight: "700",
    },
    profileMeta: {
      flex: 1,
      gap: 4,
    },
    profileName: {
      color: theme.colors.brandText,
      fontSize: 16,
      fontWeight: "600",
    },
    profileSub: {
      color: theme.colors.brandTextMuted,
      fontSize: 12,
    },
    balancePill: {
      backgroundColor: theme.colors.brandAccent,
      paddingHorizontal: 10,
      paddingVertical: 6,
      borderRadius: 999,
    },
    balanceText: {
      color: theme.colors.brandAccentText,
      fontWeight: "700",
      fontSize: 12,
    },
    recipientList: {
      gap: 10,
    },
    recipientCard: {
      backgroundColor: theme.colors.surface,
      borderRadius: 16,
      padding: 12,
      borderWidth: 1,
      borderColor: theme.colors.borderMuted,
    },
    recipientCardActive: {
      borderColor: theme.colors.accent,
      backgroundColor: theme.colors.accentSurface,
    },
    recipientCardPressed: {
      opacity: 0.85,
    },
    recipientRow: {
      flexDirection: "row",
      alignItems: "center",
      gap: 12,
    },
    recipientAvatar: {
      width: 40,
      height: 40,
      borderRadius: 14,
      backgroundColor: theme.colors.avatarSurface,
      alignItems: "center",
      justifyContent: "center",
    },
    recipientInitials: {
      color: theme.colors.avatarText,
      fontWeight: "700",
    },
    recipientMeta: {
      flex: 1,
    },
    recipientName: {
      fontSize: 15,
      fontWeight: "600",
      color: theme.colors.text,
    },
    recipientSub: {
      fontSize: 12,
      color: theme.colors.textMuted,
      marginTop: 2,
    },
    radio: {
      width: 16,
      height: 16,
      borderRadius: 8,
      borderWidth: 2,
      borderColor: theme.colors.radioBorder,
    },
    radioActive: {
      borderColor: theme.colors.accent,
      backgroundColor: theme.colors.accent,
    },
    helper: {
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    amountRow: {
      flexDirection: "row",
      alignItems: "center",
      backgroundColor: theme.colors.surface,
      borderRadius: 16,
      borderWidth: 1,
      borderColor: theme.colors.borderMuted,
      paddingHorizontal: 12,
      paddingVertical: 8,
      gap: 8,
    },
    currency: {
      fontSize: 12,
      fontWeight: "700",
      color: theme.colors.text,
    },
    amountInput: {
      flex: 1,
      fontSize: 18,
      fontWeight: "600",
      color: theme.colors.inputText,
    },
    dismissButton: {
      backgroundColor: theme.colors.surfaceAlt,
      paddingVertical: 8,
      paddingHorizontal: 10,
      borderRadius: 10,
      borderWidth: 1,
      borderColor: theme.colors.borderMuted,
    },
    dismissButtonText: {
      fontSize: 12,
      fontWeight: "600",
      color: theme.colors.text,
    },
    chipRow: {
      flexDirection: "row",
      flexWrap: "wrap",
      gap: 8,
    },
    chip: {
      backgroundColor: theme.colors.chipBackground,
      borderRadius: 999,
      borderWidth: 1,
      borderColor: theme.colors.chipBorder,
      paddingHorizontal: 12,
      paddingVertical: 6,
    },
    chipActive: {
      backgroundColor: theme.colors.chipActiveBackground,
      borderColor: theme.colors.chipActiveBackground,
    },
    chipText: {
      fontSize: 12,
      color: theme.colors.chipText,
      fontWeight: "600",
    },
    chipTextActive: {
      color: theme.colors.chipActiveText,
    },
    noteInput: {
      backgroundColor: theme.colors.inputBackground,
      borderRadius: 16,
      borderWidth: 1,
      borderColor: theme.colors.borderMuted,
      color: theme.colors.inputText,
      paddingHorizontal: 12,
      paddingVertical: 10,
    },
    summary: {
      backgroundColor: theme.colors.warningSurface,
      borderRadius: 16,
      padding: 14,
      borderWidth: 1,
      borderColor: theme.colors.warningBorder,
      gap: 6,
    },
    summaryLabel: {
      fontSize: 12,
      textTransform: "uppercase",
      letterSpacing: 1,
      color: theme.colors.warningText,
      fontWeight: "700",
    },
    summaryValue: {
      fontSize: 14,
      fontWeight: "600",
      color: theme.colors.warningTextStrong,
    },
    error: {
      color: theme.colors.danger,
      fontWeight: "600",
    },
    button: {
      backgroundColor: theme.colors.action,
      paddingVertical: 14,
      borderRadius: 999,
      alignItems: "center",
      marginBottom: 16,
    },
    buttonText: {
      color: theme.colors.actionText,
      fontWeight: "700",
      letterSpacing: 0.4,
    },
    buttonDisabled: {
      backgroundColor: theme.colors.tabInactive,
    },
    loading: {
      color: theme.colors.text,
    },
  });
