import { router } from 'expo-router';
import { StyleSheet, TouchableOpacity, AppState, Platform } from 'react-native';
import { Image as ExpoImage } from 'expo-image';
import { CustomHeader } from '@/components/common/CustomHeader';
import { Image, View, YStack } from 'tamagui';
import { useAuthStore } from '@/stores/auth';
import React, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
import { useFocusEffect, useIsFocused } from '@react-navigation/native';
import { wp } from '@/utils/ui/screenUtils';
import UserInfoCard from '@/components/clockIn/UserInfoCard';
import DateDisplay from '@/components/clockIn/DateDisplay';
import ClockInRecordList from '@/components/clockIn/ClockInRecordList';
import { useClockIn } from '@/hooks/clockIn/useClockIn';
import { useClockInStore } from '@/stores/clockIn';
import { scheduleList } from '@/api/approve';
import { ServeCheckAuth } from '@/api/personal';
import { useTeamAttendanceStore } from '@/stores';
import AnnouncementTicker from '@/components/clockIn/AnnouncementTicker';
import { startLocationSettingObserve, stopLocationSettingObserve, addLocationSettingChangeListener, getLocationSettingState } from 'baidu-location-react-native';
import dayjs from 'dayjs';
import { useTranslation } from '@/node_modules/react-i18next';

