import { StyleSheet, TouchableOpacity} from 'react-native';
import { useEffect, useState, memo } from 'react';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, runOnJS } from 'react-native-reanimated';
import { Button, YStack, XStack, useTheme } from 'tamagui';
import CustomText from '@/components/common/CustomText.jsx';
import LoadingSpinner from '@/components/ui/LoadingSpinner';
import { wp } from '@/utils/ui/screenUtils';
import { InputField } from './InputField';
import { AgreementCheckbox } from './AgreementCheckbox';
import { useTranslation } from 'react-i18next';

const styles = StyleSheet.create({
  loginButton: {
    height: wp(48),
    borderRadius: wp(8),
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export const PasswordPanel = ({
  selectedRegion,
  telNum,
  setTelNum,
  clearPhone,
  handleRegionPress,
  password,
  setPassword,
  clearPassword,
  showPassword,
  togglePasswordVisibility,
  passwordAnimatedStyle,
  changeLoginType,
  agreementAccepted,
  handleAgreementChange,
  oneButtonColor,
  primaryColor,
  handleLogin,
  loading,
  loginType,
  agreementShakeKey,
}) => {
  const { t } = useTranslation('login');
  const [toggleLabel, setToggleLabel] = useState(loginType === 'password' ? t('toggle.toCode') : t('toggle.toPassword'));
  const [buttonLabel, setButtonLabel] = useState(loginType === 'password' ? t('button.login') : t('button.getCode'));

  // Avoid calling t() inside Reanimated worklets. Compute labels on JS thread.
  const updateToggleLabel = (type) => {
    setToggleLabel(type === 'password' ? t('toggle.toCode') : t('toggle.toPassword'));
  };
  const updateButtonLabel = (type) => {
    setButtonLabel(type === 'password' ? t('button.login') : t('button.getCode'));
  };

  const toggleOpacity = useSharedValue(1);
  const buttonOpacity = useSharedValue(1);

  const toggleAnimStyle = useAnimatedStyle(() => ({
    opacity: toggleOpacity.value,
  }));

  const buttonTextAnimStyle = useAnimatedStyle(() => ({
    opacity: buttonOpacity.value,
  }));
  const spinnerSize = wp(25);
  const spinnerGap = wp(20);

  const spinnerAnimStyle = useAnimatedStyle(() => ({
    width: withTiming(loading ? spinnerSize : 0, { duration: 200 }),
    opacity: withTiming(loading ? 1 : 0, { duration: 200 }),
    marginRight: withTiming(loading ? spinnerGap : 0, { duration: 200 }),
  }));

  useEffect(() => {

    toggleOpacity.value = withTiming(0, { duration: 120 }, (finished) => {
      if (finished) {
        runOnJS(updateToggleLabel)(loginType);
        toggleOpacity.value = withTiming(1, { duration: 180 });
      }
    });

    buttonOpacity.value = withTiming(0, { duration: 120 }, (finished) => {
      if (finished) {
        runOnJS(updateButtonLabel)(loginType);
        buttonOpacity.value = withTiming(1, { duration: 180 });
      }
    });
  }, [loginType, t]);

  return (
    <YStack>
      <YStack style={{ marginBottom: wp(10) }}>
        <InputField
          zone={selectedRegion.zone}
          label=""
          placeholder={t('input.phonePlaceholder')}
          value={telNum}
          onChangeText={setTelNum}
          onClear={clearPhone}
          isPhone
          onRegionPress={handleRegionPress}
        />
        
        <Animated.View style={passwordAnimatedStyle}>
          <InputField
            label={t('input.passwordLabel')}
            placeholder={t('input.passwordPlaceholder')}
            value={password}
            onChangeText={setPassword}
            onClear={clearPassword}
            secureTextEntry={!showPassword}
            showPassword={showPassword}
            onTogglePassword={togglePasswordVisibility}
          />
        </Animated.View>
      </YStack>
      
      <XStack style={{ alignItems: 'center', justifyContent: 'flex-end' ,paddingRight:wp(10)}}>
        <TouchableOpacity  onPress={changeLoginType} disabled={loading}>
          <Animated.View style={[{ height: wp(40) }, toggleAnimStyle]}>
            <CustomText style={{ color: primaryColor, fontFamily: 'Regular' }}>
              {toggleLabel}
            </CustomText>
          </Animated.View>
        </TouchableOpacity>
      </XStack>

      <AgreementCheckbox 
        agreementAccepted={agreementAccepted}
        onAgreementChange={handleAgreementChange}
        shakeKey={agreementShakeKey}
      />
      
      <YStack>
        <Button
          style={[
            styles.loginButton,
            {
              backgroundColor: oneButtonColor ? primaryColor : '#D9D9DB',
            },
          ]}
          onPress={handleLogin}
          disabled={!oneButtonColor}
        >
          <XStack alignItems="center" justifyContent="center">
            <Animated.View
              style={[
                { overflow: 'hidden', width: 0, alignItems: 'center', marginRight: 0 },
                spinnerAnimStyle,
              ]}
            >
              <LoadingSpinner size={spinnerSize} color="white" animating={loading} />
            </Animated.View>
            <Animated.View style={buttonTextAnimStyle}>
              <CustomText style={{ color: 'white', fontSize: wp(16) }}>
                {buttonLabel}
              </CustomText>
            </Animated.View>
          </XStack>
        </Button>
      </YStack>
    </YStack>
  );
};

export default memo(PasswordPanel);