import { useRef, useCallback, useMemo, memo, useEffect, useState } from "react";
import { Dimensions, StyleSheet, ScrollView } from "react-native";
import { View, YStack } from "tamagui";
import {
  useTeamAttendanceStore,
  useTeamCalendarStore,
  useAppStore,
} from "@/stores";

// 日历组件
import { CalendarList } from "react-native-calendars";

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

// UI组件
import LoadingSpinner from "@/components/ui/LoadingSpinner";

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

// 固定日历宽度为常量，避免每次计算
const CALENDAR_WIDTH = Math.round(Dimensions.get("window").width - 32);
const WEEK_ROW_HEIGHT = 50;
const DAY_NAMES_HEIGHT = 32;

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

  // 日视图仅订阅“自然月”的可见年月（与周/月解耦合）
  const visibleYM = useTeamCalendarStore((s) => s.dayVisibleYM);
  const selectedDate = useTeamCalendarStore((s) => s.selectedDate);
  const dayJumpVersion = useTeamCalendarStore((s) => s.dayJumpVersion);
  const setSelectedDate = useTeamCalendarStore((s) => s.setSelectedDate);
  const setDayVisibleYM = useTeamCalendarStore((s) => s.setDayVisibleYM);

  // 计算可见月份键与选中日期键
  const visibleKey = useMemo(() => {
    const m = String(visibleYM.month).padStart(2, "0");
    return `${visibleYM.year}-${m}`;
  }, [visibleYM.year, visibleYM.month]);
  const selectedKey = useMemo(
    () => (selectedDate ? dayjs(selectedDate).format("YYYY-MM") : ""),
    [selectedDate]
  );

  // 当前月份 key（YYYY-MM）：仅用于“标记过滤”，不再依赖 providerDate
  const currentMonthKey = useMemo(() => visibleKey, [visibleKey]);

  // 日历 ref
  const calendarRef = useRef(null);
  // 一次性设置初始月份（仅首次挂载生效，避免出现“今天所在月”的中间态）
  const initialMonthRef = useRef(null);
  if (initialMonthRef.current == null) {
    const m = String(visibleYM.month).padStart(2, "0");
    initialMonthRef.current = `${visibleYM.year}-${m}-01`;
  }
  // 一次性“本日”跳转：当版本号变化时，滚动到当前可见月份
  useEffect(() => {
    if (!calendarRef.current) return;
    const m = String(visibleYM.month).padStart(2, "0");
    calendarRef.current.scrollToMonth(`${visibleYM.year}-${m}-01`);
  }, [dayJumpVersion]);

  //月份变化回调
  const onMonthChange = useCallback(
    (date) => {
      const d = dayjs(date.dateString);
      // 仅在年月发生变化时才写入，避免冗余更新
      if (visibleYM.year !== d.year() || visibleYM.month !== d.month() + 1) {
        setDayVisibleYM({ year: d.year(), month: d.month() + 1 });
      }
      // 同步根据该月的周数更新容器高度（分页完成后触发，避免滚动过程抖动）
      applyContainerHeightForYM(d.year(), d.month() + 1);
    },
    [setDayVisibleYM, visibleYM.year, visibleYM.month]
  );

  // 读取接口加载状态与更新时间
  const loadingCount = useTeamAttendanceStore((s) => s.loadingCount);
  const isLoading = (loadingCount || 0) > 0;

  // 读取当前统计模式与日模式拉取方法
  const activeStatisticsMode = useTeamAttendanceStore(
    (s) => s.activeStatisticsMode
  );
  const fetchTeamAttendanceDay = useTeamAttendanceStore(
    (s) => s.fetchTeamAttendanceDay
  );
  const effectiveDate = useMemo(
    () => selectedDate || dayjs().format("YYYY-MM-DD"),
    [selectedDate]
  );

  // 日模式数据拉取及守卫
  useEffect(() => {
    if (activeStatisticsMode !== "day") return;
    fetchTeamAttendanceDay({
      collectionType: 1,
      date: effectiveDate,
    });
  }, [activeStatisticsMode, effectiveDate, fetchTeamAttendanceDay]);

  //自定义主题
  const customTheme = useMemo(
    () => ({
      calendarBackground: "#ffffff",
      "stylesheet.calendar.header": {
        dayHeader: {
          color: "#191919",
          fontSize: sp(14),
          fontFamily: "Bold",
          marginBottom: wp(16),
        },
      },
      "stylesheet.day.basic": {
        selected: {
          borderRadius: wp(6),
          // 中和默认选中态：与背景一致
          backgroundColor: "#ffffff",
        },
        selectedText: {
          // 中和默认选中文本色：与普通文本一致
          color: "#191919",
        },
        todayText: {
          color: primaryColor,
        },
      },
      "stylesheet.dot": {
        dot: {
          width: wp(4),
          height: wp(4),
          marginTop: wp(10),
          marginHorizontal: wp(1),
          borderRadius: wp(2),
          opacity: 0,
        },
      },
      "stylesheet.calendar-list.main": {
        placeholderText: {
          color: "transparent",
        },
      },
    }),
    [primaryColor]
  );

  //自定义头部
  const renderHeader = useCallback(() => {
    return null;
  }, []);

  //日期选择回调：仅更新全局 selectedDate（store 内部已做同值 no-op）
  const onDayPress = useCallback(
    (day) => {
      if (isLoading) return;
      const next = day?.dateString ?? "";
      setSelectedDate(next);
    },
    [setSelectedDate, isLoading]
  );

  // 标记数据：仅包含“当前月的标记 + 选中态”，体量稳定；引用仅在当前月或选中变化时改变
  const markedDates = useMemo(() => {
    // 直接基于统计数据构建并过滤当前月，避免首次装载阶段的额外 setState 触发

    let result = {};
    // 仅当选中日期属于当前可见月时，合并选中态
    if (selectedDate && selectedKey === currentMonthKey) {
      const prev = result[selectedDate];
      result[selectedDate] = {
        ...(prev ?? {}),
        selected: true,
        selectedColor: primaryColor,
        selectedTextColor: "#ffffff",
        disableTouchEvent: true,
      };
    }
    return result;
  }, [currentMonthKey, selectedDate, selectedKey, primaryColor]);

  // 动态容器高度：根据当前可见月的行数（不使用 showSixWeeks，按实际行数计算）
  const [containerHeight, setContainerHeight] = useState(
    DAY_NAMES_HEIGHT + 5 * WEEK_ROW_HEIGHT
  );
  const FIRST_DAY_OF_WEEK = 1;

  const computeWeekCount = useCallback((year, month) => {
    const firstOfMonth = dayjs(`${year}-${String(month).padStart(2, "0")}-01`);
    const firstDayIndex = (firstOfMonth.day() - FIRST_DAY_OF_WEEK + 7) % 7;
    const daysInMonth = firstOfMonth.daysInMonth();
    const rows = Math.ceil((firstDayIndex + daysInMonth) / 7);
    return rows;
  }, []);

  const applyContainerHeightForYM = useCallback(
    (year, month) => {
      const rows = computeWeekCount(year, month);
      const target = DAY_NAMES_HEIGHT + rows * WEEK_ROW_HEIGHT;
      setContainerHeight((prev) => (prev === target ? prev : target));
    },
    [computeWeekCount]
  );

  // 首次挂载：根据初始 current 月份设置一次容器高度
  useEffect(() => {
    const d = dayjs(initialMonthRef.current);
    applyContainerHeightForYM(d.year(), d.month() + 1);
  }, [applyContainerHeightForYM]);

  return (
    <YStack position="relative" flex={1}>
      <ScrollView
        flex={1}
        contentContainerStyle={styles.contentContainer}
        // 隐藏滚动条
        showsVerticalScrollIndicator={false}
        // 解决滚动冲突
        nestedScrollEnabled={true}
      >
        <YStack height={containerHeight} overflow="hidden">
          <CalendarList
            ref={calendarRef}
            // 首次可见月：稳定的初始值，仅在首次挂载生效
            current={initialMonthRef.current}
            //是否开启水平布局
            horizontal={true}
            //是否开启分页滚动
            pagingEnabled={true}
            //日历宽度
            calendarWidth={CALENDAR_WIDTH}
            //是否隐藏额外天数
            hideExtraDays={false}
            //第一天从周几开始
            firstDay={1}
            //自定义头部
            renderHeader={renderHeader}
            //是否隐藏星期
            hideDayNames={false}
            //是否隐藏左右箭头
            hideArrows={true}
            //是否显示加载指示器
            displayLoadingIndicator={false}
            //日期选择回调
            onDayPress={onDayPress}
            //月份变化回调
            onMonthChange={onMonthChange}
            //自定义主题
            theme={customTheme}
            //标记数据
            markedDates={markedDates}
            //性能优化
            // 保留“伪无限”手感（按需调整范围），结合按月懒加载标记，避免大对象频繁更新
            // 使用大范围以覆盖跨多年场景，避免边界卡死
            pastScrollRange={240}
            futureScrollRange={36}
          />
        </YStack>
        {isLoading && (
          <YStack pointerEvents="none" style={styles.overlay}>
            <LoadingSpinner
              size={wp(20)}
              color={primaryColor}
              animating={isLoading}
            />
          </YStack>
        )}
        <View style={styles.separatorLine} />
        <View style={styles.radialProgress}>
          <RadialProgress></RadialProgress>
        </View>
        <View style={styles.teamStatisticsView}>
          <TeamStatisticsView />
        </View>
      </ScrollView>
    </YStack>
  );
});

export default DayMode;

const styles = StyleSheet.create({
  contentContainer: {
    paddingBottom: wp(12),
  },
  overlay: {
    position: "absolute",
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "rgba(255,255,255,0.6)",
    zIndex: 100,
  },
  separatorLine: {
    height: wp(1),
    marginHorizontal: wp(8),
    marginTop: wp(10),
    backgroundColor: "#F8F8F8",
  },
  radialProgress: {
    height: wp(130),
    alignItems: "center",
    backgroundColor: "#fff",
    paddingTop: wp(10),
  },
  teamStatisticsView: {
    paddingHorizontal: wp(8),
  },
});
