import { StyleSheet, FlatList, Dimensions, ScrollView } from "react-native";
import {
  useMemo,
  useCallback,
  useState,
  useRef,
  useEffect,
  useLayoutEffect,
} from "react";
import { Tabs, AnimatePresence, YStack, styled, XStack, View } from "tamagui";
import {
  useTeamCalendarStore,
  useTeamAttendanceStore,
  useAppStore,
} from "@/stores";

// 自定义组件
import TeamStatisticsView from "@/components/attendance/teamAttendance/teamStatisticsView";

// UI组件
import CustomText from "@/components/common/CustomText";

// 引入国际化
import { useTranslation } from '@/node_modules/react-i18next';

// 引入屏幕适配
import { wp, sp } from '@/utils/ui/screenUtils';

const MonthMode = (props) => {
  // 标记首次挂载，避免与外层Tab切换动画冲突
  const [enableAnimation, setEnableAnimation] = useState(false);
  useLayoutEffect(() => {
    // 使用微任务延迟，确保首次渲染完成后再启用动画
    Promise.resolve().then(() => setEnableAnimation(true));
  }, []);
  //获取主色
  const primaryColor = useAppStore((s) => s.primary);

  // 按切片订阅：可见年月（需在初始化tabState之前获取）
  const monthVisibleYM = useTeamCalendarStore((s) => s.monthVisibleYM);
  const setMonthVisibleYM = useTeamCalendarStore((s) => s.setMonthVisibleYM);

  // 初始选中月份：以可见月为准（与日/周视图统一），无则回退 1 月
  const initialMonthNo = monthVisibleYM.month || 1;
  const initialCurrentTab = `monthNo${initialMonthNo}`;

  //避免默认到1月导致多一次请求
  const [tabState, setTabState] = useState({
    activeAt: null,
    currentTab: initialCurrentTab,
    prevActiveAt: null,
  });
  //设置当前选中的tab
  const setCurrentTab = (currentTab) =>
    setTabState({ ...tabState, currentTab });
  //设置tab的点击动画效果
  const setActiveIndicator = (activeAt) =>
    setTabState({ ...tabState, prevActiveAt: tabState.activeAt, activeAt });

  const { activeAt, prevActiveAt, currentTab } = tabState;

  // 1 = right, 0 = nowhere, -1 = left
  const direction = (() => {
    if (!activeAt || !prevActiveAt || activeAt.x === prevActiveAt.x) {
      return 0;
    }
    return activeAt.x > prevActiveAt.x ? -1 : 1;
  })();

  // 当前选中的行
  const [activeRowIndex, setActiveRowIndex] = useState(0);

  const handleOnInteraction = useCallback((type, layout, rowIndex) => {
    //手动设置当前选中的行，用于多行tab时下划线动画效果
    setActiveRowIndex(rowIndex);
    if (type === "select") {
      setActiveIndicator(layout);
    }
  });

  // 获取考勤月详情数据
  const fetchTeamAttendanceMonth = useTeamAttendanceStore(
    (s) => s.fetchTeamAttendanceMonth
  );
  // 请求取消控制器，用于避免快速切换月份时的数据竞态
  const abortRef = useRef(null);
  // 读取当前统计模式用于守卫
  const activeStatisticsMode = useTeamAttendanceStore(
    (s) => s.activeStatisticsMode
  );

  // 国际化
  const { t, i18n } = useTranslation('attendance');
  const monthList = useMemo(
    () => Array.from({ length: 12 }, (_, i) => t(`months.${i + 1}`)),
    [i18n.language, t]
  );

  // —— FlatList 分页按"年"为单位（伪无限滑动） ——
  // 动态锚点：以当前可见年为锚点，确保索引总在窗口中间
  const TOTAL_PAGES = 80;
  const BASE_INDEX = Math.floor(TOTAL_PAGES / 2);
  const ANCHOR_YEAR = monthVisibleYM?.year || new Date().getFullYear();
  // 每个"年页"的宽度 = 屏幕宽度 - 左右padding
  const pageWidth = Dimensions.get("window").width - 32;
  // 吸附页宽用于索引计算（与 FlatList 视窗宽一致）
  const snapWidth = props?.visibleWidth || Dimensions.get("window").width;

  // 将分页索引映射为具体的年份（锚点为当前可见年）
  const indexToYear = useCallback(
    (index) => {
      const diff = index - BASE_INDEX;
      return ANCHOR_YEAR + diff;
    },
    [ANCHOR_YEAR, BASE_INDEX]
  );

  // 将具体的年份映射回分页索引（锚点为当前可见年）
  const yearToIndex = useCallback(
    (year) => {
      return BASE_INDEX + (year - ANCHOR_YEAR);
    },
    [ANCHOR_YEAR, BASE_INDEX]
  );

  // 生成总页数（年）
  const pages = useMemo(
    () => Array.from({ length: TOTAL_PAGES }, (_, i) => i),
    []
  );

  const flatListRef = useRef(null);
  const isProgrammaticScrollRef = useRef(false);
  const currentPageIndexRef = useRef(yearToIndex(monthVisibleYM.year));
  // 在年份横滑后，跳过一次"从 store 恢复选择"的逻辑
  const ignoreRestoreRef = useRef(false);

  // 固定宽度项布局（提升 initialScrollIndex/scrollToIndex 稳定性）
  const getItemLayout = useCallback(
    (_, index) => ({ length: pageWidth, offset: pageWidth * index, index }),
    [pageWidth]
  );

  // 跨年滚动时，同步 monthVisibleYM.year，并重置为第一月与第一行（最小钳制 + 视窗宽索引）
  const handleMomentumEnd = useCallback(
    (e) => {
      const offsetX = e?.nativeEvent?.contentOffset?.x || 0;
      const startIndex = currentPageIndexRef.current;
      const nextIndex = Math.round(offsetX / snapWidth);
      if (isProgrammaticScrollRef.current) {
        isProgrammaticScrollRef.current = false;
        return;
      }
      const delta = nextIndex - startIndex;
      const MAX_DELTA = 1;
      const clampedIndex =
        delta > MAX_DELTA
          ? startIndex + MAX_DELTA
          : delta < -MAX_DELTA
          ? startIndex - MAX_DELTA
          : nextIndex;
      if (clampedIndex !== nextIndex && flatListRef.current) {
        isProgrammaticScrollRef.current = true;
        try {
          // 用内容宽对齐像素位置，保持布局不变
          flatListRef.current.scrollToOffset({
            offset: clampedIndex * pageWidth,
            animated: false,
          });
        } catch (_) {}
      }
      currentPageIndexRef.current = clampedIndex;
      const nextYear = indexToYear(clampedIndex);
      if (nextYear !== monthVisibleYM.year) {
        // 跨年时直接重置为 1 月（保持统一的可见月）
        const targetMonth = 1;
        if (
          monthVisibleYM.year !== nextYear ||
          monthVisibleYM.month !== targetMonth
        ) {
          setMonthVisibleYM({ year: nextYear, month: targetMonth });
        }
        // 同步 Tab 与行高亮
        setTabState((prev) => ({
          ...prev,
          currentTab: `monthNo${targetMonth}`,
        }));
        setActiveRowIndex(Math.floor((targetMonth - 1) / 6));
        // 告诉"恢复逻辑"跳过这一次
        ignoreRestoreRef.current = true;
      }
    },
    [
      indexToYear,
      pageWidth,
      snapWidth,
      setMonthVisibleYM,
      monthVisibleYM.year,
      monthVisibleYM.month,
    ]
  );

  // 当可见年份变化（外部触发或内部更新）时，同步 FlatList 定位到对应年份页
  useEffect(() => {
    const targetIndex = yearToIndex(monthVisibleYM.year);
    if (targetIndex !== currentPageIndexRef.current && flatListRef.current) {
      isProgrammaticScrollRef.current = true;
      try {
        flatListRef.current.scrollToIndex({
          index: targetIndex,
          animated: false,
        });
      } catch (err) {
        flatListRef.current.scrollToOffset({
          offset: pageWidth * targetIndex,
          animated: false,
        });
      }
      currentPageIndexRef.current = targetIndex;
    }
  }, [monthVisibleYM.year, yearToIndex, pageWidth]);

  // 根据父组件传入 visibleWidth，按当前页索引×新宽度重对齐，避免出现半页或错位
  useEffect(() => {
    if (!flatListRef.current) return;
    if (!(props?.visibleWidth > 0)) return;
    const targetOffset = currentPageIndexRef.current * pageWidth;
    isProgrammaticScrollRef.current = true;
    try {
      flatListRef.current.scrollToOffset({
        offset: targetOffset,
        animated: false,
      });
    } catch (e) {}
  }, [props?.visibleWidth, pageWidth]);

  //渲染年度页（固定 12 个月）
  const renderYearPage = useCallback(() => {
    //计算生成每行6个元素的数据排列
    const totalRows = Math.ceil(monthList.length / 6);
    const rows = Array.from({ length: totalRows }, (_, rowIndex) => {
      // 直接创建长度为6的数组，不足的部分用null填充，保证最后一行正常显示
      return Array.from({ length: 6 }, (_, colIndex) => {
        const itemIndex = rowIndex * 6 + colIndex;
        return itemIndex < monthList.length ? monthList[itemIndex] : null;
      });
    });
    return (
      <Tabs
        value={currentTab}
        onValueChange={(val) => {
          setCurrentTab(val);
          // 用户点击月份时，同步可见月
          const m = /monthNo(\d+)/.exec(val);
          const monthNo = m ? parseInt(m[1], 10) : 1;
          if (monthVisibleYM.month !== monthNo) {
            setMonthVisibleYM({ year: monthVisibleYM.year, month: monthNo });
          }
        }}
        width={pageWidth}
        flexDirection="column"
        orientation="vertical"
        style={styles.monthTabs}
        gap={wp(12)}
      >
        {rows.map((rowItems, rowIndex) => (
          <YStack key={rowIndex}>
            {activeRowIndex == rowIndex && (
              <AnimatePresence>
                {activeAt && (
                  <TabsRovingIndicator
                    theme="accent"
                    active
                    width={activeAt.width / 2}
                    height={wp(3)}
                    x={activeAt.x + activeAt.width / 4}
                    bottom={activeAt.y}
                  />
                )}
              </AnimatePresence>
            )}
            <Tabs.List disablePassBorderRadius loop={false} paddingBottom={6}>
              <XStack key={rowIndex} style={styles.monthTabRows}>
                {rowItems.map((item, colIndex) => {
                  const itemIndex = rowIndex * 6 + colIndex;
                  return item ? (
                    <Tabs.Tab
                      key={itemIndex}
                      unstyled
                      value={`monthNo${itemIndex + 1}`}
                      onInteraction={(type, layout) =>
                        handleOnInteraction(type, layout, rowIndex)
                      }
                      style={styles.monthTabItem}
                    >
                      <CustomText
                        style={[
                          styles.monthTabItemText,
                          {
                            color:
                              currentTab == `monthNo${itemIndex + 1}`
                                ? primaryColor
                                : "#000",
                          },
                        ]}
                      >
                        {item}
                      </CustomText>
                    </Tabs.Tab>
                  ) : null;
                })}
              </XStack>
            </Tabs.List>
          </YStack>
        ))}
        {enableAnimation ? (
          <AnimatePresence
            exitBeforeEnter
            custom={{ direction }}
            initial={false}
          >
            <AnimatedYStack key={currentTab}>
              <Tabs.Content
                value={currentTab}
                forceMount
                flex={1}
                justifyContent="center"
              >
                <View style={styles.separatorLine} />
                <ScrollView
                  // 隐藏滚动条
                  showsVerticalScrollIndicator={false}
                  // 解决滚动冲突
                  nestedScrollEnabled={true}
                >
                  <TeamStatisticsView />
                </ScrollView>
              </Tabs.Content>
            </AnimatedYStack>
          </AnimatePresence>
        ) : (
          <Tabs.Content
            value={currentTab}
            forceMount
            flex={1}
            justifyContent="center"
          >
            <View style={styles.separatorLine} />
            <ScrollView
              showsVerticalScrollIndicator={false}
              nestedScrollEnabled={true}
            >
              <TeamStatisticsView />
            </ScrollView>
          </Tabs.Content>
        )}
      </Tabs>
    );
  }, [
    currentTab,
    pageWidth,
    primaryColor,
    setCurrentTab,
    activeAt,
    activeRowIndex,
    handleOnInteraction,
    monthVisibleYM.year,
    monthVisibleYM.month,
    setMonthVisibleYM,
    direction,
    enableAnimation,
  ]);

  // 仅在月份 Tab 变化时拉取"考勤月"数据（不再在此写 monthVisibleYM，避免双向循环）
  useEffect(() => {
    const match = /monthNo(\d+)/.exec(currentTab);
    const month = match ? parseInt(match[1], 10) : 1;
    // 模式守卫：仅在“月模式”激活时才触发拉取
    if (activeStatisticsMode !== "month") return;
    if (monthVisibleYM?.year && month) {
      // 取消上一次未完成请求
      if (abortRef.current) {
        abortRef.current.abort();
      }
      const controller = new AbortController();
      abortRef.current = controller;
      const mm = String(month).padStart(2, "0");
      const monthKey = `${monthVisibleYM.year}-${mm}`;
      // 基于考勤月(26-25)构造日期范围，并生成dates数组
      const {
        getAttendanceMonthRange2625,
        getDateRangeInclusive,
      } = require("@/utils/time/dateUtils");
      const range = getAttendanceMonthRange2625(monthVisibleYM.year, month);
      const dates = getDateRangeInclusive(range.startDate, range.endDate);
      fetchTeamAttendanceMonth(
        {
          collectionType: 2,
          dates: dates,
        },
        { signal: controller.signal }
      );
    }
  }, [
    currentTab,
    monthVisibleYM?.year,
    fetchTeamAttendanceMonth,
    activeStatisticsMode,
  ]);

  // 当外部可见月变化（如日视图滑动或切回月视图）时，同步月份 Tab 到当前可见月
  useEffect(() => {
    const m = monthVisibleYM?.month;
    if (!m) return;
    const match = /monthNo(\d+)/.exec(currentTab);
    const currentNo = match ? parseInt(match[1], 10) : 1;
    // 若来自"横滑切换年份"的一次性恢复跳过，则本次不覆盖主动设置的月
    if (ignoreRestoreRef.current) {
      ignoreRestoreRef.current = false;
      return;
    }
    if (currentNo !== m) {
      setTabState((prev) => ({ ...prev, currentTab: `monthNo${m}` }));
      // 高亮正确的行（每行6个）
      setActiveRowIndex(Math.floor((m - 1) / 6));
    }
  }, [monthVisibleYM?.month, monthVisibleYM?.year]);

  useEffect(() => {
    // 组件卸载时，取消在途请求
    return () => {
      if (abortRef.current) abortRef.current.abort();
    };
  }, []);

  // 在切换可见年月时，向父组件上报当月的考勤范围（26-25）
  useEffect(() => {
    if (!props?.onSelectedMonthRange) return;
    const y = monthVisibleYM.year;
    const m = monthVisibleYM.month;
    if (!y || !m) return;
    const { getAttendanceMonthRange2625 } = require("@/utils/time/dateUtils");
    const range = getAttendanceMonthRange2625(y, m);
    props.onSelectedMonthRange(range);
  }, [
    props?.onSelectedMonthRange,
    monthVisibleYM?.year,
    monthVisibleYM?.month,
  ]);

  return (
    <FlatList
      ref={flatListRef}
      //水平方向
      horizontal
      //分页
      pagingEnabled
      //水平滚动条
      showsHorizontalScrollIndicator={false}
      //数据
      data={pages}
      //初始滚动索引：由父容器提供宽度后即可稳定传入
      initialScrollIndex={
        props?.visibleWidth > 0 ? yearToIndex(monthVisibleYM.year) : undefined
      }
      //获取item布局
      getItemLayout={getItemLayout}
      //渲染当前可视区域前后各约 1 倍的屏幕内容，总计约 3 屏的窗口
      windowSize={3}
      //初始渲染数量
      initialNumToRender={1}
      //最大渲染数量
      maxToRenderPerBatch={1}
      //移除子视图
      removeClippedSubviews
      //滚动结束事件（切换年份）
      onMomentumScrollEnd={handleMomentumEnd}
      keyExtractor={(index) => `y-${indexToYear(index)}`}
      renderItem={({ item: index }) => {
        const year = indexToYear(index);
        return renderYearPage({ year });
      }}
    />
  );
};

