import { ThemedText } from "@/components/themed-text";
import { IconSymbol } from "@/components/ui/icon-symbol";
import { LiveScoreMatch } from "@/types/api";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router";
import React from "react";
import { Image, StyleSheet, TouchableOpacity, View } from "react-native";

interface LiveScoreHeaderProps {
  match: LiveScoreMatch;
  topInset: number;
}

export function LiveScoreHeader({ match, topInset }: LiveScoreHeaderProps) {
  const router = useRouter();

  const parseMin = (t: string) => parseInt(t?.match(/(\d+)/)?.[1] || "0");

  // 解析初始时间逻辑：(event_status 分钟 - event_time 分钟) : event_time 秒
  const getInitialTime = () => {
    const statusIdx = parseInt(match.event_status) || 0;
    const timeParts = match.event_time?.split(":") || [];
    const tMin = parseInt(timeParts[0]) || 0;
    const tSec = parseInt(timeParts[1]) || 0;

    // 如果 event_status 是纯数字分钟数
    if (!isNaN(statusIdx) && /^\d+$/.test(match.event_status)) {
      return { min: Math.max(0, statusIdx - tMin), sec: tSec };
    }
    // 回退到解析 event_time 中的数字
    return { min: tMin || parseMin(match.event_time), sec: tSec };
  };

  const initial = getInitialTime();
  const [minutes, setMinutes] = React.useState(initial.min);
  const [seconds, setSeconds] = React.useState(initial.sec);
  const lastServerMatchRef = React.useRef(
    `${match.event_status}-${match.event_time}`
  );

  // 服务器时间同步
  React.useEffect(() => {
    const currentKey = `${match.event_status}-${match.event_time}`;
    if (currentKey !== lastServerMatchRef.current) {
      const updated = getInitialTime();
      setMinutes(updated.min);
      setSeconds(updated.sec);
      lastServerMatchRef.current = currentKey;
    }
  }, [match.event_time, match.event_status]);

  // 本地秒级自增计时器
  React.useEffect(() => {
    const status = match.event_status?.toLowerCase() || "";
    const isLive =
      String(match.event_live) === "1" ||
      status.includes("live") ||
      status.includes("play") ||
      /^[12][h]$/.test(status) ||
      (parseInt(status) > 0 && parseInt(status) < 120);

    if (!isLive || status.includes("ht") || status.includes("half")) return;

    const interval = setInterval(() => {
      setSeconds((prevSeconds) => {
        if (prevSeconds >= 59) {
          setMinutes((prevMinutes) => prevMinutes + 1);
          return 0;
        }
        return prevSeconds + 1;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [match.event_key, match.event_live, match.event_status]);

  const displayTime = `${minutes}:${seconds.toString().padStart(2, "0")}`;

  return (
    <LinearGradient
      colors={["#521e10", "#0e0e10"]}
      start={{ x: 0, y: 0 }}
      end={{ x: 1, y: 1 }}
      style={[styles.container, { paddingTop: Math.max(topInset, 10) }]}
    >
      {/* Top Bar */}
      <View style={styles.topBar}>
        <View style={styles.leftContainer}>
          <TouchableOpacity
            onPress={() => router.back()}
            style={styles.iconBtn}
          >
            <IconSymbol name="chevron-back" size={28} color="#FFF" />
          </TouchableOpacity>
        </View>

        <View style={styles.statusContainer}>
          <ThemedText style={styles.statusText}>
            {match.event_status || "Live"}
          </ThemedText>
        </View>

        <View style={styles.rightActions}>
          <TouchableOpacity style={styles.iconBtn}>
            <IconSymbol name="notifications-outline" size={24} color="#FFF" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.iconBtn}>
            <IconSymbol name="star-outline" size={24} color="#FFF" />
          </TouchableOpacity>
        </View>
      </View>

      {/* Score Section */}
      <View style={styles.scoreRow}>
        <View style={styles.teamInfo}>
          <View style={styles.logoContainer}>
            <Image
              source={{ uri: match.home_team_logo }}
              style={styles.teamLogo}
            />
          </View>
          <ThemedText style={styles.teamName} numberOfLines={2}>
            {match.event_home_team}
          </ThemedText>
        </View>

        <View style={styles.centerScore}>
          <View style={styles.scoreBox}>
            <ThemedText style={styles.scoreValue}>
              {match.event_final_result?.replace(" - ", "-") || "0-0"}
            </ThemedText>
          </View>

          <View style={styles.timeInfoRow}>
            {match.event_status && (
              <ThemedText style={styles.statusLabel}>
                {match.event_status}
              </ThemedText>
            )}
            <ThemedText style={styles.timeText}>{displayTime}</ThemedText>
          </View>

          {match.goalscorers && match.goalscorers.length > 0 && (
            <View style={styles.lastGoalContainer}>
              <IconSymbol name="football-outline" size={12} color="#FFF" />
              <ThemedText style={styles.lastGoalText}>
                {match.goalscorers[match.goalscorers.length - 1].home_scorer ||
                  match.goalscorers[match.goalscorers.length - 1].away_scorer}
              </ThemedText>
            </View>
          )}
        </View>

        <View style={styles.teamInfo}>
          <View style={styles.logoContainer}>
            <Image
              source={{ uri: match.away_team_logo }}
              style={styles.teamLogo}
            />
          </View>
          <ThemedText style={styles.teamName} numberOfLines={2}>
            {match.event_away_team}
          </ThemedText>
        </View>
      </View>
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  container: {
    paddingBottom: 24,
  },
  topBar: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    marginBottom: 20,
  },
  leftContainer: {
    width: 60,
  },
  rightActions: {
    flexDirection: "row",
    justifyContent: "flex-end",
    width: 80,
  },
  iconBtn: {
    padding: 6,
    marginLeft: 4,
  },
  statusContainer: {
    backgroundColor: "rgba(255,255,255,0.1)",
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 12,
  },
  statusText: {
    color: "#FFF",
    fontWeight: "600",
    fontSize: 14,
  },
  scoreRow: {
    flexDirection: "row",
    alignItems: "flex-start",
    justifyContent: "space-between",
    paddingHorizontal: 24,
  },
  teamInfo: {
    alignItems: "center",
    width: "30%",
  },
  logoContainer: {
    width: 70,
    height: 70,
    marginBottom: 10,
    justifyContent: "center",
    alignItems: "center",
  },
  teamLogo: {
    width: 60,
    height: 60,
    resizeMode: "contain",
  },
  teamName: {
    color: "#FFF",
    fontSize: 14,
    fontWeight: "700",
    textAlign: "center",
    lineHeight: 18,
  },
  centerScore: {
    alignItems: "center",
    justifyContent: "center",
    width: "40%",
    paddingTop: 10,
  },
  scoreBox: {
    backgroundColor: "#FFF",
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 14,
    marginBottom: 8,
    minWidth: 100,
    alignItems: "center",
  },
  scoreValue: {
    color: "#000",
    fontSize: 30,
    fontWeight: "700",
    lineHeight: 30,
    letterSpacing: 1,
  },
  timeText: {
    color: "#FF4444",
    fontWeight: "700",
    fontSize: 14,
  },
  timeInfoRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  statusLabel: {
    color: "#FFF",
    fontWeight: "700",
    fontSize: 14,
    marginRight: 6,
  },
  lastGoalContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 4,
    opacity: 0.9,
  },
  lastGoalText: {
    color: "#FFF",
    fontSize: 10,
    marginLeft: 4,
  },
});
