import {
  Button,
  XStack,
  YStack,
  Text,
  View,
  Card,
  Tabs,
  styled,
  AnimatePresence,
} from "tamagui";
import { StyleSheet } from "react-native";
import { Image as ExpoImage } from "expo-image";
import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { Easing } from "react-native-reanimated";
import {
  useTeamAttendanceStore,
  useTeamCalendarStore,
  useAppStore,
} from "@/stores";

// 自定义组件
import { CustomSafeArea } from "@/components/common/CustomSafeArea";

// UI组件
import DayMode from "@/components/attendance/teamAttendance/dayMode";
import WeekMode from "@/components/attendance/teamAttendance/weekMode";
import MonthMode from "@/components/attendance/teamAttendance/monthMode";
import TabsPager from "@/components/ui/TabsPager";
import TeamDateView from "@/components/attendance/teamAttendance/teamDateView";

// 引入屏幕适配
import { wp } from '@/utils/ui/screenUtils';
// 国际化
import { useTranslation } from "react-i18next";

// 胶囊高度
const segmentHeight = wp(34);
// 胶囊之间的间距
const GAP = wp(10);
// 统一动画配置（UI 线程）
const TAB_TIMING = { duration: 240, easing: Easing.out(Easing.cubic) };

const TeamAttendance = ({ preserveStateOnUnmount = false } = {}) => {
  // 获取主色
  const primaryColor = useAppStore((s) => s.primary);

  // 国际化
  const { t } = useTranslation("attendance");

  // 当前激活的索引
  const [activeIndex, setActiveIndex] = useState(0);
  // 设置团队统计模式
  const setActiveStatisticsMode = useTeamAttendanceStore(
    (s) => s.setActiveStatisticsMode
  );
  const activeStatisticsMode = useTeamAttendanceStore(
    (s) => s.activeStatisticsMode
  );

  // 胶囊选项卡
  const tabs = [
    { key: "day", title: t("teamAttendance.dayMode") },
    { key: "week", title: t("teamAttendance.weekMode") },
    { key: "month", title: t("teamAttendance.monthMode") },
  ];

  // 日周月统计卡片tab信息
  const [tabState, setTabState] = useState({
    activeAt: null,
    currentTab: activeStatisticsMode || "day",
    prevActiveAt: null,
  });
  // 设置当前选中的日周月统计卡片tab
  const setCurrentTab = (currentTab) =>
    setTabState({ ...tabState, currentTab });
  const { activeAt, prevActiveAt, currentTab } = tabState;

  // 日周月统计卡片tab选项卡的滑动动画效果
  // 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 handleIndexChange = (i) => {
    setActiveIndex(i);
    const modeKey = tabs?.[i]?.key;
    if (modeKey) {
      setActiveStatisticsMode(modeKey);
      // 手动控制日周月统计卡片的tab切换
      setCurrentTab(modeKey);
    }
  };

  // 页面卸载时重置到“今天”。不在进入时重置，避免进入时改锚点引发竞态
  const resetDayVisibleYMToToday = useTeamCalendarStore(
    (s) => s.resetDayVisibleYMToToday
  );
  const setSelectedDate = useTeamCalendarStore((s) => s.setSelectedDate);

  useEffect(() => {
    // 初始同步 activeIndex 与 store 的模式
    const idx = tabs.findIndex((t) => t.key === activeStatisticsMode);
    if (idx >= 0) setActiveIndex(idx);
  }, []);

  useEffect(() => {
    return () => {
      if (!preserveStateOnUnmount) {
        const now = new Date();
        const y = now.getFullYear();
        const m = String(now.getMonth() + 1).padStart(2, "0");
        const d = String(now.getDate()).padStart(2, "0");
        // 先对齐可见年月，再高亮当天，避免中间态
        resetDayVisibleYMToToday();
        setSelectedDate(`${y}-${m}-${d}`);
      }
    };
  }, [resetDayVisibleYMToToday, setSelectedDate, preserveStateOnUnmount]);

  // 状态管理选中的日期范围信息
  const [selectedDateRange, setSelectedDateRange] = useState(null);

  // 处理周视图传递的日期范围信息
  const handleSelectedWeekRange = useCallback((range) => {
    setSelectedDateRange(range);
  }, []);

  // 处理月视图传递的日期范围信息
  const handleSelectedMonthRange = useCallback((range) => {
    setSelectedDateRange(range);
  }, []);

  // 请求节流/防抖，中止过时请求
  const abortRef = useRef(null);
  const debounceTimer = useRef(null);

  const triggerFetch = useCallback(() => {
    // 取消上一次未完成请求
    if (abortRef.current) {
      abortRef.current.abort();
    }
    const controller = new AbortController();
    abortRef.current = controller;
    if (currentTab === "day") {
      // 由 DayMode 组件内部负责触发日模式拉取，这里不再直接调用，避免与组件内逻辑冲突
      return;
    }
  }, [currentTab]);

  useEffect(() => {
    // 简单防抖：在月度切换时合并抖动（如快速滑动、动画期间多次触发）
    if (debounceTimer.current) clearTimeout(debounceTimer.current);
    debounceTimer.current = setTimeout(() => {
      triggerFetch();
    }, 120);
    return () => {
      if (debounceTimer.current) clearTimeout(debounceTimer.current);
    };
  }, [triggerFetch]);

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

  // 统一测量内容区域的可视宽度（传递给周/月，避免各自重复测量导致的闪烁）
  const [contentWidth, setContentWidth] = useState(0);

  return (
    <View flex={1}>
      <ExpoImage
        source={require("@/assets/images/backgrounds/home-bg.webp")}
        style={StyleSheet.absoluteFill}
        contentFit="cover"
        transition={0}
        pointerEvents="none"
        cachePolicy="memory-disk"
      />
      <CustomSafeArea style={{ flex: 1 }}>
        <View
          style={[
            styles.tabsPagerContainer,
            { height: segmentHeight + GAP * 2 },
          ]}
        >
          <TabsPager
            tabs={tabs}
            activeIndex={activeIndex}
            onIndexChange={handleIndexChange}
            primaryColor={primaryColor}
            height={segmentHeight}
            gap={GAP}
            timing={TAB_TIMING}
            gestureEnabled={false}
          />
        </View>

        <Tabs flex={1} value={currentTab} onValueChange={setCurrentTab}>
          <YStack style={styles.teamAttendanceContainer}>
            <Card flex={1}>
              <AnimatePresence
                exitBeforeEnter
                custom={{ direction }}
                initial={false}
              >
                <AnimatedYStack key={currentTab}>
                  <Tabs.Content
                    value={currentTab}
                    forceMount
                    flex={1}
                    justifyContent="center"
                  >
                    <YStack
                      flex={1}
                      onLayout={(e) => {
                        const w = Math.round(
                          e?.nativeEvent?.layout?.width || 0
                        );
                        if (w && w !== contentWidth) setContentWidth(w);
                      }}
                    >
                      <TeamDateView
                        currentTab={currentTab}
                        selectedDateRange={selectedDateRange}
                      />
                      {currentTab == "day" && <DayMode />}
                      {currentTab == "week" && contentWidth > 0 && (
                        <WeekMode
                          visibleWidth={contentWidth}
                          onSelectedWeekRange={handleSelectedWeekRange}
                        />
                      )}
                      {currentTab == "month" && contentWidth > 0 && (
                        <MonthMode
                          visibleWidth={contentWidth}
                          onSelectedMonthRange={handleSelectedMonthRange}
                        />
                      )}
                    </YStack>
                  </Tabs.Content>
                </AnimatedYStack>
              </AnimatePresence>
            </Card>
          </YStack>
        </Tabs>
      </CustomSafeArea>
    </View>
  );
};

export default TeamAttendance;

//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,
        },
      }),
    },
  },
});

const styles = StyleSheet.create({
  tabsPagerContainer: {
    paddingVertical: wp(10),
  },
  teamAttendanceContainer: {
    flex: 1,
    paddingHorizontal: 16,
    gap: wp(10),
  },
});