//tab下划线切换动画效果
const TabsRovingIndicator = ({ active, ...props }) => {
  //获取主色
  const primaryColor = useAppStore((s) => s.primary);
  return (
    <YStack
      position="absolute"
      opacity={0.7}
      animation="medium"
      enterStyle={{
        opacity: 0,
      }}
      exitStyle={{
        opacity: 0,
      }}
      {...(active && {
        backgroundColor: primaryColor,
        opacity: 0.6,
      })}
      {...props}
    />
  );
};

//tab 页选项卡切换动画效果
const AnimatedYStack = styled(YStack, {
  flex: 1,
  x: 0,
  opacity: 1,

  animation: "fast",
  variants: {
    // 1 = right, 0 = nowhere, -1 = left
    direction: {
      ":number": (direction) => ({
        enterStyle: {
          x: direction > 0 ? -wp(25) : wp(25),
          opacity: 0,
        },
        exitStyle: {
          zIndex: 0,
          x: direction < 0 ? -wp(25) : wp(25),
          opacity: 0,
        },
      }),
    },
  },
});

export default MonthMode;

const styles = StyleSheet.create({
  monthTabs: {
    paddingHorizontal: wp(8),
  },
  monthTabRows: {
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: wp(16),
  },
  monthTabItem: {
    justifyContent: "center",
    alignItems: "center",
  },
  monthTabItemText: {
    fontSize: sp(14),
    lineHeight: wp(22),
    fontFamily: "Medium",
    color: "#191919",
    minWidth: wp(44),
    textAlign: "center",
  },
  separatorLine: {
    height: wp(1),
    backgroundColor: "#F8F8F8",
  },
});
