import AnimatedIcon from 'components/AnimatedIcon';
import AppText from 'components/AppText';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  FlatList,
  Modal,
  Pressable,
  StyleSheet,
  useWindowDimensions,
  View,
} from 'react-native';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import Auto from 'svg/Auto';
import Avia from 'svg/Avia';
import BoxCreate from 'svg/BoxCreate';
import BoxSuccess from 'svg/BoxSuccess';
import { HomeStyle } from './styled';

const PartyCarousel = ({
  aviaData,
  activeTab,
  autoData,
}: {
  autoData: any;
  aviaData: any;
  activeTab: 'AUTO' | 'AVIA';
}) => {
  const { width: screenWidth } = useWindowDimensions();
  const cardWidth = screenWidth * 0.95;
  const styles = useMemo(() => HomeStyle(), []);
  const { t } = useTranslation();

  // animatsiya
  const opacity = useSharedValue(0);
  const translateY = useSharedValue(20);

  useEffect(() => {
    opacity.value = 1;
    translateY.value = 0;
    opacity.value = withTiming(1, { duration: 500 });
    translateY.value = withTiming(0, { duration: 500 });
  }, [activeTab]);

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
    transform: [{ translateY: translateY.value }],
  }));

  // status config
  const statusConfig: any = {
    COLLECTING: {
      backgroundColor: '#28A7E8',
      textColor: '#fff',
      icon: <BoxCreate color="#fff" width={18} height={18} />,
    },
    ON_THE_WAY: {
      backgroundColor: '#5eda62ff',
      textColor: '#fff',
      icon: <Auto color="#fff" width={18} height={18} />,
    },
    IN_WAREHOUSE: {
      backgroundColor: '#28A7E8',
      textColor: '#fff',
      icon: <BoxSuccess color="#fff" width={18} height={18} />,
    },
    IN_CUSTOMS: {
      backgroundColor: '#28A7E8',
      textColor: '#fff',
      icon: <Avia color="#fff" width={18} height={18} />,
    },
    DEFAULT: {
      backgroundColor: '#f0f0f0',
      textColor: '#555',
      icon: <BoxCreate color="#28A7E8" width={18} height={18} />,
    },
  };

  // calendarList faqat activeTab uchun
  const calendarList = useMemo(() => {
    const data: any[] = [];
    const weekdays = [
      { key: 'sunday', label: 'Ya' },
      { key: 'monday', label: 'Du' },
      { key: 'tuesday', label: 'Se' },
      { key: 'wednesday', label: 'Cho' },
      { key: 'thursday', label: 'Pa' },
      { key: 'friday', label: 'Ju' },
      { key: 'saturday', label: 'Sha' },
    ];

    const prepareList = (calendar: any, type: 'auto' | 'avia') => {
      if (!calendar) return;
      data.push({
        cargo: type,
        party: calendar.cargoType,
        isAni: true,
        start: weekdays.map((day, index) => {
          const start = new Date(calendar.weekStartDate);
          start.setDate(start.getDate() + index);
          const status =
            calendar[day.key as keyof typeof calendar] || 'DEFAULT';
          return {
            date: start.toISOString().split('T')[0],
            weekday: day.label,
            status,
          };
        }),
      });
    };

    if (activeTab === 'AUTO') {
      prepareList(autoData, 'auto');
    } else if (activeTab === 'AVIA') {
      prepareList(aviaData, 'avia');
    }

    return data;
  }, [autoData, aviaData, activeTab]);

  const flatListRef = useRef<FlatList>(null);
  const today = useMemo(() => {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    return d;
  }, []);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [modalVisible, setModalVisible] = useState(false);

  const renderItem = ({ item, index }: { item: any; index: number }) => {
    const isLast = index === calendarList.length - 1;
    return (
      <Pressable
        onPress={() => {
          setSelectedItem(item);
          setModalVisible(true);
        }}
        style={[
          styles.autoContainer,
          {
            width: cardWidth,
            marginRight: isLast ? 0 : 10,
          },
        ]}
      >
        {item.isAni && (
          <>
            <FlatList
              data={item.start}
              numColumns={7}
              keyExtractor={(_, idx) => idx.toString()}
              renderItem={({ item: day }) => {
                const dateObj = new Date(day.date);
                const isToday = dateObj.toDateString() === today.toDateString();
                const config = statusConfig[day.status] || statusConfig.DEFAULT;

                let backgroundColor = config.backgroundColor;
                let textColor = config.textColor;

                if (isToday) {
                  backgroundColor = '#22b1f88f';
                  textColor = '#fff';
                }

                if (day.weekday === 'Ju') {
                  backgroundColor = '#4CAF50';
                  textColor = '#fff';
                }

                return (
                  <View
                    style={[
                      styles.date,
                      {
                        backgroundColor,
                        marginRight: 5,
                      },
                    ]}
                  >
                    <AppText style={[styles.dateLabel, { color: textColor }]}>
                      {day.date.slice(-2)}
                    </AppText>
                    <AppText style={[styles.dateLabel, { color: textColor }]}>
                      {t(day.weekday)}
                    </AppText>
                  </View>
                );
              }}
              showsHorizontalScrollIndicator={false}
            />

            <View style={styles.divider} />

            <View style={styles.rowFull}>
              <AppText style={styles.reysTitle}>
                {item.cargo.toUpperCase()}
              </AppText>
              <View style={styles.animatedIconWrapper}>
                <AnimatedIcon type={activeTab} />
              </View>
            </View>
          </>
        )}
      </Pressable>
    );
  };

  return (
    <Animated.View style={animatedStyle}>
      <FlatList
        data={calendarList}
        keyExtractor={(_, index) => index.toString()}
        renderItem={renderItem}
        horizontal
        snapToInterval={cardWidth + 10}
        decelerationRate="fast"
        contentContainerStyle={{
          paddingHorizontal: (screenWidth - cardWidth) / 2,
          padding: 10,
        }}
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        getItemLayout={(_, index) => ({
          length: cardWidth,
          offset: cardWidth * index,
          index,
        })}
      />
      <Modal
        transparent
        visible={modalVisible}
        animationType="fade"
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={modalStyles.modalOverlay}>
          <View style={modalStyles.modalContent}>
            <AppText style={modalStyles.modalTitle}>
              {t('Yetkazish tafsilotlari')}
            </AppText>
            {selectedItem &&
              selectedItem.start.map((day: any, idx: number) => (
                <AppText
                  key={idx}
                  style={{ textAlign: 'left', width: '100%', marginTop: 2 }}
                >
                  {day.date} - {t(day.weekday)} - {t(day.status)}
                </AppText>
              ))}
            <Pressable
              onPress={() => setModalVisible(false)}
              style={modalStyles.closeButton}
            >
              <AppText style={{ color: '#fff', textAlign: 'center' }}>
                {t('Yopish')}
              </AppText>
            </Pressable>
          </View>
        </View>
      </Modal>
    </Animated.View>
  );
};

export default PartyCarousel;

const modalStyles = StyleSheet.create({
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    width: '80%',
    backgroundColor: '#fff',
    padding: 20,
    borderRadius: 12,
    alignItems: 'center',
  },
  modalTitle: {
    fontSize: 18,
    fontFamily: 'GolosText-Bold',
    marginBottom: 12,
  },
  closeButton: {
    marginTop: 20,
    backgroundColor: '#28A7E8',
    paddingVertical: 8,
    width: '100%',
    textAlign: 'center',
    paddingHorizontal: 20,
    borderRadius: 8,
  },
});
