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

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

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

  // events 可能在 data.events 或 match.events 中
  const events = (data as any).events || (data.match as any).events;
  if (!events || typeof events !== "object") {
    return null;
  }

  // 处理数组格式的 events
  let eventsObj = events;
  if (Array.isArray(events) && events.length > 0) {
    eventsObj = events[0];
  }

  const substitutes = eventsObj?.substitutes || [];
  const filteredSubstitutes = substitutes.filter(
    (sub: SubstituteEvent) => sub.home_scorer || sub.away_scorer || sub.home_assist || sub.away_assist
  );

  if (filteredSubstitutes.length === 0) {
    return null;
  }

  const extractPlayerName = (value: any): string => {
    if (!value) return "";
    if (typeof value === "string") return value;
    if (Array.isArray(value)) {
      if (value.length === 0) return "";
      const firstItem = value[0];
      if (typeof firstItem === "object" && firstItem !== null) {
        return String(firstItem.in || firstItem.out || firstItem.player || "");
      }
      return String(firstItem);
    }
    if (typeof value === "object" && value !== null) {
      return String(value.in || value.out || value.player || "");
    }
    return String(value);
  };

  const renderSubstituteEvent = (sub: SubstituteEvent, index: number) => {
    let playerIn = "";
    let playerOut = "";
    let isHome = false;

    const homeScorerData = (sub as any).home_scorer;
    if (homeScorerData) {
      isHome = true;
      if (typeof homeScorerData === "object" && !Array.isArray(homeScorerData) && "in" in homeScorerData) {
        playerIn = String(homeScorerData.in || "");
        playerOut = String(homeScorerData.out || "");
      } else if (Array.isArray(homeScorerData) && homeScorerData.length > 0) {
        const firstItem = homeScorerData[0];
        if (typeof firstItem === "object" && firstItem !== null && "in" in firstItem) {
          playerIn = String(firstItem.in || "");
          playerOut = String(firstItem.out || "");
        } else {
          playerIn = extractPlayerName(firstItem);
        }
      } else {
        playerIn = extractPlayerName(homeScorerData);
      }
    }

    const awayScorerData = (sub as any).away_scorer;
    if (awayScorerData && !playerIn) {
      isHome = false;
      if (typeof awayScorerData === "object" && !Array.isArray(awayScorerData) && "in" in awayScorerData) {
        playerIn = String(awayScorerData.in || "");
        playerOut = String(awayScorerData.out || "");
      } else if (Array.isArray(awayScorerData) && awayScorerData.length > 0) {
        const firstItem = awayScorerData[0];
        if (typeof firstItem === "object" && firstItem !== null && "in" in firstItem) {
          playerIn = String(firstItem.in || "");
          playerOut = String(firstItem.out || "");
        } else {
          playerIn = extractPlayerName(firstItem);
        }
      } else {
        playerIn = extractPlayerName(awayScorerData);
      }
    }

    if (!playerOut) {
      playerOut = extractPlayerName(sub.home_scorer_out || sub.away_scorer_out || sub.home_assist || sub.away_assist);
    }
    
    return (
      <View key={`sub-${index}`} style={[styles.eventRow, { borderBottomColor: borderColor }]}>
        <View style={styles.eventTime}>
          <ThemedText style={styles.timeText}>
            {sub.time ? `${sub.time}'` : ""}
          </ThemedText>
        </View>
        <View style={[styles.eventContent, isHome ? styles.homeEvent : styles.awayEvent]}>
          <IconSymbol name="swap-horizontal" size={16} color={isDark ? "#2196F3" : "#1976D2"} />
          <View style={styles.substituteContent}>
            {playerOut ? (
              <>
                <ThemedText style={[styles.substituteIn, { color: isDark ? "#4CAF50" : "#2E7D32" }]} numberOfLines={1}>
                  {playerIn}
                </ThemedText>
                <ThemedText style={styles.substituteArrow}>↔</ThemedText>
                <ThemedText style={styles.substituteOut} numberOfLines={1}>
                  {playerOut}
                </ThemedText>
              </>
            ) : (
              <ThemedText style={styles.eventText} numberOfLines={1}>
                {playerIn}
              </ThemedText>
            )}
          </View>
        </View>
      </View>
    );
  };

  return (
    <View style={[styles.container, { backgroundColor: bgColor, borderColor }]}>
      <ThemedText style={styles.title}>
        {t("detail.events.substitutes")}
      </ThemedText>
      <View style={styles.content}>
        {filteredSubstitutes.map((sub: SubstituteEvent, index: number) => renderSubstituteEvent(sub, index))}
      </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: 12,
    opacity: 0.7,
  },
  content: {
    gap: 0,
  },
  eventRow: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 8,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  eventTime: {
    width: 40,
    alignItems: "center",
  },
  timeText: {
    fontSize: 12,
    fontWeight: "500",
    opacity: 0.6,
  },
  eventContent: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
    paddingLeft: 12,
  },
  homeEvent: {
    justifyContent: "flex-start",
  },
  awayEvent: {
    justifyContent: "flex-end",
    flexDirection: "row-reverse",
  },
  eventText: {
    fontSize: 13,
    fontWeight: "500",
    flex: 1,
  },
  substituteContent: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
  },
  substituteIn: {
    fontSize: 13,
    fontWeight: "500",
  },
  substituteArrow: {
    fontSize: 12,
    opacity: 0.5,
  },
  substituteOut: {
    fontSize: 13,
    fontWeight: "500",
    opacity: 0.6,
    textDecorationLine: "line-through",
  },
});
