import { PacketsData } from 'api/packets';
import React, { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  useWindowDimensions,
} 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 { width: screenWidth } = useWindowDimensions();
  const scale = useMemo(() => (screenWidth < 360 ? 0.85 : 1), [screenWidth]);
  const { t } = useTranslation();
  const styles = useMemo(
    () => makeStyles(scale, screenWidth),
    [scale, screenWidth],
  );

  const createIcons = useCallback(
    (scale: number, cargo: string) => [
      {
        status: 'COLLECTING',
        icon: <BoxIcon width={20 * scale} height={20 * scale} color="" />,
      },
      {
        status: 'ON_THE_WAY',
        icon:
          cargo === 'avia' ? (
            <Avia width={20 * scale} height={20 * scale} color="" />
          ) : (
            <Auto width={20 * scale} height={20 * scale} color="" view="-4" />
          ),
      },
      {
        status: 'IN_CUSTOMS',
        icon: <BagIcon width={20 * scale} height={20 * scale} color="" />,
      },
      {
        status: 'IN_WAREHOUSE',
        icon: <Store width={20 * scale} height={20 * scale} color="" />,
      },
      {
        status: 'DELIVERED',
        icon: <TrunkIcon width={20 * scale} height={20 * scale} color="" />,
      },
      {
        status: 'PAID',
        icon: <SuccessIcon width={20 * scale} height={20 * scale} color="" />,
      },
    ],
    [],
  );

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

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

      const icons = createIcons(scale, ItemLayout.deliveryStatus);

      return (
        <TouchableOpacity
          key={index}
          onPress={() => handleItemPress(ItemLayout)}
        >
          <View style={styles.card}>
            <View style={styles.statusCard}>
              {icons.map((item, i) => {
                const iconColor = i <= currentStatusIndex ? '#28A7E8' : '#000';
                const viewColor =
                  i <= currentStatusIndex ? '#28A7E81A' : '#0000001A';

                return (
                  <React.Fragment key={item.status}>
                    <View
                      style={[styles.circle, { backgroundColor: viewColor }]}
                    >
                      {React.cloneElement(item.icon, { color: iconColor })}
                    </View>
                    {i !== icons.length - 1 && (
                      <View
                        style={[
                          styles.divider,
                          { borderBottomColor: iconColor },
                        ]}
                      />
                    )}
                  </React.Fragment>
                );
              })}
            </View>
            <View
              style={[
                styles.statusLabelWrapper,
                {
                  backgroundColor: `${
                    statusColorMap[ItemLayout.deliveryStatus]
                  }1A`,
                },
              ]}
            >
              <Text
                style={[
                  styles.statusText,
                  { color: statusColorMap[ItemLayout.deliveryStatus] },
                ]}
              >
                {t(
                  tabList.find(item => item.value === ItemLayout.deliveryStatus)
                    ?.label || '',
                )}
              </Text>
            </View>
            <View style={styles.infoCard}>
              <Text style={styles.infoTitle}>{t('Reys raqami')}</Text>
              <Text
                style={[styles.infoText, { width: '50%', textAlign: 'right' }]}
              >
                {ItemLayout.packetName}
              </Text>
            </View>
            <View style={styles.infoCard}>
              <Text style={styles.infoTitle}>{t('Mahsulotlar og’irligi')}</Text>
              <Text style={styles.infoText}>{ItemLayout.weight}</Text>
            </View>
            <View style={styles.infoCard}>
              <Text style={styles.infoTitle}>{t('Umumiy narxi')}</Text>
              <Text style={styles.infoText}>{ItemLayout.totalPrice}</Text>
            </View>
          </View>
        </TouchableOpacity>
      );
    },
    [scale, createIcons, handleItemPress],
  );

  const orderItems = useMemo(() => {
    if (selectedData) {
      return [renderOrderItem(selectedData, 0)];
    }
    return data.data.map(renderOrderItem);
  }, [data, renderOrderItem, selectedData]);

  const countSection = useMemo(
    () => (
      <View style={styles.count}>
        <Text style={styles.title}>{t('Buyurtmalar soni')}</Text>
        {selectedData ? (
          <Text style={styles.title}>1</Text>
        ) : (
          <Text style={styles.title}>{data.data.length}</Text>
        )}
      </View>
    ),
    [styles.count, styles.title, data.data.length, selectedData],
  );

  return (
    <View style={styles.container}>
      {countSection}
      {orderItems}
    </View>
  );
};

const makeStyles = (scale: number, screenWidth: number) =>
  StyleSheet.create({
    container: {
      width: screenWidth * 0.95,
      marginTop: 10,
      alignSelf: 'center',
      borderRadius: 8 * scale,
      padding: 8 * scale,
      backgroundColor: '#F5F5F5',
    },
    count: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    title: {
      fontSize: 16 * scale,
      fontWeight: '500',
      color: '#333',
    },
    card: {
      backgroundColor: '#FFFFFF',
      marginTop: 12 * scale,
      padding: 15 * scale,
      borderRadius: 10 * scale,
      gap: 5 * scale,
      flexDirection: 'column',
    },
    statusCard: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      marginBottom: 10 * scale,
    },
    circle: {
      padding: 8 * scale,
      borderRadius: 50,
      alignItems: 'center',
      justifyContent: 'center',
    },
    divider: {
      width: 20 * scale,
      borderBottomWidth: 2 * scale,
      borderStyle: 'dashed',
    },
    statusLabelWrapper: {
      borderRadius: 8 * scale,
      alignSelf: 'flex-start',
      paddingVertical: 6 * scale,
      paddingHorizontal: 10 * scale,
      marginBottom: 12 * scale,
    },
    statusText: {
      fontWeight: '600',
      fontSize: 16 * scale,
    },
    infoCard: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginBottom: 6 * scale,
    },
    infoTitle: {
      fontSize: 16 * scale,
      color: '#979797',
      fontWeight: '500',
    },
    infoText: {
      fontSize: 14 * scale,
      color: '#28A7E8',
      fontWeight: '500',
    },
    modalOverlay: {
      flex: 1,
      backgroundColor: 'rgba(0,0,0,0.4)',
      justifyContent: 'center',
      alignItems: 'center',
      zIndex: 20,
    },
    modalContent: {
      width: '90%',
      maxHeight: '80%',
      backgroundColor: '#fff',
      borderRadius: 10,
      padding: 20,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.3,
      shadowRadius: 4,
      elevation: 5,
    },
    modalTitle: {
      fontSize: 20 * scale,
      fontWeight: '600',
      marginBottom: 10,
    },
    closeButton: {
      marginTop: 20,
      backgroundColor: '#28A7E8',
      paddingVertical: 10,
      borderRadius: 8,
      alignItems: 'center',
    },
  });

export default Order;
