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 BasketballScoreTableProps {
  data: MatchDetailData;
  isDark: boolean;
}

export function BasketballScoreTable({
  data,
  isDark,
}: BasketballScoreTableProps) {
  const { t } = useTranslation();
  const { match } = data;
  const bgColor = isDark ? "#1C1C1E" : "#FFF";
  const borderColor = isDark ? "#2C2C2E" : "rgba(0,0,0,0.06)";
  const headerTextColor = isDark ? "#666" : "#999";
  const textColor = isDark ? "#FFF" : "#000";

  // 解析篮球比分 - 从 scores 对象获取四节比分
  const parseBasketballScores = () => {
    const scores = match.scores as any;
    if (!scores || typeof scores !== "object") {
      // 如果没有 scores 对象，尝试从 eventFinalResult 解析
      const finalResult = match.eventFinalResult || "-";
      const matchResult = finalResult.match(/(\d+)\s*[-–]\s*(\d+)/);
      if (matchResult) {
        return {
          home: {
            total: parseInt(matchResult[1], 10),
            q1: 0,
            q2: 0,
            q3: 0,
            q4: 0,
          },
          away: {
            total: parseInt(matchResult[2], 10),
            q1: 0,
            q2: 0,
            q3: 0,
            q4: 0,
          },
        };
      }
      return {
        home: { total: 0, q1: 0, q2: 0, q3: 0, q4: 0 },
        away: { total: 0, q1: 0, q2: 0, q3: 0, q4: 0 },
      };
    }

    const q1 = scores["1stQuarter"]?.[0] || { score_home: "0", score_away: "0" };
    const q2 = scores["2ndQuarter"]?.[0] || { score_home: "0", score_away: "0" };
    const q3 = scores["3rdQuarter"]?.[0] || { score_home: "0", score_away: "0" };
    const q4 = scores["4thQuarter"]?.[0] || { score_home: "0", score_away: "0" };

    const homeQ1 = parseInt(q1.score_home || "0", 10);
    const homeQ2 = parseInt(q2.score_home || "0", 10);
    const homeQ3 = parseInt(q3.score_home || "0", 10);
    const homeQ4 = parseInt(q4.score_home || "0", 10);
    const homeTotal = homeQ1 + homeQ2 + homeQ3 + homeQ4;

    const awayQ1 = parseInt(q1.score_away || "0", 10);
    const awayQ2 = parseInt(q2.score_away || "0", 10);
    const awayQ3 = parseInt(q3.score_away || "0", 10);
    const awayQ4 = parseInt(q4.score_away || "0", 10);
    const awayTotal = awayQ1 + awayQ2 + awayQ3 + awayQ4;

    return {
      home: {
        total: homeTotal,
        q1: homeQ1,
        q2: homeQ2,
        q3: homeQ3,
        q4: homeQ4,
      },
      away: {
        total: awayTotal,
        q1: awayQ1,
        q2: awayQ2,
        q3: awayQ3,
        q4: awayQ4,
      },
    };
  };

  const scoreData = parseBasketballScores();

  const headers = [
    t("detail.score_table.team") || "Team",
    t("detail.score_table.total") || "Total",
    "1",
    "2",
    "3",
    "4",
  ];

  const rows = [
    {
      logo: match.homeTeamLogo,
      name: match.eventHomeTeam,
      total: scoreData.home.total,
      q1: scoreData.home.q1,
      q2: scoreData.home.q2,
      q3: scoreData.home.q3,
      q4: scoreData.home.q4,
    },
    {
      logo: match.awayTeamLogo,
      name: match.eventAwayTeam,
      total: scoreData.away.total,
      q1: scoreData.away.q1,
      q2: scoreData.away.q2,
      q3: scoreData.away.q3,
      q4: scoreData.away.q4,
    },
  ];

  return (
    <View style={[styles.container, { backgroundColor: bgColor, borderColor }]}>
      <View style={[styles.header, { borderBottomColor: borderColor }]}>
        {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 && { borderBottomColor: borderColor, borderBottomWidth: 1 }]}>
          <View style={styles.teamCell}>
            {row.logo && row.logo.trim() !== "" && !row.logo.includes("placehold") ? (
              <Image source={{ uri: row.logo }} style={styles.teamLogo} />
            ) : null}
            <ThemedText style={[styles.teamName, { color: textColor }]} numberOfLines={1}>
              {row.name}
            </ThemedText>
          </View>
          <ThemedText style={[styles.cellText, styles.totalText, { color: textColor }]}>
            {row.total}
          </ThemedText>
          <ThemedText style={[styles.cellText, { color: textColor }]}>{row.q1}</ThemedText>
          <ThemedText style={[styles.cellText, { color: textColor }]}>{row.q2}</ThemedText>
          <ThemedText style={[styles.cellText, { color: textColor }]}>{row.q3}</ThemedText>
          <ThemedText style={[styles.cellText, { color: textColor }]}>{row.q4}</ThemedText>
        </View>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginHorizontal: 16,
    marginTop: 12,
    borderRadius: 16,
    padding: 20,
    borderWidth: 1,
    overflow: "hidden",
  },
  header: {
    flexDirection: "row",
    paddingBottom: 16,
    borderBottomWidth: 1,
  },
  headerText: {
    fontSize: 12,
    fontWeight: "600",
    opacity: 0.8,
  },
  row: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 14,
  },
  teamCell: {
    flex: 3,
    flexDirection: "row",
    alignItems: "center",
    gap: 10,
  },
  teamLogo: {
    width: 28,
    height: 28,
    resizeMode: "contain",
  },
  teamName: {
    flex: 1,
    fontSize: 14,
    fontWeight: "600",
  },
  cellText: {
    flex: 1,
    textAlign: "center",
    fontSize: 14,
    fontWeight: "500",
    opacity: 0.8,
  },
  totalText: {
    fontWeight: "700",
    opacity: 1,
  },
});
