import { PacketsData } from 'api/packets';
import AppText from 'components/AppText';
import React, { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, StyleSheet, TouchableOpacity, View } from 'react-native';
import Auto from 'svg/Auto';
import Avia from 'svg/Avia';
import BagIcon from 'svg/BagIcon';
import BoxIcon from 'svg/Box';
import Store from 'svg/Store';
import SuccessIcon from 'svg/SuccessIcon';
import TrunkIcon from 'svg/TrunkIcon';
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: 'Toshkent omboriga 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(), []);

  const createIcons = useCallback(
    (cargo: string) => [
      {
        status: 'COLLECTING',
        icon: <BoxIcon width={24} height={24} color="" />,
      },
      {
        status: 'ON_THE_WAY',
        icon:
          cargo === 'avia' ? (
            <Avia width={24} height={24} color="" />
          ) : (
            <Auto width={24} height={24} color="" view="-4" />
          ),
      },
      {
        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: 'PAID',
        icon: <SuccessIcon width={24} height={24} color="" />,
      },
    ],
    [],
  );

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

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

      return (
        <TouchableOpacity key={index} 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 }) => {
                const iconColor = i <= currentStatusIndex ? '#28A7E8' : '#000';
                const viewColor =
                  i <= currentStatusIndex ? '#28A7E81A' : '#0000001A';

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

            {/* Status Label */}
            <View
              style={[
                styles.statusLabelWrapper,
                {
                  backgroundColor: `${statusColorMap[item.deliveryStatus]}1A`,
                },
              ]}
            >
              <AppText
                style={[
                  styles.statusText,
                  { color: statusColorMap[item.deliveryStatus] },
                ]}
              >
                {t(
                  tabList.find(tab => tab.value === item.deliveryStatus)
                    ?.label || '',
                )}
              </AppText>
            </View>

            {/* Info */}
            <View style={styles.infoCard}>
              <AppText style={styles.infoTitle}>{t('Reys raqami')}</AppText>
              <AppText
                style={[styles.infoText, { width: '50%', textAlign: 'right' }]}
              >
                {item.packetName}
              </AppText>
            </View>
            <View style={styles.infoCard}>
              <AppText style={styles.infoTitle}>
                {t('Mahsulotlar og’irligi')}
              </AppText>
              <AppText style={styles.infoText}>{item.weight}</AppText>
            </View>
            <View style={styles.infoCard}>
              <AppText style={styles.infoTitle}>{t('Umumiy narxi')}</AppText>
              <AppText style={styles.infoText}>{item.totalPrice}</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',
      alignItems: 'center',
      marginTop: 10,
    },
    title: {
      fontSize: 16,
      fontWeight: '500',
      color: '#333',
    },
    card: {
      backgroundColor: '#fff',
      margin: 1,
      marginTop: 8,
      padding: 15,
      borderRadius: 10,
      // iOS
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.2,
      shadowRadius: 2,
      // Android
      elevation: 2,
    },
    statusCard: {
      marginBottom: 10,
    },
    circle: {
      padding: 8,
      borderRadius: 50,
      alignItems: 'center',
      justifyContent: 'center',
    },
    divider: {
      width: 20,
      borderBottomWidth: 2,
      borderStyle: 'dashed',
    },
    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,
    },
    iconWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      flex: 1,
      marginBottom: 10,
    },
    infoTitle: {
      fontSize: 16,
      color: '#979797',
      fontWeight: '500',
    },
    infoText: {
      fontSize: 14,
      color: '#28A7E8',
      fontWeight: '500',
    },
  });

export default Order;
