import React, { useEffect, useMemo, useState } from 'react';
import { Modal, StyleSheet, TouchableOpacity, Dimensions } from 'react-native';
import { View } from 'tamagui';
import CustomText from '@/components/common/CustomText.jsx';
import { Image as ExpoImage } from 'expo-image';
import { useClockInStore } from '@/stores/clockIn';
import { wp } from '@/utils/ui/screenUtils';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, withDelay, Easing, interpolate, Extrapolation, runOnJS } from 'react-native-reanimated';
import { useTranslation } from '@/node_modules/react-i18next';
const EASE_OUT = Easing.bezier(0.0, 0.0, 0.2, 1.0);
const EASE_IN = Easing.bezier(0.4, 0.0, 1.0, 1.0);
const OPEN_DURATION = 250;
const CLOSE_DURATION = 250;

const ClockInPopup = ({ visible, onClose }) => {

  const clockType = useClockInStore(state => state.clockType);
  const { i18n } = useTranslation();

  // 动画控制：挂载控制 + 进度值
  const [mounted, setMounted] = useState(visible);
  const maskProgress = useSharedValue(0);
  const contentProgress = useSharedValue(0);
  // 显示快照
  const [displayType, setDisplayType] = useState(clockType);
  // 每次展示期间只选择一次图片变体，保持稳定
  const [variantIndex, setVariantIndex] = useState(0);

  // 语言映射：i18n 语言 -> 我们的图片分类
  const langVariant = useMemo(() => {
    const lang = (i18n.resolvedLanguage || i18n.language || '').toLowerCase();
    // 简体：zh-CN / zh / zh-cn
    if (lang.startsWith('zh')) {
      if (lang.includes('tw') || lang.includes('hk') || lang.includes('mo')) {
        return 'zh-Hant';
      }
      return 'zh-Hans';
    }
    // 英文：en / en-us / en-xx
    if (lang.startsWith('en')) return 'en';

    return 'zh-Hans';
  }, [i18n.resolvedLanguage, i18n.language]);

  const closeLabel = useMemo(() => {
    switch (langVariant) {
      case 'zh-Hant':
        return '關閉';
      case 'en':
        return 'Close';
      default:
        return '关闭';
    }
  }, [langVariant]);

  useEffect(() => {
    if (visible) {

      setMounted(true);
  
      setDisplayType(clockType);
      maskProgress.value = withTiming(1, { duration: OPEN_DURATION, easing: EASE_OUT });
      contentProgress.value = withDelay(60, withTiming(1, { duration: OPEN_DURATION, easing: EASE_OUT }));
    } else {

      if (!mounted) return;
      contentProgress.value = withTiming(0, { duration: CLOSE_DURATION, easing: EASE_IN });
      maskProgress.value = withDelay(60, withTiming(0, { duration: CLOSE_DURATION, easing: EASE_IN }, (finished) => {
        if (finished) {
          runOnJS(setMounted)(false);
          // 在卸载时清空本地快照
          runOnJS(setDisplayType)(null);
        }
      }));
    }
  }, [visible]);

  // 若在显示期间类型变化，更新快照；关闭期间不更新，保留现有内容做退场动画
  useEffect(() => {
    if (visible) {
      setDisplayType(clockType);
      // 在显示期间类型变化时，刷新一次随机选择
      const hasVariants = [1, 2, 3, 4].includes(clockType);
      setVariantIndex(hasVariants ? (Math.random() < 0.5 ? 0 : 1) : 0);
    }
  }, [clockType, visible]);

  // 保留语言显示与基本动画逻辑，不做图片防抖处理

  const maskStyle = useAnimatedStyle(() => ({
    opacity: maskProgress.value,
  }));

  const contentAnimStyle = useAnimatedStyle(() => {
    const scale = interpolate(contentProgress.value, [0, 1], [0, 1], Extrapolation.CLAMP);
    return {
      opacity: contentProgress.value,
      transform: [{ scale }],
    };
  });

  const handleClose = () => {
    onClose && onClose();
  };
  const renderClockTypeContent = () => {
    const language = langVariant; 
    switch (displayType) {
      case 1: // 工作日早上上班
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(341.675), height: wp(398.8) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/zu14908.webp')
                  : require('@/assets/images/organized_images/sadf4909.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(341.675), height: wp(398.8) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/zht4908.webp')
                  : require('@/assets/images/organized_images/zht4909.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(341.675), height: wp(398.8) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/en14908.webp')
                  : require('@/assets/images/organized_images/en4909.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 2: // 工作日晚上下班
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(341.675), height: wp(398.8) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/x4910.webp')
                  : require('@/assets/images/organized_images/zus4911.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(341.675), height: wp(398.8) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/zht4910.webp')
                  : require('@/assets/images/organized_images/zht4911.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(341.675), height: wp(398.8) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/en4910.webp')
                  : require('@/assets/images/organized_images/en4911.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 3: // 休息日上班
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(326.5), height: wp(384) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/df4912.webp')
                  : require('@/assets/images/organized_images/cz4913.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(326.5), height: wp(384) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/zht4912.webp')
                  : require('@/assets/images/organized_images/zht4913.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(326.5), height: wp(384) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/en4912.webp')
                  : require('@/assets/images/organized_images/en4913.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 4: // 休息日下班
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(326.5), height: wp(384) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/dfd4914.webp')
                  : require('@/assets/images/organized_images/cvc4915.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(326.5), height: wp(384) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/zht4914.webp')
                  : require('@/assets/images/organized_images/zht4915.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(326.5), height: wp(384) }}
                source={variantIndex === 0
                  ? require('@/assets/images/organized_images/en4914.webp')
                  : require('@/assets/images/organized_images/en4915.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 5: // 早退卡
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(320.68), height: wp(422.06) }}
                source={require('@/assets/images/organized_images/fg4916.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(320.68), height: wp(422.06) }}
                source={require('@/assets/images/organized_images/zht4916.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(320.68), height: wp(422.06) }}
                source={require('@/assets/images/organized_images/en4916.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 6: // 迟到卡
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(330.8), height: wp(424.5) }}
                source={require('@/assets/images/organized_images/cvcvc4918.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(330.8), height: wp(424.5) }}
                source={require('@/assets/images/organized_images/zht4918.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(330.8), height: wp(424.5) }}
                source={require('@/assets/images/organized_images/en4918.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 7: // 工作日中午下班
        return (
          <View style={[styles.wrap1, { width: wp(326), height: wp(384) }]}> 
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(326), height: wp(384) }}
                source={require('@/assets/images/organized_images/dfdfd4919.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(326), height: wp(384) }}
                source={require('@/assets/images/organized_images/zht4919.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(326), height: wp(384) }}
                source={require('@/assets/images/organized_images/en4919.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 8: // 工作日中午上班
        return (
          <View style={[styles.wrap1, { width: wp(326), height: wp(384) }]}> 
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(326), height: wp(384) }}
                source={require('@/assets/images/organized_images/dfdf4920.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(326), height: wp(384) }}
                source={require('@/assets/images/organized_images/zht4920.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(326), height: wp(384) }}
                source={require('@/assets/images/organized_images/en4920.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      case 9: // 更新打卡
        return (
          <View style={styles.wrap1}>
            {language === 'zh-Hans' && (
              <ExpoImage
                style={{ width: wp(351.8), height: wp(391.1) }}
                source={require('@/assets/images/organized_images/gx4921.webp')}
                contentFit="cover"
              />
            )}
            {language === 'zh-Hant' && (
              <ExpoImage
                style={{ width: wp(351.8), height: wp(391.1) }}
                source={require('@/assets/images/organized_images/zht4921.webp')}
                contentFit="cover"
              />
            )}
            {language === 'en' && (
              <ExpoImage
                style={{ width: wp(351.8), height: wp(391.1) }}
                source={require('@/assets/images/organized_images/en4921.webp')}
                contentFit="cover"
              />
            )}
          </View>
        );

      default:
        return null;
    }
  };

  if (!mounted || displayType === null || displayType === undefined) {
    return null;
  }

  return (
    <Modal
      visible={mounted}
      transparent
      animationType="none"
      presentationStyle="overFullScreen"
      onRequestClose={handleClose}
    >
      <Animated.View style={[styles.modalMask, maskStyle]}>

        <TouchableOpacity style={StyleSheet.absoluteFill} activeOpacity={1} onPress={handleClose} />
        <Animated.View pointerEvents="box-none" style={[styles.modalWrapper, contentAnimStyle]}>
          {renderClockTypeContent()}
          <TouchableOpacity style={styles.wrap2} onPress={handleClose} activeOpacity={0.8}>
            <CustomText style={{ fontSize: wp(16), color: '#000' }}>{closeLabel}</CustomText>
          </TouchableOpacity>
        </Animated.View>
      </Animated.View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  modalMask: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalWrapper: {
    alignItems: 'center',
  },
  wrap1: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  wrap2: {
    marginTop: wp(12),
    width: wp(203),
    height: wp(51),
    borderRadius: wp(8),
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
});

export default ClockInPopup;
