import Clipboard from '@react-native-clipboard/clipboard';
import { useQuery } from '@tanstack/react-query';
import { authApi } from 'api/auth';
import warhouses_api from 'api/warhouses';
import AppText from 'components/AppText';
import React from 'react';
import { useTranslation } from 'react-i18next';
import {
  FlatList,
  StyleSheet,
  TouchableOpacity,
  useWindowDimensions,
  View,
} from 'react-native';
import Toast from 'react-native-toast-message';
import Copy from 'svg/Copy';
import Kitay from 'svg/Ki';

const TabsAutoWarehouses = () => {
  const { width: screenWidth } = useWindowDimensions();
  const scale = screenWidth < 360 ? 0.85 : 1;
  const cardWidth = screenWidth * 0.95;
  const { t } = useTranslation();
  const styles = makeStyles(scale, cardWidth, screenWidth);

  const { data: getMe } = useQuery({
    queryKey: ['getMe'],
    queryFn: authApi.getMe,
  });

  const addressInfo = [
    {
      id: 1,
      title: 'China (Auto)',
      postCode: '510440',
      addressInfo: [
        `收件人∶吴彦祖AT(${getMe?.autoCargoId})`,
        '地址∶广州市白云区龙归街道南村攀龙六巷30号AТ(N209)',
        ' 电话: 18023847617',
        `1004 ${getMe?.aviaCargoId}`,
      ],
    },
    // {
    //   id: 2,
    //   title: 'Korea (Auto)',
    //   postCode: '520550',
    //   addressInfo: [
    //     '收件人∶李小龙AT(M312)',
    //     '地址∶深圳市南山区科技园科发路',
    //     '18号AT(M312)',
    //     '电话: 13800008888',
    //   ],
    // },
  ];

  const handleCopy = (info: string[]) => {
    if (getMe?.status === 'ACTIVE') {
      Clipboard.setString(info.join('\n'));
      Toast.show({
        type: 'success',
        text1: t('Nusxa olingan'),
        text2: t('Avto manzili nusxalandi!'),
        position: 'top',
        visibilityTime: 2000,
      });
    } else {
      Toast.show({
        type: 'error',
        text1: t('Xatolik yuz berdi!'),
        text2: t('Akkaunt faol emas!'),
        position: 'top',
        visibilityTime: 2000,
      });
    }
  };

  const { data } = useQuery({
    queryKey: ['warhouses'],
    queryFn: () => warhouses_api.getWarhouses({ cargoType: 'AUTO' }),
  });

  const formattedData =
    data?.map((item: string | null) => {
      if (!item) return '';

      const withAutoCargo = item.replace('%s', getMe?.autoCargoId || '');

      const withAviaCargo = withAutoCargo.replace(
        '%s',
        getMe?.aviaCargoId || '',
      );

      return withAviaCargo;
    }) || [];

  return (
    <FlatList
      data={formattedData}
      horizontal
      keyExtractor={(_, index) => index.toString()}
      pagingEnabled
      showsHorizontalScrollIndicator={false}
      snapToInterval={cardWidth + 10}
      decelerationRate="fast"
      renderItem={({ item, index }) => {
        const isLast = index === formattedData.length - 1;
        return (
          <View style={[styles.card, { marginRight: isLast ? 0 : 10 }]}>
            <View style={styles.titleCard}>
              <Kitay width={24 * scale} height={24 * scale} />
              <AppText style={styles.title}>China (Auto)</AppText>
            </View>
            <View style={styles.infoId}>
              <View style={{ gap: 4 * scale, width: '90%' }}>
                <AppText style={styles.infoText}>{item}</AppText>
              </View>
              <TouchableOpacity onPress={() => handleCopy(item.addressInfo)}>
                <Copy color="#28A7E8" width={24 * scale} height={24 * scale} />
              </TouchableOpacity>
            </View>
          </View>
        );
      }}
    />
  );
};

const makeStyles = (scale: number, cardWidth: number, screenWidth: number) =>
  StyleSheet.create({
    card: {
      width: cardWidth,
      backgroundColor: '#28a8e82c',
      borderRadius: 12 * scale,
      padding: 15 * scale,
      gap: 10 * scale,
    },
    titleCard: {
      flexDirection: 'row',
      gap: 8 * scale,
      alignItems: 'center',
    },
    title: {
      fontSize: 20 * scale,
      fontFamily: 'GolosText-Bold',
      color: '#101623CC',
    },
    infoId: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginVertical: 8 * scale,
    },
    infoText: {
      fontSize: 16 * scale,
      color: '#28A7E8',
    },
    postCodeWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
    },
    postCodeText: {
      fontSize: 16 * scale,
      color: '#000000',
      fontWeight: '500',
    },
    postCode: {
      fontSize: 16 * scale,
      color: '#28A7E8',
      fontWeight: '400',
      marginLeft: 4 * scale,
    },
  });

export default TabsAutoWarehouses;
