import { ThemedText } from "@/components/themed-text";
import { MatchDetailData, Player } from "@/types/api";
import React from "react";
import { useTranslation } from "react-i18next";
import { StyleSheet, View } from "react-native";

interface LineupsCardProps {
  data: MatchDetailData;
  isDark: boolean;
}

export function LineupsCard({ data, isDark }: LineupsCardProps) {
  const { t } = useTranslation();
  const { match } = data;
  const bgColor = isDark ? "#1C1C1E" : "#FFF";
  const borderColor = isDark ? "#2C2C2E" : "#EEE";

  const players = (match as any).players || null;

  if (!players || (!players.home_team && !players.away_team)) {
    return null;
  }

  // 兼容两种结构：
  // 1) home_team/away_team 直接是球员数组
  // 2) home_team/away_team 是对象，包含 starting_lineups/substitutes/coaches 等
  const getTeamData = (team: any) => {
    const starting: any[] = [];
    const subs: any[] = [];
    let coachName: string | undefined;
    let coachCountry: string | undefined;

    if (!team) {
      return { starting, subs, coachName, coachCountry };
    }

    if (Array.isArray(team)) {
      // 旧结构：直接数组 = 首发
      return { starting: team, subs, coachName, coachCountry };
    }

    if (Array.isArray(team.starting_lineups)) {
      starting.push(...team.starting_lineups);
    }
    if (Array.isArray(team.substitutes)) {
      subs.push(...team.substitutes);
    }
    if (Array.isArray(team.coaches) && team.coaches.length > 0) {
      const c = team.coaches[0];
      coachName = c?.coache || c?.name;
      coachCountry = c?.coache_country || c?.country;
    }

    return { starting, subs, coachName, coachCountry };
  };

  const home = getTeamData(players.home_team);
  const away = getTeamData(players.away_team);

  const hasLineups = home.starting.length > 0 || away.starting.length > 0;

  if (!hasLineups) {
    return null;
  }

  const getPlayerNumber = (p: any, idx: number) =>
    p?.player_number ?? p?.number ?? p?.playerNumber ?? idx + 1;

  const getPlayerName = (p: any) =>
    p?.player_name ?? p?.player ?? p?.name ?? p?.playerName ?? "";

  const getPlayerPosition = (p: any) =>
    p?.position ?? p?.player_type ?? p?.player_position ?? "";

  const splitByPosition = (list: any[]) => {
    const gk: any[] = [];
    const def: any[] = [];
    const mid: any[] = [];
    const fwd: any[] = [];

    list.forEach((p) => {
      const pos = Number(p?.player_position ?? p?.positionCode ?? 0);
      if (pos === 1) {
        gk.push(p);
      } else if (pos >= 2 && pos <= 5) {
        def.push(p);
      } else if (pos >= 6 && pos <= 8) {
        mid.push(p);
      } else if (pos >= 9 && pos <= 11) {
        fwd.push(p);
      } else {
        // 没有合理编号的，放到中场组兜底
        mid.push(p);
      }
    });

    return { gk, def, mid, fwd };
  };

  return (
    <View style={[styles.container, { backgroundColor: bgColor, borderColor }]}>
      <ThemedText style={styles.title}>
        {t("detail.events.lineups")}
      </ThemedText>
      <View style={styles.content}>
        {/* 主队首发 */}
        {home.starting.length > 0 && (
          <View style={styles.teamLineup}>
            <ThemedText style={styles.teamName}>
              {match.eventHomeTeam}
            </ThemedText>
            {(() => {
              const groups = splitByPosition(home.starting.slice(0, 11));
              return (
                <>
                  {groups.gk.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={styles.lineGroupTitle}>
                        {t("detail.events.lineups_goalkeepers")}
                      </ThemedText>
                      {groups.gk.map((player: Player, idx: number) => (
                        <View key={`home-gk-${idx}`} style={styles.playerRow}>
                          <ThemedText style={styles.playerNumber}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                          <ThemedText style={styles.playerName} numberOfLines={1}>
                            {getPlayerName(player)}
                          </ThemedText>
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={styles.playerPosition}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                        </View>
                      ))}
                    </View>
                  )}
                  {groups.def.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={styles.lineGroupTitle}>
                        {t("detail.events.lineups_defenders")}
                      </ThemedText>
                      {groups.def.map((player: Player, idx: number) => (
                        <View key={`home-def-${idx}`} style={styles.playerRow}>
                          <ThemedText style={styles.playerNumber}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                          <ThemedText style={styles.playerName} numberOfLines={1}>
                            {getPlayerName(player)}
                          </ThemedText>
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={styles.playerPosition}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                        </View>
                      ))}
                    </View>
                  )}
                  {groups.mid.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={styles.lineGroupTitle}>
                        {t("detail.events.lineups_midfielders")}
                      </ThemedText>
                      {groups.mid.map((player: Player, idx: number) => (
                        <View key={`home-mid-${idx}`} style={styles.playerRow}>
                          <ThemedText style={styles.playerNumber}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                          <ThemedText style={styles.playerName} numberOfLines={1}>
                            {getPlayerName(player)}
                          </ThemedText>
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={styles.playerPosition}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                        </View>
                      ))}
                    </View>
                  )}
                  {groups.fwd.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={styles.lineGroupTitle}>
                        {t("detail.events.lineups_forwards")}
                      </ThemedText>
                      {groups.fwd.map((player: Player, idx: number) => (
                        <View key={`home-fwd-${idx}`} style={styles.playerRow}>
                          <ThemedText style={styles.playerNumber}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                          <ThemedText style={styles.playerName} numberOfLines={1}>
                            {getPlayerName(player)}
                          </ThemedText>
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={styles.playerPosition}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                        </View>
                      ))}
                    </View>
                  )}
                </>
              );
            })()}

            {home.coachName && (
              <View style={styles.coachRow}>
                <ThemedText style={styles.coachLabel}>
                  {t("detail.events.lineups_coach")}:
                </ThemedText>
                <ThemedText style={styles.coachValue}>
                  {home.coachName}
                  {home.coachCountry ? ` (${home.coachCountry})` : ""}
                </ThemedText>
              </View>
            )}

            {Array.isArray(home.subs) && home.subs.length > 0 && (
              <View style={styles.subsSection}>
                <ThemedText style={styles.subsTitle}>
                  {t("detail.events.lineups_subs")}
                </ThemedText>
                {home.subs.map((p: any, idx: number) => (
                  <View key={`home-sub-${idx}`} style={styles.playerRow}>
                    <ThemedText style={styles.playerNumber}>
                      {getPlayerNumber(p, idx)}
                    </ThemedText>
                    <ThemedText style={styles.playerName} numberOfLines={1}>
                      {getPlayerName(p)}
                    </ThemedText>
                  </View>
                ))}
              </View>
            )}
          </View>
        )}
        {/* 客队首发 */}
        {away.starting.length > 0 && (
          <View style={[styles.teamLineup, { marginTop: 16 }]}>
            <ThemedText style={[styles.teamName, styles.awayTeamName]}>
              {match.eventAwayTeam}
            </ThemedText>
            {(() => {
              const groups = splitByPosition(away.starting.slice(0, 11));
              return (
                <>
                  {groups.gk.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={[styles.lineGroupTitle, styles.awayText]}>
                        {t("detail.events.lineups_goalkeepers")}
                      </ThemedText>
                      {groups.gk.map((player: Player, idx: number) => (
                        <View
                          key={`away-gk-${idx}`}
                          style={[styles.playerRow, styles.awayPlayerRow]}
                        >
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={[styles.playerPosition, styles.awayText]}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                          <ThemedText
                            style={[styles.playerName, styles.awayText]}
                            numberOfLines={1}
                          >
                            {getPlayerName(player)}
                          </ThemedText>
                          <ThemedText style={[styles.playerNumber, styles.awayNumber]}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                        </View>
                      ))}
                    </View>
                  )}
                  {groups.def.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={[styles.lineGroupTitle, styles.awayText]}>
                        {t("detail.events.lineups_defenders")}
                      </ThemedText>
                      {groups.def.map((player: Player, idx: number) => (
                        <View
                          key={`away-def-${idx}`}
                          style={[styles.playerRow, styles.awayPlayerRow]}
                        >
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={[styles.playerPosition, styles.awayText]}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                          <ThemedText
                            style={[styles.playerName, styles.awayText]}
                            numberOfLines={1}
                          >
                            {getPlayerName(player)}
                          </ThemedText>
                          <ThemedText style={[styles.playerNumber, styles.awayNumber]}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                        </View>
                      ))}
                    </View>
                  )}
                  {groups.mid.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={[styles.lineGroupTitle, styles.awayText]}>
                        {t("detail.events.lineups_midfielders")}
                      </ThemedText>
                      {groups.mid.map((player: Player, idx: number) => (
                        <View
                          key={`away-mid-${idx}`}
                          style={[styles.playerRow, styles.awayPlayerRow]}
                        >
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={[styles.playerPosition, styles.awayText]}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                          <ThemedText
                            style={[styles.playerName, styles.awayText]}
                            numberOfLines={1}
                          >
                            {getPlayerName(player)}
                          </ThemedText>
                          <ThemedText style={[styles.playerNumber, styles.awayNumber]}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                        </View>
                      ))}
                    </View>
                  )}
                  {groups.fwd.length > 0 && (
                    <View style={styles.lineGroup}>
                      <ThemedText style={[styles.lineGroupTitle, styles.awayText]}>
                        {t("detail.events.lineups_forwards")}
                      </ThemedText>
                      {groups.fwd.map((player: Player, idx: number) => (
                        <View
                          key={`away-fwd-${idx}`}
                          style={[styles.playerRow, styles.awayPlayerRow]}
                        >
                          {!!getPlayerPosition(player) && (
                            <ThemedText style={[styles.playerPosition, styles.awayText]}>
                              {String(getPlayerPosition(player))}
                            </ThemedText>
                          )}
                          <ThemedText
                            style={[styles.playerName, styles.awayText]}
                            numberOfLines={1}
                          >
                            {getPlayerName(player)}
                          </ThemedText>
                          <ThemedText style={[styles.playerNumber, styles.awayNumber]}>
                            {getPlayerNumber(player, idx)}
                          </ThemedText>
                        </View>
                      ))}
                    </View>
                  )}
                </>
              );
            })()}

            {away.coachName && (
              <View style={styles.coachRow}>
                <ThemedText style={styles.coachLabel}>
                  {t("detail.events.lineups_coach")}:
                </ThemedText>
                <ThemedText style={styles.coachValue}>
                  {away.coachName}
                  {away.coachCountry ? ` (${away.coachCountry})` : ""}
                </ThemedText>
              </View>
            )}

            {Array.isArray(away.subs) && away.subs.length > 0 && (
              <View style={styles.subsSection}>
                <ThemedText style={[styles.subsTitle, styles.awayText]}>
                  {t("detail.events.lineups_subs")}
                </ThemedText>
                {away.subs.map((p: any, idx: number) => (
                  <View
                    key={`away-sub-${idx}`}
                    style={[styles.playerRow, styles.awayPlayerRow]}
                  >
                    <ThemedText style={[styles.playerName, styles.awayText]} numberOfLines={1}>
                      {getPlayerName(p)}
                    </ThemedText>
                    <ThemedText style={[styles.playerNumber, styles.awayNumber]}>
                      {getPlayerNumber(p, idx)}
                    </ThemedText>
                  </View>
                ))}
              </View>
            )}
          </View>
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    margin: 16,
    marginTop: 0,
    borderRadius: 12,
    padding: 16,
    borderWidth: 1,
    elevation: 2,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  title: {
    fontSize: 14,
    fontWeight: "600",
    marginBottom: 14,
    opacity: 0.7,
  },
  content: {
    gap: 6,
  },
  teamLineup: {
    marginTop: 8,
  },
  teamName: {
    fontSize: 13,
    fontWeight: "600",
    marginBottom: 8,
    opacity: 0.8,
  },
  awayTeamName: {
    textAlign: "right",
  },
  playerRow: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 4,
    gap: 8,
  },
  awayPlayerRow: {
    flexDirection: "row",
    justifyContent: "flex-end",
  },
  playerNumber: {
    fontSize: 12,
    fontWeight: "600",
    width: 24,
    textAlign: "center",
    opacity: 0.6,
  },
  playerName: {
    fontSize: 13,
    fontWeight: "500",
    flex: 1,
  },
  playerPosition: {
    fontSize: 11,
    fontWeight: "500",
    opacity: 0.5,
    textTransform: "uppercase",
  },
  awayText: {
    textAlign: "right",
  },
  awayNumber: {
    textAlign: "right",
  },
  // 每条线（守门员/后卫/中场/前锋）的容器
  lineGroup: {
    marginBottom: 8,
  },
  lineGroupTitle: {
    fontSize: 12,
    fontWeight: "600",
    opacity: 0.7,
    marginBottom: 6,
  },
  // 主/客队教练行
  coachRow: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 12,
    gap: 6,
  },
  coachLabel: {
    fontSize: 12,
    opacity: 0.7,
  },
  coachValue: {
    fontSize: 12,
    fontWeight: "500",
  },
  // 替补区
  subsSection: {
    marginTop: 12,
  },
  subsTitle: {
    fontSize: 12,
    opacity: 0.7,
    marginBottom: 6,
  },
});
