import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { StyleSheet } from "react-native";
import { Image as ExpoImage } from "expo-image";
import {
  Button,
  XStack,
  YStack,
  Text,
  View,
  Card,
  Tabs,
  styled,
  AnimatePresence,
} from "tamagui";
//自定义安全区
import { CustomSafeArea } from "@/components/common/CustomSafeArea";
//自定义导航栏
import { CustomHeader } from "@/components/common/CustomHeader";
//用户信息
import UserInfo from "@/components/attendance/userInfo";
//日期显示
import DateView from "@/components/attendance/dateView";
//考勤规则
import AttendanceRules from "@/components/attendance/attendanceRules";
//日考勤统计
import DayAttendanceStat from "@/components/attendance/dayAttendanceStat";
//周考勤统计
import WeekAttendanceStat from "@/components/attendance/weekAttendanceStat";
//月考勤统计
import MonthAttendanceStat from "@/components/attendance/monthAttendanceStat";
//国际化
import { useTranslation } from "@/node_modules/react-i18next";
//日历可见年月/选中日期 store、考勤统计store
import {
  useCalendarStore,
  useStatisticsStore,
  useAuthStore,
  useTeamAttendanceStore,
  useAppStore,
} from "@/stores";

//自定义文本组件
import CustomText from "@/components/common/CustomText";

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

