import AnimatedIcon from 'components/AnimatedIcon';
import React, { useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  FlatList,
  Modal,
  Pressable,
  StyleSheet,
  Text,
  useWindowDimensions,
  View,
} from 'react-native';
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,
  autoData,
}: {
  autoData: any;
  aviaData: any;
}) => {
  const { width: screenWidth } = useWindowDimensions();
  const scale = screenWidth < 360 ? 0.85 : 1;
  const cardWidth = screenWidth * 0.95;
  const styles = useMemo(() => HomeStyle(scale), [scale]);
  const { t } = useTranslation();

  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} />,
    },
  };

  const calendarList = useMemo(() => {
    const data: any[] = [];

    const prepareList = (calendar: any, type: 'auto' | 'avia') => {
      if (!calendar) return;
      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' },
      ];

      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,
          };
        }),
      });
    };

    prepareList(autoData, 'auto');
    prepareList(aviaData, 'avia');

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

  const flatListRef = useRef<FlatList>(null);
  const today = useMemo(() => {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    return d;
  }, []);

  // --- MODAL STATE ---
  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 && (
          <>
            <View style={styles.cardBody}>
              {Array.isArray(item.start) &&
                item.start.map((day: any, idx: number) => {
                  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
                      key={idx}
                      style={[
                        styles.date,
                        {
                          backgroundColor,
                          alignItems: 'center',
                          justifyContent: 'center',
                          height: 70,
                        },
                      ]}
                    >
                      <Text style={[styles.dateLabel, { color: textColor }]}>
                        {day.date.slice(-2)}
                      </Text>
                      <Text style={[styles.dateLabel, { color: textColor }]}>
                        {t(day.weekday)}
                      </Text>
                    </View>
                  );
                })}
            </View>
            <View style={styles.divider} />
            <View style={styles.autoCard}>
              <View style={styles.row}>
                <View style={styles.rowFull}>
                  <Text style={styles.reysTitle}>
                    {item.cargo.toUpperCase()}
                  </Text>
                  <View style={styles.animatedIconWrapper}>
                    <AnimatedIcon type={item.cargo} />
                  </View>
                </View>
              </View>
            </View>
          </>
        )}
      </Pressable>
    );
  };

  return (
    <>
      <FlatList
        ref={flatListRef}
        data={calendarList}
        keyExtractor={(_, index) => index.toString()}
        renderItem={renderItem}
        horizontal
        snapToInterval={cardWidth + 10}
        decelerationRate="fast"
        contentContainerStyle={{
          paddingHorizontal: (screenWidth - cardWidth) / 2,
        }}
        pagingEnabled
        style={{ marginBottom: 20 }}
        showsHorizontalScrollIndicator={false}
        getItemLayout={(_, index) => ({
          length: cardWidth,
          offset: cardWidth * index,
          index,
        })}
      />

      {/* MODAL */}
      <Modal
        transparent
        visible={modalVisible}
        animationType="fade"
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={modalStyles.modalOverlay}>
          <View style={modalStyles.modalContent}>
            <Text style={modalStyles.modalTitle}>
              {t('Yetkazish tafsilotlari')}
            </Text>
            {selectedItem && (
              <>
                {selectedItem.start.map((day: any, idx: number) => (
                  <Text key={idx} style={{ textAlign: 'left', width: '100%' }}>
                    {day.date} - {t(day.weekday)} - {t(day.status)}
                  </Text>
                ))}
              </>
            )}
            <Pressable
              onPress={() => setModalVisible(false)}
              style={modalStyles.closeButton}
            >
              <Text style={{ color: '#fff' }}>{t('Yopish')}</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
    </>
  );
};

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,
    fontWeight: '600',
    marginBottom: 12,
  },
  closeButton: {
    marginTop: 20,
    backgroundColor: '#28A7E8',
    paddingVertical: 8,
    paddingHorizontal: 20,
    borderRadius: 8,
  },
});
