import React, { useState, useEffect } from 'react';
import { View, Text, Image, TouchableOpacity, StyleSheet, ImageBackground, ActivityIndicator } from 'react-native';
import BackIcon from '../../components/BackIcon';
import fontSize from '../../utils/fontsizeUtils';
import widthUtils from '../../utils/widthUtils';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';

type RootStackParamList = {
  Home: undefined;
  ShippingDetails: undefined;
  Main: undefined;
  // Add other screens as needed
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList>;

export const ShippingDetailsSection = () => {
  const [shippingMethod, setShippingMethod] = useState('maritime'); // 'maritime' or 'airway'
  const [isLoading, setIsLoading] = useState(true);
  const navigation = useNavigation<NavigationProp>();

  useEffect(() => {
    // Preload images
    const preloadImages = async () => {
      try {
        await Promise.all([
          Image.prefetch(Image.resolveAssetSource(require('../../../assets/img/image_f67fe9bc.png')).uri),
          Image.prefetch(Image.resolveAssetSource(require('../../../assets/img/feijiback.png')).uri)
        ]);
        setIsLoading(false);
      } catch (error) {
        console.error('Error preloading images:', error);
        setIsLoading(false);
      }
    };

    preloadImages();
  }, []);

  const handleShippingMethodChange = (method: 'maritime' | 'airway') => {
    setShippingMethod(method);
  };

  // Get background image based on shipping method
  const getBackgroundImage = () => {
    return shippingMethod === 'maritime' 
      ? require('../../../assets/img/image_f67fe9bc.png')
      : require('../../../assets/img/feijiback.png');
  };

  return (
    <View style={styles.container}>
      {isLoading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#005EE4" />
        </View>
      ) : (
        <ImageBackground
          source={getBackgroundImage()}
          style={styles.backgroundImage}
        >
          <View style={styles.contentContainer}>
            <View style={styles.timeShippingSection}>
              <View style={styles.shippingCostContainer}>
                <View style={styles.svgContainer}>
                  <TouchableOpacity 
                    style={styles.backButton}
                    onPress={() => {
                      navigation.goBack();
                    }}
                  >
                    <BackIcon size={fontSize(18)} color="#ffffff"/>
                  </TouchableOpacity>
                </View>
                <Text style={styles.shippingCostLabelTextStyle}>运费</Text>
              </View>
            </View>

            {/* Calculator Form */}
            <View style={styles.shippingCalculatorContainer}>
              <View style={styles.flexColumnCenteredWithSelect}>
                {/* Shipping Method Selection */}
                <View style={styles.shippingMethodContainer}>
                  {/* Maritime Option */}
                  <TouchableOpacity 
                    style={[
                      styles.maritimeInfoBox, 
                      shippingMethod === 'maritime' ? styles.activeShippingMethod : {}
                    ]}
                    onPress={() => handleShippingMethodChange('maritime')}
                  >
                    <View style={styles.svgContainer1}>
                      <Image 
                        source={require('../../../assets/img/海运 (1) 1.png')}
                        style={{width: widthUtils(24, 24).width, height: widthUtils(24, 24).height, 
                          tintColor: shippingMethod === 'maritime' ? '#fff' : '#747474'}}
                      />
                    </View>
                    <Text style={[
                      styles.maritimeHeadingStyle,
                      shippingMethod === 'maritime' ? {} : {color: '#747474'}
                    ]}>海运</Text>
                  </TouchableOpacity>

                  {/* Airway Option */}
                  <TouchableOpacity 
                    style={[
                      styles.airwayInfoContainer,
                      shippingMethod === 'airway' ? styles.activeShippingMethod : {}
                    ]}
                    onPress={() => handleShippingMethodChange('airway')}
                  >
                    <View style={styles.svgContainer2}>
                      <Image 
                        source={require('../../../assets/img/空运 1.png')}
                        style={{width: widthUtils(24, 24).width, height: widthUtils(24, 24).height, tintColor: shippingMethod === 'airway' ? '#fff' : '#747474'}}
                      />
                    </View>
                    <Text style={[
                      styles.flightModeLabel,
                      shippingMethod === 'airway' ? {color: '#fff'} : {}
                    ]}>空运</Text>
                  </TouchableOpacity>
                </View>

                {/* Parcel Volume Form */}
                <View style={styles.parcelVolumeFormContainer}>
                  {/* Dropdown Select - Replace with actual picker component */}
                  <View style={styles.parcelVolumeContainer}>
                    <Text style={styles.parcelVolumeLabel}>包裹体积</Text>
                    <View style={styles.volumeInputContainer}>
                      <Text style={styles.volumePromptTextStyle}>请输入包裹体积</Text>
                      <Text style={styles.volumeLabel}>{shippingMethod === 'maritime' ? 'm³' : 'kg'}</Text>
                    </View>
                  </View>

                  <View style={styles.parcelVolumeContainer}>
                    <Text style={styles.parcelVolumeLabel}>包裹体积</Text>
                    <View style={styles.volumeInputContainer}>
                      <Text style={styles.volumePromptTextStyle}>请输入包裹体积</Text>
                      <Text style={styles.volumeLabel}>{shippingMethod === 'maritime' ? 'm³' : 'kg'}</Text>
                    </View>
                  </View>
                </View>

                {/* Submit Button */}
                <TouchableOpacity style={styles.primaryButton}>
                  <Text style={{color: 'white', fontSize: fontSize(16), fontFamily: 'PingFang SC', fontWeight: '600'}}>
                  计算运费
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </ImageBackground>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    flex: 1,
  },
  backgroundImage: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover',
  },
  contentContainer: {
    flex: 1,
    padding: 15,
  },
  timeShippingSection: {
    flexDirection: 'column',
  },
  timeAndImageContainer: {
    flexDirection: 'row',
    gap: 8,
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: 36,
  },
  timeDisplay: {
    width: widthUtils(42, 42).width,
    fontSize: fontSize(17),
    fontFamily: 'SF Pro',
    fontWeight: '600',
    color: 'white',
    textAlign: 'center',
  },
  timeImageContainer: {
    width: widthUtils(54, 154).width,
    height:  widthUtils(54, 154).height,
  },
  shippingCostContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 20,
    justifyContent: 'center',
  },
  svgContainer: {
    width: widthUtils(18, 18).width,
    height: widthUtils(18, 18).height,
    position: 'absolute',
    left: 0,
  },
  shippingCostLabelTextStyle: {
    fontSize: fontSize(20),
    lineHeight: 22,
    fontFamily: 'Microsoft YaHei UI',
    fontWeight: '700',
    color: 'white',
    textAlign: 'center',
    textTransform: 'capitalize',
    width: '100%',
  },
  shippingCalculatorContainer: {
    marginTop: widthUtils(100,100).height,
    paddingTop: 18,
    paddingRight: 20,
    paddingBottom: 28,
    paddingLeft: 20,
    backgroundColor: 'white',
    borderRadius: 5,
    justifyContent: 'center',
  },
  flexColumnCenteredWithSelect: {
    flexDirection: 'column',
    justifyContent: 'center',
  },
  shippingMethodContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: widthUtils(80, 80).height,
    paddingRight: 10,
    paddingLeft: 10,
    backgroundColor: '#f2f6ff',
    borderRadius: 5,
  },
  maritimeInfoBox: {
    height: widthUtils(60, 60).height,
    paddingRight: 19,
    paddingLeft: 20,
    backgroundColor: '#f2f6ff',
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center',
  },
  airwayInfoContainer: {
    height: widthUtils(60, 60).height,
    paddingRight: 24,
    paddingLeft: 25,
    marginLeft: 10,
    backgroundColor: '#f2f6ff',
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center',
  },
  activeShippingMethod: {
    backgroundColor: '#005EE4',
  },
  svgContainer1: {
    width: widthUtils(32, 32).width,
    height: widthUtils(32, 32).height,
  },
  maritimeHeadingStyle: {
    marginTop: -5,
    fontSize: fontSize(14),
    fontFamily: 'Segoe UI',
    fontWeight: '700',
    color: 'white',
    textTransform: 'capitalize',
  },
  svgContainer2: {
    width: widthUtils(24, 24).width,
    height: widthUtils(24, 24).height,
  },
  flightModeLabel: {
    marginTop: -2,
    fontSize: fontSize(14),
    fontFamily: 'Segoe UI',
    fontWeight: '400',
    color: '#747474',
    textTransform: 'capitalize',
  },
  parcelVolumeFormContainer: {
    marginTop: 16,
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: '#dbdce0',
  },
  optionContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: widthUtils(60, 60).height,
    paddingRight: 6,
    paddingLeft: 8,
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: '#dbdce0',
    borderTopLeftRadius: 5,
    borderTopRightRadius: 5,
  },
  pingfangTextSelect: {
    fontSize: fontSize(12),
    fontFamily: 'PingFang SC',
    fontWeight: '500',
    color: '#646472',
  },
  iconSelectDropdown: {
    width: widthUtils(24, 24).width,
    height: widthUtils(24, 24).height,
    marginLeft: 10,
  },
  parcelVolumeContainer: {
    width: '100%',
    paddingTop: 6,
    paddingRight: 8,
    paddingBottom: 10,
    paddingLeft: 8,
    marginTop: -1,
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: '#dbdce0',
    borderBottomLeftRadius: 5,
    borderBottomRightRadius: 5,
  },
  parcelVolumeLabel: {
    fontSize: fontSize(12),
    fontFamily: 'PingFang SC',
    fontWeight: '600',
    color: '#646472',
  },
  volumeInputContainer: {
    flexDirection: 'row',
    gap: 8,
    alignItems: 'center',
    justifyContent: 'space-between',
    width: '100%',
  },
  volumePromptTextStyle: {
    fontSize: fontSize(16),
    lineHeight: 22,
    fontFamily: 'PingFang SC',
    fontWeight: '400',
    color: '#807e7e',
  },
  volumeLabel: {
    fontSize: fontSize(16),
    lineHeight: 22,
    fontFamily: 'PingFang SC',
    fontWeight: '600',
    color: '#1c284e',
  },
  primaryButton: {
    width:'100%',
    height: widthUtils(50, 50).height,
    marginTop: 34,
    backgroundColor: '#002fa7',
    borderRadius: 25,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backButton: {
    padding: 10,
    borderRadius: 20,
    zIndex: 10,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f2f6ff',
  },
});
