import { PacketsData } from 'api/packets';
import AppText from 'components/AppText';
import { formatPrice } from 'helpers/formatPrice';
import React, { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, StyleSheet, TouchableOpacity, View } from 'react-native';
import Avia from 'svg/Avia';
import BagIcon from 'svg/BagIcon';
import BoxIcon from 'svg/Box';
import Store from 'svg/Store';
import TrunkIcon from 'svg/TrunkIcon';
import Wallet from 'svg/Wallet';
import { DataInfo } from '../lib/data';

const statusColorMap: Record<string, string> = {
  COLLECTING: '#FF69B4',
  ON_THE_WAY: '#1E90FF',
  IN_CUSTOMS: '#8A2BE2',
  IN_WAREHOUSE: '#00BFFF',
  ARRIVED: '#FFA500',
  DELIVERED: '#32CD32',
};

const statuses = [
  'COLLECTING',
  'ON_THE_WAY',
  'IN_CUSTOMS',
  'IN_WAREHOUSE',
  'ARRIVED',
  'DELIVERED',
  'PAID',
] as const;

type FilterType = (typeof statuses)[number];

const tabList: { label: string; value: FilterType }[] = [
  { label: "Yig'ilmoqda", value: 'COLLECTING' },
  { label: "Yo'lda", value: 'ON_THE_WAY' },
  { label: 'Bojxonada', value: 'IN_CUSTOMS' },
  { label: 'Omborga yetib keldi', value: 'IN_WAREHOUSE' },
  { label: 'Topshirish punktida', value: 'DELIVERED' },
  { label: 'Qabul qilingan', value: 'PAID' },
];

interface Props {
  data: PacketsData;
  selectedData: DataInfo | null;
  openModal: (item: DataInfo) => void;
}