export default function Attendance({ preserveStateOnUnmount = false } = {}) {
  //获取用户信息
  const userInfo = useAuthStore((state) => state.getUser());

  // 团队考勤权限标记
  const inTeamAttendance = useTeamAttendanceStore((s) => s.inTeamAttendance);

  // 要查看的指定考勤人员信息
  const viewTeamMember = useTeamAttendanceStore((s) => s.viewTeamMember);
  // 根据考勤模式计算正确的用户信息
  const targetStaffUID = useMemo(() => {
    const staffUID =
      inTeamAttendance && viewTeamMember?.staffUID
        ? viewTeamMember.staffUID
        : userInfo?.ID;
    return staffUID ?? userInfo?.ID;
  }, [inTeamAttendance, viewTeamMember?.staffUID, userInfo?.ID]);

  //国际化
  const { t } = useTranslation("attendance");
  const attendanceStatistics = t("pageTitle.attendanceStatistics");
  const day = t("attendanceDimension.day");
  const week = t("attendanceDimension.week");
  const month = t("attendanceDimension.month");
  //获取主色
  const primaryColor = useAppStore((s) => s.primary);

  // 从全局统计 store 读取并写回当前考勤统计模式
  const activeStatisticsMode = useStatisticsStore(
    (s) => s.activeStatisticsMode
  );
  const setActiveStatisticsMode = useStatisticsStore(
    (s) => s.setActiveStatisticsMode
  );

  //tab信息
  const [tabState, setTabState] = useState({
    activeAt: null,
    currentTab: activeStatisticsMode || "day",
    prevActiveAt: null,
  });
  //设置当前选中的tab
  const setCurrentTab = (currentTab) => {
    setTabState({ ...tabState, currentTab });
    setActiveStatisticsMode(currentTab);
  };
  //设置tab的点击动画效果
  const setActiveIndicator = (activeAt) =>
    setTabState({ ...tabState, prevActiveAt: tabState.activeAt, activeAt });
  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;
  })();

  //绑定tab的触发效果
  const handleOnInteraction = (type, layout) => {
    if (type === "select") {
      setActiveIndicator(layout);
    }
  };

  //考勤统计维度
  const attendanceDimension = [
    {
      name: "day",
      label: day,
    },
    {
      name: "week",
      label: week,
    },
    {
      name: "month",
      label: month,
    },
  ];

  // 页面卸载时重置到“今天”。不在进入时重置，避免进入时改锚点引发竞态
  const resetDayVisibleYMToToday = useCalendarStore(
    (s) => s.resetDayVisibleYMToToday
  );
  const setSelectedDate = useCalendarStore((s) => s.setSelectedDate);
  // 获取可见年月（仅用于“日视图”自然月）
  const dayVisibleYM = useCalendarStore((s) => s.dayVisibleYM);
  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 fetchStatisticsDetail = useStatisticsStore(
    (s) => s.fetchStatisticsDetail
  );

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

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

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

  // 计算请求日期数组使用 useMemo，依赖可见年月，避免重复计算
  const calendarMonthInfo = useMemo(() => {
    const year = dayVisibleYM?.year;
    const month = dayVisibleYM?.month; // 1-12
    if (!year || !month) return null;
    const first = new Date(year, month - 1, 1);
    const last = new Date(year, month, 0);
    // 将 JS 周日=0 转为 周一=0（Mon-based）
    const wdMonFirst = (first.getDay() + 6) % 7;
    const wdMonLast = (last.getDay() + 6) % 7;
    // 计算起始日期和结束日期
    const start = new Date(first);
    start.setDate(first.getDate() - wdMonFirst);
    const end = new Date(last);
    end.setDate(last.getDate() + (6 - wdMonLast));
    // 生成日期列表
    const dates = [];
    for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
      const y = d.getFullYear();
      const m = String(d.getMonth() + 1).padStart(2, "0");
      const dd = String(d.getDate()).padStart(2, "0");
      dates.push(`${y}-${m}-${dd}`);
    }
    const mm = String(month).padStart(2, "0");
    const monthKey = `${year}-${mm}`;
    return { dates, monthKey };
  }, [dayVisibleYM?.year, dayVisibleYM?.month]);

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

  const triggerFetch = useCallback(() => {
    if (!calendarMonthInfo) return;
    // 取消上一次未完成请求
    if (abortRef.current) {
      abortRef.current.abort();
    }
    const controller = new AbortController();
    abortRef.current = controller;
    if (currentTab === "day") {
      fetchStatisticsDetail(
        {
          collectionType: 23,
          staffUID: targetStaffUID,
          dates: calendarMonthInfo.dates,
          monthKey: calendarMonthInfo.monthKey,
        },
        { signal: controller.signal }
      );
    }
  }, [calendarMonthInfo, fetchStatisticsDetail, currentTab, targetStaffUID]);

  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();
    };
  }, []);

  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>
        {(!inTeamAttendance || !!viewTeamMember?.staffUID) && (
          <CustomHeader title={attendanceStatistics} />
        )}
        <Tabs flex={1} value={currentTab} onValueChange={setCurrentTab}>
          <YStack style={attendanceStyles.container}>
            <Card style={attendanceStyles.userInfo}>
              <XStack items="center" justify="space-between">
                <UserInfo />
                <View
                  style={{
                    borderColor: primaryColor,
                    borderWidth: wp(1),
                    borderRadius: wp(4),
                  }}
                >
                  <Tabs.List>
                    {attendanceDimension.map((item, index) => (
                      <XStack key={index}>
                        <Tabs.Tab
                          theme={
                            currentTab == item.name ? "lightPrimaryWhite" : ""
                          }
                          unstyled
                          borderRadius={0}
                          alignItems="center"
                          justifyContent="center"
                          onInteraction={handleOnInteraction}
                          value={item.name}
                        >
                          <CustomText
                            style={[
                              attendanceStyles.tabItemText,
                              {
                                color:
                                  currentTab == item.name
                                    ? "#FFFFFF"
                                    : primaryColor,
                                borderRightColor:
                                  currentTab != item.name
                                    ? primaryColor
                                    : "#fff",
                                borderRightWidth:
                                  index < attendanceDimension.length - 1
                                    ? wp(1)
                                    : 0,
                              },
                            ]}
                          >
                            {item.label}
                          </CustomText>
                        </Tabs.Tab>
                      </XStack>
                    ))}
                  </Tabs.List>
                </View>
              </XStack>
            </Card>
            {currentTab === "day" && (
              <Card>
                <AttendanceRules />
              </Card>
            )}
            <Card flex={1}>
              <AnimatePresence
                exitBeforeEnter
                custom={{ direction }}
                initial={false}
              >
                <AnimatedYStack key={currentTab}>
                  <Tabs.Content
                    value={currentTab}
                    forceMount
                    flex={1}
                    justifyContent="center"
                  >
                    <YStack flex={1}>
                      <DateView
                        currentTab={currentTab}
                        selectedDateRange={selectedDateRange}
                      />
                      {currentTab == "day" && <DayAttendanceStat />}
                      {currentTab == "week" && (
                        <WeekAttendanceStat
                          onSelectedWeekRange={handleSelectedWeekRange}
                        />
                      )}
                      {currentTab == "month" && (
                        <MonthAttendanceStat
                          onSelectedMonthRange={handleSelectedMonthRange}
                        />
                      )}
                    </YStack>
                  </Tabs.Content>
                </AnimatedYStack>
              </AnimatePresence>
            </Card>
          </YStack>
        </Tabs>
      </CustomSafeArea>
    </View>
  );
}

//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 attendanceStyles = StyleSheet.create({
  container: {
    flex: 1,
    paddingVertical: wp(10),
    paddingHorizontal: 16,
    gap: wp(10),
  },
  userInfo: {
    paddingHorizontal: wp(16),
    paddingVertical: wp(14),
  },
  tabItemText: {
    fontSize: sp(14),
    fontFamily: "Regular",
    paddingHorizontal: wp(10),
    paddingVertical: wp(6),
  },
  separatorLine: {
    height: wp(28),
    width: wp(1),
  },
});