import useLocationSetupPrompt from '@/hooks/system/useLocationSetupPrompt';
import { LOCATION_CONFIG } from '@/constants/location';
const HomeScreen = React.memo(function HomeScreen() {
    const userInfo = useAuthStore(s => s.user);
  const { t } = useTranslation('attendance');
  const {
    clockInList,
    startLocationWatching,
    stopLocationWatching,
    restartWatchingAndRefresh,
    getClockInList,
  } = useClockIn();
  const { actionTypeResult, loading } = useClockInStore();
  const { showByError, ensureReady, dismissLocationPrompt } = useLocationSetupPrompt();
  const isFocused = useIsFocused();

  // 下拉刷新状态
  const [refreshing, setRefreshing] = useState(false);
  // 控制列表自动展开的触发器：仅在页面进入/下拉刷新时递增，静默更新不改动
  const [expandTrigger, setExpandTrigger] = useState(0);
  // 首屏骨架加载状态（位置监听首次返回数据前）
  const [isInitialLoading, setIsInitialLoading] = useState(true);
  const didExpandOnFirstLoadRef = useRef(false);
  const prevLoadingRef = useRef(false);
  // 公告是否存在未读
  const [hasUnreadAnnouncement, setHasUnreadAnnouncement] = useState(false);
  // 最新未读公告标题
  const [unreadTitle, setUnreadTitle] = useState('');
  // AppState 当前值（用于统一启停判定）
  const [appStateStatus, setAppStateStatus] = useState(AppState.currentState || 'active');
  // 去抖后的 AppState，用于避免 Android 短暂的 background/active 抖动
  const [debouncedAppState, setDebouncedAppState] = useState(AppState.currentState || 'active');
  const appStateDebounceTimerRef = useRef(null);
  // AppState 去抖时长常量
  const APPSTATE_DEBOUNCE_MS = useMemo(() => ({ foreground: 300, background: 1500 }), []);
  // 上一次判定结果，避免重复启停
  const prevShouldWatchRef = useRef(null);
  // 手动重启监听中的标记（避免与安卓系统监听器互相打架）
  const manualRestartingRef = useRef(false);
  // 手动重启完成的时间点，用于在短时间内抑制统一启停误判导致的 stop
  const lastManualRestartAtRef = useRef(0);
  // 到点静默刷新定时器集合
  const scheduledTimersRef = useRef([]);

  // 当打卡列表首次拿到数据后，关闭首屏骨架，并触发一次自动展开
  useEffect(() => {
    if (isInitialLoading && Array.isArray(clockInList) && clockInList.length > 0) {
      setIsInitialLoading(false);
      if (!didExpandOnFirstLoadRef.current) {
        setExpandTrigger((v) => v + 1);
        didExpandOnFirstLoadRef.current = true;
      }
    }
  }, [isInitialLoading, clockInList]);

  // 监听 store.loading 在打完卡后刷新完成的场景：refreshing=false 且 loading 从 true 变为 false 时触发一次展开
  useEffect(() => {
    const prev = prevLoadingRef.current;
    if (prev && !loading && !refreshing && !isInitialLoading) {
      setExpandTrigger((v) => v + 1);
    }
    prevLoadingRef.current = loading;
  }, [loading, refreshing, isInitialLoading]);

  // 下拉刷新处理函数：先 stop 再 start，并等待首个定位刷新完成
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    manualRestartingRef.current = true;
    try {
      const ready = await ensureReady();
      if (!ready) return;
      await restartWatchingAndRefresh();
      // 触发列表根据最新数据自动展开当前需要打卡的卡片
      setExpandTrigger((v) => v + 1);
      // 标记手动重启刚刚完成，用于抑制统一启停在短时间内误触发 stop
      lastManualRestartAtRef.current = Date.now();
    } catch (error) {   
      console.error('[clockIn] 刷新失败:', error);
      showByError(error);
    } finally {
      manualRestartingRef.current = false;
      setRefreshing(false);
    }
  }, [restartWatchingAndRefresh, ensureReady, showByError, refreshing]);

  // 从服务器获取团队考勤权限
  const fetchTeamAttendanceAuth = useCallback(async () => {
    try {
      const res = await ServeCheckAuth({
        url: 'team_collection_auth',
        type: 'interface',
      })
      const setInTeamAttendance = useTeamAttendanceStore.getState()?.setInTeamAttendance;
      // 设置团队权限标记
      if (res?.status === 0 && res?.data) {
        setInTeamAttendance?.(!!res?.data);
      } else {
        setInTeamAttendance?.(false);
      }
    } catch (error) {
      console.error('[clockIn] 获取团队考勤权限失败:', error);
      setInTeamAttendance?.(false);
      showByError(error);
    }
  }, [])

  useEffect(() => {
    // 页面进入时，请求一次统计按钮权限
    fetchTeamAttendanceAuth();
  }, [])

  // 点击统计按钮节流窗口（毫秒）
  const STATISTICS_NAV_THROTTLE_MS = 800;
  // 统计按钮导航节流截止时间
  const statisticsNavThrottleUntilRef = useRef(0);
  
  // 处理统计按钮点击
  const handleStatisticsPress = useCallback(() => {
    const now = Date.now();
    if (now < statisticsNavThrottleUntilRef.current) {
      return;
    }
    statisticsNavThrottleUntilRef.current = now + STATISTICS_NAV_THROTTLE_MS;

    const inTeamAttendance = useTeamAttendanceStore.getState()?.inTeamAttendance;
    if (inTeamAttendance) {
      // 有团队考勤权限，跳转携带团队考勤和个人考勤切换的入口页
      router.push('/attendance');
    } else {
      // 无团队考勤权限，进入个人考勤页面
      router.push('/attendance/attendanceStatistics');
    }
  }, []);
  
  /**
   * 开始持续监听位置
   */
  const startLocationMonitoring = useCallback(async () => {
    try {
      // 启动前进行权限与服务可用性检查
      const ready = await ensureReady();
      if (!ready) return;
      
      // 开始持续监听位置变化（无需额外 UI 更新回调）
      await startLocationWatching((loc) => {
        try {
          const coords = loc?.coords || loc;
          if (coords && typeof coords.latitude === 'number' && typeof coords.longitude === 'number') {
            // 仅在定位精度足够（配置阈值）时关闭提示，避免 iOS 近似定位下提示被立即关闭
            const acc = coords?.accuracy;
            const threshold = LOCATION_CONFIG?.ATTENDANCE?.accuracyThreshold ?? 100;
            if (typeof acc === 'number' && acc <= threshold) {
              dismissLocationPrompt();
            }
          }
        } catch (_) {}
      });
    } catch (error) {
      console.error('[clockIn] 启动位置监听失败:', error);
      showByError(error);
    }
  }, [ensureReady, startLocationWatching, showByError, dismissLocationPrompt])

  /**
   * 停止持续监听位置变化
   */
  const stopLocationMonitoring = useCallback(async () => {
    try {
      // 停止位置监听
      await stopLocationWatching();
    } catch (error) {
      console.error('[clockIn] 停止位置监听失败:', error);
    }
  }, [stopLocationWatching])

  // 查询公告是否存在未读
  const checkAnnouncementUnread = useCallback(async () => {
    try {
      const res = await scheduleList({ pageNum: 1, pageSize: 50 });
      const list = res?.data?.Data ?? [];
      const unreadList = Array.isArray(list) ? list.filter((it) => it?.IsRead === 0) : [];
      // 选出按 CreatedTime 最新的一条
      let latestUnread = null;
      for (const it of unreadList) {
        const curTime = new Date(it?.CreatedTime || 0).getTime() || 0;
        const prevTime = new Date(latestUnread?.CreatedTime || 0).getTime() || 0;
        if (!latestUnread || curTime > prevTime) {
          latestUnread = it;
        }
      }
      const nextTitle = latestUnread?.Title || '';
      const hasUnread = unreadList.length > 0;
      setUnreadTitle((prev) => (prev === nextTitle ? prev : nextTitle));
      setHasUnreadAnnouncement((prev) => (prev === hasUnread ? prev : hasUnread));
    } catch (error) {
      console.error('[clockIn] 获取公告未读状态失败:', error);
    }
  }, []);

  // 页面聚焦时检查公告未读（不在这里启停定位）
  useFocusEffect(
    useCallback(() => {
      checkAnnouncementUnread();
    }, [checkAnnouncementUnread])
  );

  // 仅监听 AppState 变化，更新状态供统一判定使用
  useEffect(() => {
    const handleAppStateChange = (nextState) => {
      setAppStateStatus(nextState);
    };

    const subscription = AppState.addEventListener('change', handleAppStateChange);
    return () => {
      subscription.remove();
    };
  }, []);

  // 对 AppState 做去抖，过滤 Android 上极短暂的 background 抖动
  useEffect(() => {
    if (appStateDebounceTimerRef.current) {
      clearTimeout(appStateDebounceTimerRef.current);
      appStateDebounceTimerRef.current = null;
    }
    const delay = appStateStatus === 'background' ? APPSTATE_DEBOUNCE_MS.background : APPSTATE_DEBOUNCE_MS.foreground;
    appStateDebounceTimerRef.current = setTimeout(() => {
      setDebouncedAppState(appStateStatus);
    }, delay);
    return () => {
      if (appStateDebounceTimerRef.current) {
        clearTimeout(appStateDebounceTimerRef.current);
        appStateDebounceTimerRef.current = null;
      }
    };
  }, [appStateStatus]);

  // 统一启停：仅当 shouldWatch 真正发生变化时才调用 start/stop
  useEffect(() => {
    // 手动重启监听期间（下拉刷新触发），避免与统一启停发生竞态
    if (manualRestartingRef.current) {
      return;
    }

    const shouldWatch = isFocused && debouncedAppState !== 'background';
    const prev = prevShouldWatchRef.current;
 
    if (prev === shouldWatch) {
      return;
    }
    prevShouldWatchRef.current = shouldWatch;

    if (shouldWatch) {
      startLocationMonitoring();
    } else {
      // 在手动重启完成后的短时间内，忽略一次 stop，避免 appState 抖动（去抖后仍为 background）导致刚 start 又 stop
      const since = Date.now() - (lastManualRestartAtRef.current || 0);
      if (since < 2000) {
        return;
      }
      stopLocationMonitoring();
    }
  }, [isFocused, debouncedAppState, appStateStatus, startLocationMonitoring, stopLocationMonitoring]);

  // 监听（Android/iOS）定位服务/权限变化：感知切换后即时启停
  useEffect(() => {
    if (!isFocused) return;
    let subscription = null;
    let cancelled = false;

    const handler = ({ isLocationEnabled, hasPermission }) => {
      if (manualRestartingRef.current) {
        return;
      }
      if (!isLocationEnabled || !hasPermission) {
        stopLocationMonitoring();
      } else {
        if (isFocused && debouncedAppState !== 'background') {
          startLocationMonitoring();
        }
      }
    };

    (async () => {
      try {
        subscription = addLocationSettingChangeListener(handler);
        await startLocationSettingObserve();

        // Android端：订阅成功后主动拉取一次当前状态，用于更快对齐（仅在未取消时执行）
        if (!cancelled && Platform.OS === 'android' && typeof getLocationSettingState === 'function') {
          try {
            const initial = await getLocationSettingState();
            // 仅在“不可用/无权限”时触发一次对齐，避免与统一启停产生重复 start
            if (!cancelled && (initial?.isLocationEnabled === false || initial?.hasPermission === false)) {
              handler(initial);
            }
          } catch (_) {
            // 忽略异常：平台不支持或实现缺失时
          }
        }
      } catch (e) {
        // 忽略启动/订阅失败（平台不支持或原生实现缺失时）
      }
    })();
  
    return () => {
      cancelled = true;
      if (subscription && subscription.remove) subscription.remove();
      stopLocationSettingObserve().catch(() => {});
    };
  }, [isFocused, debouncedAppState, startLocationMonitoring, stopLocationMonitoring]);

  // 组件卸载时确保停止监听
  useEffect(() => {
    return () => {
      // 仅在真正卸载时兜底停止监听（切 tab/回到前台不会触发卸载）
      stopLocationMonitoring();
    };
  }, [stopLocationMonitoring]);

  // 根据 clockInList 的 workTime 到点静默刷新
  useEffect(() => {
    // 清理已有定时器
    const clearAll = () => {
      if (scheduledTimersRef.current && scheduledTimersRef.current.length) {
        scheduledTimersRef.current.forEach((id) => clearTimeout(id));
      }
      scheduledTimersRef.current = [];
    };

    // 仅在页面聚焦且前台时启用
    const active = isFocused && debouncedAppState !== 'background';

    // 预计算即将到达的 workTime 列表（仅未来时间）
    const now = dayjs();
    const upcomingTimes = Array.isArray(clockInList)
      ? clockInList
          .map((it) => it?.workTime)
          .filter((t) => typeof t === 'string' && /^\d{2}:\d{2}$/.test(t))
          .map((t) => {
            const [hh, mm] = t.split(':').map((s) => parseInt(s, 10));
            return dayjs().hour(hh).minute(mm).second(0).millisecond(0);
          })
          .filter((ts) => ts.isAfter(now))
          .sort((a, b) => a.valueOf() - b.valueOf())
          .map((ts) => ts.format('HH:mm'))
          .filter((t, i, a) => a.indexOf(t) === i)
      : [];

    // 每次依赖变更都重新调度，避免因 React 调用上一次 cleanup 而丢失 timers
    clearAll();
    if (!active) {
      return () => {};
    }

    // 逐个 workTime 设置定时器
    for (const timeStr of upcomingTimes) {
      const [hh, mm] = timeStr.split(':').map((s) => parseInt(s, 10));
      const target = dayjs().hour(hh).minute(mm).second(0).millisecond(0);
      const delay = Math.max(target.diff(dayjs(), 'millisecond'), 0);

      const id = setTimeout(async () => {
        // 若正在手动重启或页面已不活跃，跳过此次静默刷新
        if (manualRestartingRef.current || !isFocused || debouncedAppState === 'background') {
          return;
        }
        try {
          console.log(`[clockIn] workTime 到点(${timeStr})，触发静默刷新`);
          await getClockInList({ silent: true });
        } catch (e) {
          // 吞错：静默刷新失败不打断主流程
          console.warn('[clockIn] workTime 静默刷新失败:', e?.message || e);
        }
      }, delay);
      scheduledTimersRef.current.push(id);
    }

    // 清理函数
    return () => {
      clearAll();
    };
  }, [clockInList, isFocused, debouncedAppState, getClockInList]);

  // 跳转公告页
  const openAnnouncement = useCallback(() => {
    router.push('/announcement');
  }, []);

  // 右上角按钮内容
  const headerRightContent = useMemo(() => (
    <TouchableOpacity style={styles.headerRight} onPress={openAnnouncement}>
      <View style={styles.iconWrapper}>
        <Image 
          width={wp(24)} 
          height={wp(24)} 
          source={require('@/assets/images/icon/zu5437.png')}
        />
        {hasUnreadAnnouncement && <View style={styles.redDot} />}
      </View>
    </TouchableOpacity>
  ), [hasUnreadAnnouncement, openAnnouncement]);

  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"
      />
    
        <CustomHeader 
        
          title={t('pageTitle.clockIn')} 
          useCustomStyle={true} 
          leftContent={''} 
          rightContent={headerRightContent} 
        />
        {/* 悬浮未读公告滚动条*/}
        {hasUnreadAnnouncement && !!unreadTitle ? (
          <AnnouncementTicker title={unreadTitle} top={wp(8)} />
        ) : null}
        <YStack style={styles.pagePadding}>
          {/* 用户信息卡片 */}
          <UserInfoCard 
            userInfo={userInfo}  
            onStatisticsPress={handleStatisticsPress}
          />
          {/* 日期显示 */}
          <DateDisplay />
          
          {/* 打卡记录列表 */}
          <ClockInRecordList
            records={clockInList}
            onRefresh={onRefresh}
            refreshing={refreshing}
            actionTypeData={actionTypeResult}
            expandTrigger={expandTrigger}
            loadingInitial={isInitialLoading}
          />
        </YStack>
    </View>
  );
});

const styles = StyleSheet.create({
  bg: {
    width: '100%',
    height: '100%'
  },
  pagePadding: {
    flex:1,
    paddingTop: wp(12),
    paddingHorizontal: wp(12),
  },
  headerRight: {
    paddingRight: wp(22),
    flexDirection: 'row',
    alignItems: 'center'
  },
  iconWrapper: {
    position: 'relative',
  },
  redDot: {
    position: 'absolute',
    top: -2,
    right: -2,
    width: wp(8),
    height: wp(8),
    borderRadius: wp(4),
    backgroundColor: '#FF3B30',
  }
});

export default HomeScreen;
