import React, {useState, useRef} from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  FlatList,
  Image,
  ActivityIndicator,
  RefreshControl,
  Animated,
  PanResponder,
  Dimensions,
} from 'react-native';
import styles from './style';
import FAB from '../../components/FAB/fab';
import SubButton from '../../components/FAB/sub_button';
import R from '../../assets/R';
import * as SCREENNAME from '../../routers/ScreenNames';
import {useNavigation} from '@react-navigation/native';

const EmailHomeView = props => {
  const {groupedEmails, loading, onEmailPress, onRefresh, formatEmailDate} =
    props;

  const navigation = useNavigation();
  const screenWidth = Dimensions.get('window').width;

  const [localGroupedEmails, setLocalGroupedEmails] = useState(groupedEmails);
  const [swipedEmailId, setSwipedEmailId] = useState(null);

  React.useEffect(() => {
    setLocalGroupedEmails(groupedEmails);
  }, [groupedEmails]);

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#007AFF" />
        <Text style={styles.loadingText}>Đang tải email...</Text>
      </View>
    );
  }

  const SwipeableEmailItem = ({item, onDelete}) => {
    const translateX = useRef(new Animated.Value(0)).current;
    const deleteThreshold = screenWidth * 0.3;

    React.useEffect(() => {
      if (swipedEmailId !== null && swipedEmailId !== item.id) {
        Animated.spring(translateX, {
          toValue: 0,
          useNativeDriver: true,
        }).start();
      }
    }, [swipedEmailId]);

    const panResponder = PanResponder.create({
      onMoveShouldSetPanResponder: (evt, gestureState) => {
        // console.log('gestureState L1', gestureState);
        const moveX = Math.abs(gestureState.dx);
        // console.log('moveX', moveX);
        const isSwipingLeft = moveX < deleteThreshold;
        // console.log('isSwipingLeft', isSwipingLeft);
        return isSwipingLeft;
      },
      onPanResponderMove: (evt, gestureState) => {
        // console.log('gestureState L2', gestureState.dx);
        if (
          gestureState.vx < 0 &&
          gestureState.dx > -100 &&
          gestureState.dx < 0
        ) {
          console.log('gestureState L2', gestureState.dx, gestureState.vx);
          translateX.setValue(-100);
          setSwipedEmailId(item.id);
        } else {
          translateX.setValue(0);
        }
        // if (gestureState.dx > -100 && gestureState.dx < 0  ) {
        //   translateX.setValue(-100);
        // }else if(gestureState.dx >0){
        //   translateX.setValue(0);
        // }
      },
      onPanResponderRelease: (evt, gestureState) => {
        // console.log('gestureState L3', gestureState);
        if (Math.abs(gestureState.dx) >= 0 && gestureState.vx === 0) {
          console.log('gestureState L3', gestureState.dx, gestureState.vx);
          // // Nếu di chuyển đủ lớn, vuốt để xóa
          // if (gestureState.dx < -deleteThreshold ) {
          //   // Hiển thị nút xóa
          //   Animated.timing(translateX, {
          //     toValue: -100,
          //     duration: 300,
          //     useNativeDriver: true,
          //   }).start();
          //   setSwipedEmailId(item.id);
          // } else {
          //   // Nếu di chuyển sang phải (hoặc không vuốt đủ xa), quay lại vị trí ban đầu
          //   Animated.spring(translateX, {
          //     toValue: 0,
          //     useNativeDriver: true,
          //   }).start(() => {
          //     setSwipedEmailId(null);
          //   });
          // }

          navigation.navigate(SCREENNAME.DETAILEMAIL);
        }
        // } else {
        //   // Nếu không có chuyển động đủ lớn (chỉ bấm), chuyển tới màn hình chi tiết
        //   navigation.navigate(SCREENNAME.DETAILEMAIL);
        // }
      },
    });

    const deleteOpacity = translateX.interpolate({
      inputRange: [-deleteThreshold, 0],
      outputRange: [1, 0],
      extrapolate: 'clamp',
    });

    const handleDeletePress = () => {
      // Delete immediately without animation
      onDelete(item.id);
      setSwipedEmailId(null);
    };

    const handleCancelPress = () => {
      Animated.spring(translateX, {
        toValue: 0,
        useNativeDriver: true,
      }).start(() => {
        setSwipedEmailId(null);
      });
    };
    const handleEmailPress = () => {
      if (swipedEmailId === null) {
        navigation.navigate(SCREENNAME.DETAILEMAIL);
      }
    };

    return (
      <View style={styles.swipeContainer}>
        <Animated.View
          style={[styles.deleteBackground, {opacity: deleteOpacity}]}>
          <TouchableOpacity
            style={styles.deleteButton}
            onPress={handleDeletePress}>
            <Image source={R.images.icDelete} style={styles.deleteIcon} />
            <Text style={styles.deleteText}>Xóa</Text>
          </TouchableOpacity>
        </Animated.View>

        <Animated.View
          style={[{transform: [{translateX}]}]}
          {...panResponder.panHandlers}>
          <TouchableOpacity
            style={[styles.emailItem, !item.isRead && styles.unreadEmail]}
            onPress={handleEmailPress}>
            <View style={styles.avatarContainer}>
              <View style={styles.avatar}>
                <Text style={styles.avatarText}>
                  {item.sender.charAt(0).toUpperCase()}
                </Text>
              </View>
            </View>

            <View style={styles.emailContent}>
              <View style={styles.emailHeader}>
                <Text
                  style={[
                    styles.senderName,
                    !item.isRead && styles.unreadText,
                  ]}>
                  {item.sender}
                </Text>
              </View>

              <Text
                style={[styles.emailSubject, !item.isRead && styles.unreadText]}
                numberOfLines={1}>
                {item.subject}
              </Text>

              <Text
                style={[
                  styles.emailPreview,
                  !item.isRead && styles.unreadEmail,
                ]}
                numberOfLines={2}>
                {item.preview}
              </Text>
            </View>

            <View
              style={{
                justifyContent: 'center',
                alignItems: 'flex-end',
                position: 'absolute',
                right: 15,
                top: 10,
              }}>
              <Text style={styles.emailDate}>
                {`${item.date.getDate().toString().padStart(2, '0')}/${(
                  item.date.getMonth() + 1
                )
                  .toString()
                  .padStart(2, '0')}/${item.date.getFullYear()}`}
              </Text>
              {item.hasAttachment && (
                <View style={styles.attachmentIndicator}>
                  <Text style={styles.attachmentCount}>2</Text>
                </View>
              )}
            </View>
          </TouchableOpacity>
        </Animated.View>
      </View>
    );
  };

  const handleDeleteEmail = emailId => {
    const updatedGroupedEmails = {};

    Object.keys(localGroupedEmails).forEach(dateKey => {
      const filteredEmails = localGroupedEmails[dateKey].filter(
        email => email.id !== emailId,
      );
      if (filteredEmails.length > 0) {
        updatedGroupedEmails[dateKey] = filteredEmails;
      }
    });

    setLocalGroupedEmails(updatedGroupedEmails);
  };

  const renderEmailItem = ({item}) => (
    <SwipeableEmailItem item={item} onDelete={handleDeleteEmail} />
  );

  const renderDateSection = (dateLabel, emailsForDate) => (
    <View key={dateLabel} style={styles.dateSection}>
      <Text style={styles.dateSectionHeader}>{dateLabel}</Text>
      {emailsForDate.map(email => (
        <View key={email.id}>{renderEmailItem({item: email})}</View>
      ))}
    </View>
  );

  return (
    <View style={styles.container}>
      <View style={styles.body}>
        <FlatList
          data={Object.keys(localGroupedEmails)}
          keyExtractor={item => item}
          renderItem={({item: dateLabel}) =>
            renderDateSection(dateLabel, localGroupedEmails[dateLabel])
          }
          refreshControl={
            <RefreshControl
              refreshing={loading}
              onRefresh={onRefresh}
              colors={['#007AFF']}
            />
          }
          showsVerticalScrollIndicator={false}
          contentContainerStyle={styles.listContainer}
        />
      </View>

      <FAB>
        <SubButton
          onPress={() => navigation.navigate(SCREENNAME.SENDEMAIL)}
          label="Soạn email"
          images={R.images.icEdit}
          backgroundColor={R.colors.orange}
        />
      </FAB>
    </View>
  );
};

export default EmailHomeView;
