import React, { useState, useCallback, useRef } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import HealthDataCard from './HealthDataCard';
import { fetchOxygenSaturation } from '@/utils/health';
import dayjs from 'dayjs';

interface OxygenSaturationCardProps {
  style?: object;
  selectedDate?: Date;
}

const OxygenSaturationCard: React.FC<OxygenSaturationCardProps> = ({
  style,
  selectedDate
}) => {
  const [oxygenSaturation, setOxygenSaturation] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const loadingRef = useRef(false);

  // 获取血氧饱和度数据 - 在页面聚焦、日期变化时触发
  useFocusEffect(
    useCallback(() => {
      const loadOxygenSaturationData = async () => {
        const dateToUse = selectedDate || new Date();

        // 防止重复请求
        if (loadingRef.current) return;

        try {
          loadingRef.current = true;
          setLoading(true);

          const options = {
            startDate: dayjs(dateToUse).startOf('day').toDate().toISOString(),
            endDate: dayjs(dateToUse).endOf('day').toDate().toISOString()
          };

          const data = await fetchOxygenSaturation(options);
          setOxygenSaturation(data);
        } catch (error) {
          console.error('OxygenSaturationCard: 获取血氧饱和度数据失败:', error);
          setOxygenSaturation(null);
        } finally {
          setLoading(false);
          loadingRef.current = false;
        }
      };

      loadOxygenSaturationData();
    }, [selectedDate])
  );

  return (
    <HealthDataCard
      title="血氧饱和度"
      value={loading ? '--' : (oxygenSaturation !== null && oxygenSaturation !== undefined ? oxygenSaturation.toFixed(1) : '--')}
      unit="%"
      style={style}
    />
  );
};

export default OxygenSaturationCard;