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

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

// 解析足球比分字符串，例如 "2 - 1" 或 "1-0"
function parseFootballScore(scoreString: string): number[] {
  if (!scoreString || scoreString === "-" || scoreString.trim() === "") return [0, 0];
  // 处理 "2 - 1" 或 "2-1" 格式
  const parts = scoreString.replace(/\s+/g, "").split("-");
  if (parts.length === 2) {
    return [parseInt(parts[0]) || 0, parseInt(parts[1]) || 0];
  }
  return [0, 0];
}

export function FootballScoreTable({ data, isDark }: FootballScoreTableProps) {
  const { t } = useTranslation();
  const { match } = data;
  const bgColor = isDark ? "#1C1C1E" : "#FFF";
  const headerTextColor = isDark ? "#666" : "#999";

  // 解析各种比分
  const finalScore = parseFootballScore(match.eventFinalResult || "-");
  const halftimeScore = parseFootballScore(match.eventHalftimeResult || "-");
  const ftScore = parseFootballScore(match.eventFtResult || "-");
  const penaltyScore = parseFootballScore(match.eventPenaltyResult || "-");

  // 判断是否有加时赛或点球
  const hasExtraTime = ftScore[0] !== finalScore[0] || ftScore[1] !== finalScore[1];
  const hasPenalty = penaltyScore[0] > 0 || penaltyScore[1] > 0;

  // 动态生成表头
  const headers = [t("detail.score_table.team")];
  if (hasPenalty) {
    headers.push(t("detail.score_table.penalty"));
  }
  if (hasExtraTime) {
    headers.push(t("detail.score_table.extra_time"));
  }
  headers.push(t("detail.score_table.full_time"));
  headers.push(t("detail.score_table.halftime"));

  const rows = [
    {
      logo: match.homeTeamLogo,
      name: match.eventHomeTeam,
      penalty: hasPenalty ? penaltyScore[0] : null,
      extraTime: hasExtraTime ? finalScore[0] : null,
      fullTime: hasExtraTime ? ftScore[0] : finalScore[0],
      halftime: halftimeScore[0],
    },
    {
      logo: match.awayTeamLogo,
      name: match.eventAwayTeam,
      penalty: hasPenalty ? penaltyScore[1] : null,
      extraTime: hasExtraTime ? finalScore[1] : null,
      fullTime: hasExtraTime ? ftScore[1] : finalScore[1],
      halftime: halftimeScore[1],
    },
  ];

  return (
    <View style={[styles.container, { backgroundColor: bgColor }]}>
      <View style={styles.header}>
        {headers.map((h, i) => (
          <ThemedText
            key={h}
            style={[
              styles.headerText,
              {
                color: headerTextColor,
                flex: i === 0 ? 3 : 1,
                textAlign: i === 0 ? "left" : "center",
              },
            ]}
          >
            {h}
          </ThemedText>
        ))}
      </View>

      {rows.map((row, idx) => (
        <View key={idx} style={[styles.row, idx === 0 && styles.rowBorder]}>
          <View style={styles.teamCell}>
            <Image source={{ uri: row.logo }} style={styles.teamLogo} />
            <ThemedText style={styles.teamName} numberOfLines={1}>
              {row.name}
            </ThemedText>
          </View>
          {hasPenalty && (
            <ThemedText style={styles.cellText}>
              {row.penalty !== null ? row.penalty : "-"}
            </ThemedText>
          )}
          {hasExtraTime && (
            <ThemedText style={styles.cellText}>
              {row.extraTime !== null ? row.extraTime : "-"}
            </ThemedText>
          )}
          <ThemedText style={styles.cellText}>{row.fullTime}</ThemedText>
          <ThemedText style={styles.cellText}>{row.halftime}</ThemedText>
        </View>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    margin: 16,
    borderRadius: 12,
    padding: 16,
    elevation: 2,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  header: {
    flexDirection: "row",
    paddingBottom: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: "rgba(150,150,150,0.2)",
  },
  headerText: {
    fontSize: 12,
    fontWeight: "500",
  },
  row: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 12,
  },
  rowBorder: {
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: "rgba(150,150,150,0.1)",
  },
  teamCell: {
    flex: 3,
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  teamLogo: {
    width: 24,
    height: 24,
    resizeMode: "contain",
  },
  teamName: {
    flex: 1,
    fontSize: 14,
    fontWeight: "500",
  },
  cellText: {
    flex: 1,
    textAlign: "center",
    fontSize: 14,
    fontWeight: "500",
  },
});