const Order = ({ data, openModal, selectedData }: Props) => {
  const { t } = useTranslation();
  const styles = useMemo(() => makeStyles(), []);

  /** 🔥 SUCCESS ICON faqat paymentStatus ga qarab o‘zgaradi */
  const createIcons = useCallback((cargo: string, paymentStatus?: string) => {
    const isPaid = paymentStatus === 'PAYED';

    return [
      {
        status: 'COLLECTING',
        icon: <BoxIcon width={24} height={24} color="" />,
      },
      {
        status: 'ON_THE_WAY',
        icon: <Avia width={24} height={24} color="" />,
      },
      {
        status: 'IN_CUSTOMS',
        icon: <BagIcon width={24} height={24} color="" />,
      },
      {
        status: 'IN_WAREHOUSE',
        icon: <Store width={24} height={24} color="" />,
      },
      {
        status: 'DELIVERED',
        icon: <TrunkIcon width={24} height={24} color="" />,
      },
      {
        status: 'PENDING',
        icon: (
          <Wallet
            width={24}
            height={24}
            color={isPaid ? '#28A7E8' : '#C0C0C0'}
          />
        ),
      },
    ];
  }, []);

  const handleItemPress = useCallback(
    (item: DataInfo) => openModal(item),
    [openModal],
  );

  const renderOrderItem = useCallback(
    ({ item }: { item: DataInfo }) => {
      const currentStatusIndex = statuses.indexOf(
        item.deliveryStatus as FilterType,
      );

      const icons = createIcons(item.deliveryStatus, item.paymentStatus);

      return (
        <TouchableOpacity onPress={() => handleItemPress(item)}>
          <View style={styles.card}>
            <FlatList
              data={icons}
              keyExtractor={(iconItem, i) => iconItem.status + i}
              numColumns={6}
              contentContainerStyle={styles.statusCard}
              renderItem={({ item: iconItem, index: i }) => {
                let iconColor = '#000';
                let bgColor = '#0000001A';

                if (
                  iconItem.status === 'DELIVERED' &&
                  item.deliveryStatus === 'DELIVERED'
                ) {
                  iconColor = '#28A7E8';
                  bgColor = '#28A7E81A';
                } else if (iconItem.status === 'PENDING') {
                  if (item.paymentStatus === 'PAYED') {
                    iconColor = '#28A7E8'; // blue
                    bgColor = '#28A7E81A';
                  } else if (item.paymentStatus === 'PENDING') {
                    iconColor = '#FFA500'; // orange
                    bgColor = '#FFA5001A';
                  } else {
                    iconColor = '#C0C0C0'; // gray
                    bgColor = '#C0C0C01A';
                  }
                } else if (i <= currentStatusIndex) {
                  iconColor = '#28A7E8'; // blue
                  bgColor = '#28A7E81A';
                }

                return (
                  <View style={styles.iconWrapper}>
                    <View
                      style={[
                        styles.circle,
                        {
                          backgroundColor: bgColor,
                          justifyContent: 'center',
                          alignItems: 'center',
                        },
                      ]}
                    >
                      {React.cloneElement(iconItem.icon, { color: iconColor })}
                    </View>
                    {i !== icons.length - 1 && (
                      <View
                        style={[
                          styles.divider,
                          { borderBottomColor: iconColor },
                        ]}
                      />
                    )}
                  </View>
                );
              }}
            />

            <View
              style={[
                {
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                  width: '100%',
                },
              ]}
            >
              <AppText
                style={[
                  styles.statusText,
                  styles.statusLabelWrapper,
                  {
                    color: statusColorMap[item.deliveryStatus],
                    backgroundColor: `${statusColorMap[item.deliveryStatus]}1A`,
                  },
                ]}
              >
                {t(
                  tabList.find(el => el.value === item.deliveryStatus)?.label ||
                    '',
                )}
              </AppText>
              <AppText
                style={[
                  styles.statusText,
                  styles.statusLabelWrapper,
                  {
                    color:
                      item.paymentStatus === 'NEW'
                        ? '#D32F2F'
                        : item.paymentStatus === 'PENDING'
                        ? '#FFA500'
                        : item.paymentStatus === 'PAYED'
                        ? '#32CD32'
                        : '#D32F2F',
                    backgroundColor:
                      item.paymentStatus === 'NEW'
                        ? '#D32F2F1A'
                        : item.paymentStatus === 'PENDING'
                        ? '#FFA5001A'
                        : item.paymentStatus === 'PAYED'
                        ? '#32CD321A'
                        : '#D32F2F',
                  },
                ]}
              >
                {item.paymentStatus === 'NEW'
                  ? t("To'lanmagan")
                  : item.paymentStatus === 'PENDING'
                  ? t("To'lov kutilmoqda")
                  : item.paymentStatus === 'PAYED' && t("To'langan")}
              </AppText>
            </View>

            <View style={styles.infoCard}>
              <AppText style={styles.infoTitle}>{t('Reys raqami')}</AppText>
              <AppText
                style={[styles.infoText, { width: '50%', textAlign: 'right' }]}
              >
                {item.packetName}
              </AppText>
            </View>

            {item.items.map(e => (
              <View
                key={e.trekId}
                style={{
                  ...styles.infoCard,
                  flexDirection: 'column',
                  gap: 4,
                  marginTop: 4,
                }}
              >
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    gap: 4,
                  }}
                >
                  <AppText style={styles.infoTitle}>
                    {t('Mahsulot nomi')}
                  </AppText>
                  <AppText style={styles.infoText}>{e.name}</AppText>
                </View>
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    gap: 4,
                  }}
                >
                  <AppText style={styles.infoTitle}>{t('Trek ID')}</AppText>
                  <AppText style={styles.infoText}>{e.trekId}</AppText>
                </View>
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    gap: 4,
                  }}
                >
                  <AppText style={styles.infoTitle}>{t('Og’irligi')}</AppText>
                  <AppText style={styles.infoText}>{e.weight} kg</AppText>
                </View>
              </View>
            ))}

            <View style={styles.infoCard}>
              <AppText style={styles.infoTitle}>
                {t('Mahsulotlar og’irligi')}
              </AppText>
              <AppText style={styles.infoText}>{item.weight} kg</AppText>
            </View>
            {(item.deliveryStatus === 'DELIVERED' ||
              item.paymentStatus === 'PAID') && (
              <View style={styles.infoCard}>
                <AppText style={styles.infoTitle}>{t('Umumiy narxi')}</AppText>
                <AppText style={styles.infoText}>
                  {formatPrice(item.totalPrice)} {t('so‘m')}
                </AppText>
              </View>
            )}
          </View>
        </TouchableOpacity>
      );
    },
    [createIcons, handleItemPress],
  );

  const ordersData = useMemo(
    () => (selectedData ? [selectedData] : data.data),
    [data, selectedData],
  );

  return (
    <View style={styles.container}>
      <View style={styles.count}>
        <AppText style={styles.title}>{t('Buyurtmalar soni')}</AppText>
        <AppText style={styles.title}>
          {selectedData ? '1' : data.data.length}
        </AppText>
      </View>

      <FlatList
        data={ordersData}
        scrollEnabled={false}
        renderItem={renderOrderItem}
        keyExtractor={(item, index) => item.id?.toString() || index.toString()}
      />
    </View>
  );
};

const makeStyles = () =>
  StyleSheet.create({
    container: { width: '95%', margin: 'auto', borderRadius: 10 },
    count: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginTop: 10,
    },
    title: { fontSize: 16, fontWeight: '500', color: '#333' },
    card: {
      backgroundColor: '#fff',
      marginTop: 8,
      padding: 15,
      borderRadius: 10,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.2,
      shadowRadius: 2,
      elevation: 2,
    },
    statusCard: { marginBottom: 10 },
    circle: {
      padding: 8,
      borderRadius: 50,
      alignItems: 'center',
      justifyContent: 'center',
    },
    divider: { width: 20, borderBottomWidth: 2, borderStyle: 'dashed' },
    iconWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      flex: 1,
      marginBottom: 10,
    },
    statusLabelWrapper: {
      borderRadius: 8,
      alignSelf: 'flex-start',
      paddingVertical: 6,
      paddingHorizontal: 10,
      marginBottom: 12,
    },
    statusText: { fontFamily: 'GolosText-Bold', fontSize: 16 },
    infoCard: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginBottom: 6,
    },
    infoTitle: { fontSize: 16, color: '#979797', fontWeight: '500' },
    infoText: { fontSize: 14, color: '#28A7E8', fontWeight: '500' },
  });

export default Order;
