import React, { useMemo, memo, useState, useEffect } from 'react';
import { TouchableOpacity, Vibration, Platform, StyleSheet } from 'react-native';
import { View } from 'tamagui';
import CustomText from '@/components/common/CustomText.jsx';
import { LinearGradient } from 'tamagui/linear-gradient';
import { useClockIn } from '@/hooks/clockIn/useClockIn';
import { useClockInStore } from '@/stores/clockIn';
import { useAuthStore } from '@/stores/auth';
import { clockIn } from '@/api/clock';
import { showError } from '@/utils/ui/toast';
import { wp } from '@/utils/ui/screenUtils';
import { cardTypes } from '@/constants/apply.js';
import dayjs from 'dayjs';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import { useTranslation } from 'react-i18next';


const styles = StyleSheet.create({
  buttonBase: {
    borderRadius: wp(8),
    flex: 1,
  },
  gradientBase: {
    borderRadius: wp(8),
    height: wp(51),
    justifyContent: 'center',
    alignItems: 'center',
  },
  timeContainer: {
    alignItems: 'center',
    flexDirection: 'row',
  },
  timeText: {
    color: 'white',
    fontSize: wp(16),
    fontFamily: 'Bold',
    fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
    letterSpacing: 1.1,
    marginRight: 5,
  },
  labelText: {
    color: 'white',
    fontSize: wp(16),
    fontFamily: 'Medium',
  },
  defaultText: {
    color: 'white',
    fontSize: wp(16),
    fontFamily: 'Bold',
  },
});

/**
 * 共享的打卡按钮组件
 * 提供统一的打卡逻辑和样式，支持主打卡页面和外勤打卡页面复用
 * @param {Object} record - 打卡记录数据
 * @param {Object} actionTypeData - 打卡类型数据
 * @param {Function} onClockInSuccess - 打卡成功回调
 * @param {Object} customStyle - 自定义样式
 * @param {boolean} disabled - 是否禁用
 * @param {boolean} showTimeInButton - 是否在按钮内显示时间（外勤打卡页面使用）
 */
const ClockInButton = ({ 
  record, 
  actionTypeData, 
  onClockInSuccess,
  customStyle = {},
  disabled = false,
  showTimeInButton = false 
}) => {
  const { getBtnLabel, getClockInList, clockInBtnLoading, setClockInBtnLoading } = useClockIn();
  const { location, isClockInCooldownActive, setLastClockInSuccessTime, actionCoords } = useClockInStore();
  const { user } = useAuthStore();
  const [currentTime, setCurrentTime] = useState(dayjs().format('HH:mm:ss'));
  const { t } = useTranslation('attendance');

  // 仅用于配色的禁用判断（与主页一致），不影响交互
  const colorDisabled = useMemo(() => {
    if (!record) return true;
    if (record.isClockCard && actionTypeData?.actionType === 'noClock') return true;
    if (!record.isClockCard) return true;
    return false;
  }, [record, actionTypeData]);

  // 时间更新逻辑（仅在需要在按钮内显示时间时启用）
  useEffect(() => {
    if (!showTimeInButton) return;
    
    const timer = setInterval(() => {
      setCurrentTime(dayjs().format('HH:mm:ss'));
    }, 1000);
    return () => clearInterval(timer);
  }, [showTimeInButton]);

  // 按钮显示文字
  const btnLabel = useMemo(() => {
    return getBtnLabel(record, actionTypeData);
  }, [record, actionTypeData, getBtnLabel]);

  // 时间显示逻辑（参考ClockInRecordItem的逻辑）
  const timeDisplay = useMemo(() => {
    if (!showTimeInButton) return null;
    
    if (!record.isClockCard && record.clockActionType !== '') {
      return record.actionTime?.split(' ')?.[1];
    }
    if (record.isClockCard) {
      if (record.onOff === 'off' && record.actionTime !== '') {
        return currentTime;
      } else {
        return currentTime;
      }
    }
    return currentTime;
  }, [record, currentTime, showTimeInButton]);

  // 按钮颜色配置（与主页一致：基于 record.actionType，显示灰色时机与主页一致）
  const buttonColors = useMemo(() => {
    if (disabled || colorDisabled) {
      return ['#BABABA', '#BABABA'];
    }
    const typeKey = record?.actionType || 'common';
    const cardType = cardTypes[typeKey];
    if (cardType?.linearColor) return cardType.linearColor;
    return ['#667eea', '#764ba2'];
  }, [record?.actionType, disabled, colorDisabled]);

  // 计算opacity样式（保持原有交互逻辑）
  const gradientOpacity = useMemo(() => {
    return (clockInBtnLoading || disabled) ? 0.6 : 1;
  }, [clockInBtnLoading, disabled]);

  // 打卡处理函数（保持原有交互逻辑）
  const handleClockIn = async () => {
    if (clockInBtnLoading || disabled) {
      return;
    }

    // 15秒内防重复提交
    if (isClockInCooldownActive && isClockInCooldownActive()) {
      showError(t('messages.cooldown'));
      return;
    }

    if (!location) {
      console.warn('位置信息未获取');
      return;
    }

    try {
      setClockInBtnLoading(true);
      
      // 优先使用与当前 UI 判定一致的坐标快照，避免点击瞬间位置变更导致提交坐标不一致
      const submitCoords = actionCoords && typeof actionCoords?.latitude === 'number' && typeof actionCoords?.longitude === 'number'
        ? actionCoords
        : location;
      const res = await clockIn({
        checkAddress: submitCoords?.addressText ?? location?.addressText,
        latitude: String(submitCoords?.latitude),
        longitude: String(submitCoords?.longitude),
        staffUID: user.ID,
      });

      if (res.status === 0) {
      
        Vibration.vibrate(200);
        
        // 刷新打卡列表
        await getClockInList();
        
        // 记录打卡成功时间用于15秒内防重复提交
        try { setLastClockInSuccessTime(Date.now()); } catch (e) {}
        
        // 执行成功回调
        onClockInSuccess?.(res);
      }
    } catch (error) {
      console.error('打卡失败:', error);
    } finally {
      setClockInBtnLoading(false);
    }
  };

  return (
    <TouchableOpacity
      style={[styles.buttonBase, customStyle]}
      onPress={handleClockIn}
      disabled={clockInBtnLoading || disabled}
      activeOpacity={0.8}
    >
      <LinearGradient
        colors={buttonColors}
        start={[0, 0]}
        end={[1, 0]}
        borderRadius={wp(8)}
        style={[styles.gradientBase, { opacity: gradientOpacity }]}
      >
        {showTimeInButton ? (
          <View style={styles.timeContainer}>
            <CustomText style={styles.timeText}>
              {timeDisplay}
            </CustomText>
            {clockInBtnLoading ? (
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <LoadingSpinner size={wp(25)} color="white" />
                <CustomText style={styles.labelText}>{t('btnText.clockInLoading')}</CustomText>
              </View>
            ) : (
              <CustomText style={styles.labelText}>
                {btnLabel}
              </CustomText>
            )}
          </View>
        ) : (
          clockInBtnLoading ? (
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <LoadingSpinner size={wp(25)} color="white" />
              <CustomText style={styles.defaultText}>{t('btnText.clockInLoading')}</CustomText>
            </View>
          ) : (
            <CustomText style={styles.defaultText}>
              {btnLabel}
            </CustomText>
          )
        )}
      </LinearGradient>
    </TouchableOpacity>
  );
};

export default memo(ClockInButton);
