import { XStack, View, Button } from "tamagui";
import { StyleSheet, TouchableOpacity } from "react-native";
import { useMemo, useCallback } from "react";
import { useTranslation } from "@/node_modules/react-i18next";
import { useCalendarStore, useAppStore } from "@/stores";

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

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

const DateView = (props) => {
  //获取主色
  const primaryColor = useAppStore((s) => s.primary);
  // 按切片订阅：日/周/月 可见年月
  const dayVisibleYM = useCalendarStore((s) => s.dayVisibleYM);
  const weekVisibleYM = useCalendarStore((s) => s.weekVisibleYM);
  const monthVisibleYM = useCalendarStore((s) => s.monthVisibleYM);
  // 点击本日/本周/本月
  const jumpDayToToday = useCalendarStore((s) => s.jumpDayToToday);
  const setSelectedDate = useCalendarStore((s) => s.setSelectedDate);
  const jumpWeekToToday = useCalendarStore((s) => s.jumpWeekToToday);
  const jumpMonthToToday = useCalendarStore((s) => s.jumpMonthToToday);
  //国际化
  const { t } = useTranslation("attendance");

  // 计算 header 显示的年份（按当前维度）
  const headerYear = useMemo(() => {
    if (props.currentTab === "week") return weekVisibleYM.year;
    if (props.currentTab === "month") return monthVisibleYM.year;
    return dayVisibleYM.year;
  }, [
    props.currentTab,
    weekVisibleYM.year,
    monthVisibleYM.year,
    dayVisibleYM.year,
  ]);

  // 计算 header 中的日期显示：
  // - 日视图：“8月”
  // - 周视图：显示选中的考勤周范围，如 08.18-08.24
  // - 月视图：显示选中的考勤月范围，如 07.26-08.25
  const monthLabel = useMemo(() => {
    const dayLabel = t(`months.${dayVisibleYM.month}`);
    if (props.currentTab === "week") {
      if (
        props.selectedDateRange?.startDate &&
        props.selectedDateRange?.endDate
      ) {
        try {
          const { formatDateRange } = require("@/utils/time/dateUtils");
          return formatDateRange(
            props.selectedDateRange.startDate,
            props.selectedDateRange.endDate
          );
        } catch (e) {
          return dayLabel;
        }
      }
      return dayLabel;
    }
    if (props.currentTab === "month") {
      try {
        const {
          getAttendanceMonthRange2625,
          formatDateRange,
        } = require("@/utils/time/dateUtils");
        const range = getAttendanceMonthRange2625(
          monthVisibleYM.year,
          monthVisibleYM.month
        );
        return formatDateRange(range.startDate, range.endDate);
      } catch (e) {
        return dayLabel;
      }
    }
    return dayLabel;
  }, [
    props.currentTab,
    props.selectedDateRange?.startDate,
    props.selectedDateRange?.endDate,
    t,
    dayVisibleYM.month,
    monthVisibleYM.year,
    monthVisibleYM.month,
  ]);

  const todayLabel = useMemo(() => {
    switch (props.currentTab) {
      case "day":
        return t("attendanceDimension.day");
      case "week":
        return t("attendanceDimension.week");
      case "month":
        return t("attendanceDimension.month");
      default:
        return t("attendanceDimension.day");
    }
  }, [props.currentTab, t]);

  // 统一处理“本日、本周、本月”按钮点击
  const handlePressToday = useCallback(() => {
    const now = new Date();
    const y = now.getFullYear();
    const m = now.getMonth() + 1;
    const d = String(now.getDate()).padStart(2, "0");
    if (props.currentTab === "week") {
      // 周模式：直接按考勤月规则跳到“今天所在考勤周”
      jumpWeekToToday();
    } else if (props.currentTab === "month") {
      // 月模式：跳到“今天所在的考勤月(26-25)的结束月”
      jumpMonthToToday();
    } else {
      // 日模式：触发一次性“本日”跳转并高亮“今天”
      jumpDayToToday();
      setSelectedDate(`${y}-${String(m).padStart(2, "0")}-${d}`);
    }
  }, [
    jumpWeekToToday,
    props.currentTab,
    jumpDayToToday,
    setSelectedDate,
    jumpMonthToToday,
  ]);

  return (
    <XStack style={styles.calendarHeader}>
      <XStack style={styles.calendarHeaderCurrentYearContainer}>
        <CustomText style={styles.calendarHeaderCurrentYear}>
          {headerYear}
        </CustomText>
        <View style={styles.calendarHeaderLine}></View>
        <CustomText style={styles.calendarHeaderCurrentMonth}>
          {monthLabel}
        </CustomText>
      </XStack>
      <TouchableOpacity onPress={handlePressToday}>
        <XStack
          style={[
            styles.calendarHeaderTodayButton,
            { backgroundColor: primaryColor },
          ]}
        >
          <CustomText style={styles.calendarHeaderTodayButtonText}>
            {t('todayButton', { unit: todayLabel })}
          </CustomText>
        </XStack>
      </TouchableOpacity>
      {/* <Button onPress={handlePressToday} style={[styles.calendarHeaderTodayButton, { backgroundColor: primaryColor }]}>
                <CustomText style={styles.calendarHeaderTodayButtonText}>本{todayLabel}</CustomText>
            </Button> */}
    </XStack>
  );
};

export default DateView;

const styles = StyleSheet.create({
  calendarHeader: {
    justifyContent: "space-between",
    alignItems: "center",
    backgroundColor: "#fff",
    paddingBottom: wp(10),
    paddingTop: wp(13),
  },
  calendarHeaderCurrentYearContainer: {
    alignItems: "center",
    justifyContent: "center",
  },
  calendarHeaderCurrentYear: {
    fontSize: sp(14),
    lineHeight: wp(25),
    fontFamily: "Bold",
    paddingHorizontal: wp(7),
    marginLeft: wp(9),
  },
  calendarHeaderLine: {
    width: wp(1),
    height: wp(13),
    backgroundColor: "#707070",
    alignSelf: "center",
  },
  calendarHeaderCurrentMonth: {
    fontSize: sp(14),
    lineHeight: wp(25),
    fontFamily: "Bold",
    paddingHorizontal: wp(6),
  },
  calendarHeaderTodayButton: {
    borderRadius: wp(4),
    paddingHorizontal: wp(14),
    paddingVertical: wp(6),
    marginRight: wp(18),
  },
  calendarHeaderTodayButtonText: {
    fontSize: sp(12),
    fontFamily: "Regular",
    color: "#fff",
  },
});
