import { XStack, YStack } from "tamagui";
import { TouchableOpacity, TouchableWithoutFeedback } from "react-native";
import { useCallback, useMemo } from "react";
import { StyleSheet } from "react-native";
import { wp, sp } from '@/utils/ui/screenUtils';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import { router } from "expo-router";
import dayjs from "dayjs";
//国际化
import { useTranslation } from "@/node_modules/react-i18next";
//自定义文本组件
import CustomText from "@/components/common/CustomText";
//最后更新时间组件
import LastUpdateView from "./lastUpdateView";
//考勤统计store
import { useStatisticsStore, useAppStore } from "@/stores";
//考勤统计、考勤详情数据映射配置
import { ATTENDANCE_DATA_DEF } from "@/constants/attendanceStatus";
//引入考勤模块工具函数
import { buildStatisticsItems } from '@/utils/business/attendanceUtils';

const StatisticsView = () => {
  //获取主色
  const primaryColor = useAppStore((s) => s.primary);

  //国际化
  const { t, i18n } = useTranslation("attendance");
  // 映射国际化文案，仅在语言变化时重算
  const statsConfig = useMemo(
    () =>
      ATTENDANCE_DATA_DEF.map((d) => ({
        ...d,
        label: t(d.labelKey),
        countUnit: t(d.unitKey),
      })),
    // 依赖语言变化
    [i18n.language]
  );

  //从考勤统计store获取统计详情数据
  const statisticsDetail = useStatisticsStore((s) => s.statisticsDetail);
  // 读取接口加载状态与更新时间
  const loadingCount = useStatisticsStore((s) => s.loadingCount);
  const lastUpdateTime = useStatisticsStore((s) => s.lastUpdateTime);
  const isLoading = (loadingCount || 0) > 0;

  // 使用useMemo缓存统计项数据，避免重复计算
  const statisticsViews = useMemo(
    () => buildStatisticsItems(statisticsDetail, statsConfig),
    [statisticsDetail, statsConfig]
  );

  //计算生成每行3个元素的数据排列
  const rows = useMemo(() => {
    const totalRows = Math.ceil(statisticsViews.length / 3);
    return Array.from({ length: totalRows }, (_, rowIndex) => {
      // 直接创建长度为3的数组，不足的部分用null填充，保证最后一行正常显示
      return Array.from({ length: 3 }, (_, colIndex) => {
        const itemIndex = rowIndex * 3 + colIndex;
        return itemIndex < statisticsViews.length
          ? statisticsViews[itemIndex]
          : null;
      });
    });
  }, [statisticsViews]);

  //跳转到统计详情页面
  const toStatisticsDetail = useCallback(() => {
    //加载中阻止跳转
    if (isLoading) return;
    router.push(`/attendance/statisticsDetail`);
  }, [isLoading]);

  return (
    <YStack style={styles.statisticsView}>
      {rows.map((rowItems, rowIndex) => (
        <XStack key={rowIndex} style={styles.statisticsRow}>
          {rowItems.map((item, colIndex) => (
            <YStack
              key={rowIndex * 3 + colIndex}
              style={styles.statisticsItemCol}
            >
              {item ? (
                item.count > 0 ? (
                  <TouchableOpacity
                    onPress={() => toStatisticsDetail(item)}
                    disabled={isLoading}
                  >
                    <YStack style={styles.statisticsItem}>
                      <CustomText
                        style={[
                          styles.statisticsValue,
                          { color: primaryColor },
                        ]}
                      >
                        {item.count}
                      </CustomText>
                      <CustomText
                        style={[styles.statisticsTitle, { color: "#191919" }]}
                      >
                        {item.label}
                      </CustomText>
                    </YStack>
                  </TouchableOpacity>
                ) : (
                  <TouchableWithoutFeedback>
                    <YStack style={styles.statisticsItem}>
                      <CustomText
                        style={[styles.statisticsValue, { color: "#C1C1C1" }]}
                      >
                        {item.count}
                      </CustomText>
                      <CustomText
                        style={[styles.statisticsTitle, { color: "#C1C1C1" }]}
                      >
                        {item.label}
                      </CustomText>
                    </YStack>
                  </TouchableWithoutFeedback>
                )
              ) : (
                <TouchableWithoutFeedback
                  pointerEvents="none"
                  accessible={false}
                  focusable={false}
                  accessibilityElementsHidden
                  importantForAccessibility="no-hide-descendants"
                >
                  <YStack style={styles.statisticsItem}>
                    <CustomText
                      style={[styles.statisticsValue, { opacity: 0 }]}
                    >
                      0
                    </CustomText>
                    <CustomText
                      style={[styles.statisticsTitle, { opacity: 0 }]}
                    >
                      占位
                    </CustomText>
                  </YStack>
                </TouchableWithoutFeedback>
              )}
            </YStack>
          ))}
        </XStack>
      ))}

      {isLoading && (
        <YStack pointerEvents="none" style={styles.overlay}>
          <LoadingSpinner
            size={wp(20)}
            color={primaryColor}
            animating={isLoading}
          />
        </YStack>
      )}

      <LastUpdateView />
    </YStack>
  );
};

export default StatisticsView;

const styles = StyleSheet.create({
  statisticsView: {
    gap: wp(20),
    paddingVertical: wp(16),
    position: "relative",
    minHeight: wp(140),
  },
  statisticsRow: {
    alignItems: "center",
    justifyContent: "space-between",
    flexGrow: 1,
    flexBasis: 0,
  },
  statisticsItemCol: {
    flex: 1,
    minWidth: 0,
  },
  statisticsItem: {
    alignItems: "center",
    justifyContent: "center",
    gap: wp(2),
  },
  statisticsValue: {
    fontSize: sp(22),
    lineHeight: wp(30),
    fontFamily: "Bold",
  },
  statisticsTitle: {
    fontSize: sp(12),
    lineHeight: wp(17),
    fontFamily: "Medium",
  },
  overlay: {
    position: "absolute",
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    backgroundColor: "rgba(255,255,255,0.6)",
    alignItems: "center",
    justifyContent: "center",
    gap: wp(8),
  },
  updateTextContainer: {
    alignItems: "center",
    justifyContent: "center",
  },
  updateText: {
    fontSize: sp(10),
    lineHeight: wp(14),
    color: "#bababa",
    marginTop: wp(6),
  },
});
