import { useQuery } from '@tanstack/react-query';
import { authApi } from 'api/auth';
import SingleFileDrop from 'components/FileDrop';
import LayoutTwo from 'components/LayoutTwo';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Image,
  RefreshControl,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Toast from 'react-native-toast-message';
import Shablon from 'screens/../../assets/bootsplash/shablon.jpg';
import TabsAutoWarehouses from './TabsAutoWarehouses';
import TabsAviaWarehouses from './TabsAviaWarehouses';

interface FileData {
  uri: string;
  name: string;
  type: string;
  base64: string;
}

interface WarehousesProps {}
const botToken = '7768577881:AAGXGtOl2IiMImrsY6BZmksN9Rjeq2InlTo';

const Warehouses = (props: WarehousesProps) => {
  const [refreshing, setRefreshing] = React.useState(false);
  const { t } = useTranslation();
  const [isLoading, setIsLoading] = React.useState(false);
  const [backImage, setBackImage] = React.useState<FileData | null>(null);
  const { data: getMe } = useQuery({
    queryKey: ['getMe'],
    queryFn: authApi.getMe,
  });

  const openTelegramWithImage = async () => {
    const telegramApiUrl = `https://api.telegram.org/bot${botToken}/sendPhoto`;

    const formData = new FormData();
    formData.append('chat_id', '-1002950892822');
    formData.append('photo', {
      uri: backImage?.uri,
      type: 'image/jpeg',
      name: 'photo.jpg',
    });
    formData.append(
      'caption',
      `Foydalanuvchi ismi: ${getMe?.fullName} 
Telefon nomer: +${getMe?.phone} 
Cargo Idsi: ${getMe?.aviaCargoId}
      `,
    );
    try {
      setIsLoading(true);
      await fetch(telegramApiUrl, {
        method: 'POST',
        body: formData,
      });
      Toast.show({
        type: 'success',
        text1: t("So'rovingiz jo'natilidi. Tez orada siz bilan bog'lanamiz"),
        position: 'top',
        visibilityTime: 2000,
      });
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: t('Xatolik yuz berdi'),
        position: 'top',
        visibilityTime: 2000,
      });
    } finally {
      setIsLoading(false); // 👈 loading tugadi
    }
  };

  const onRefresh = React.useCallback(() => {
    setRefreshing(true);
    setTimeout(() => {
      setRefreshing(false);
    }, 1500);
  }, []);

  const refreshControl = React.useMemo(
    () => <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />,
    [refreshing, onRefresh],
  );

  const contentContainerStyle = React.useMemo(
    () => ({ paddingBottom: 10 }),
    [],
  );
  return (
    <LayoutTwo title={t('Xitoy omborlari manzili')}>
      <ScrollView
        keyboardShouldPersistTaps="handled"
        refreshControl={refreshControl}
        contentContainerStyle={contentContainerStyle}
      >
        <View style={styles.card}>
          <Text style={styles.title}>{t('Bizning Xitoy manzilimiz')}</Text>
          <Text style={styles.text}>
            {t(
              'Taobao, pinduoduo, 1688 ,alibaba va Xitoyning istalgan platformasiga kiritish uchun',
            )}
          </Text>
          <TabsAviaWarehouses />
          <TabsAutoWarehouses />
          <Text style={styles.title}>
            {t('Xitoy omborlarimiz manzilini programmaga kiriting')}
          </Text>
          <View style={{ gap: 20 }}>
            <Text style={styles.text}>
              {t(
                "Diqqat! Iltimos, Xitoy omborimiz manzilini Xitoy programmalariga kiritganingizdan so'ng, kiritilgan holatdagi skrenshotni bizga yuborib, tekshirtiring",
              )}
            </Text>
            <Text style={styles.text}>
              {t(
                "Xitoy ombori manzilini to'g'ri kiritish, mahsulotingiz yo'qolib qolish oldini oladi.",
              )}
            </Text>
            <Text style={styles.text}>
              {t(
                "Agar sizda savol tug'ilsa yoki biron narsaga tushunmasangiz bizga murojaat qiling",
              )}
            </Text>
          </View>
          <Text style={styles.title}>{t('Skrenshot rasmini yuklang')}</Text>
          <Image
            source={Shablon}
            style={{ width: '100%', height: 500, objectFit: 'cover' }}
          />
          <SingleFileDrop
            title={t('Rasmni shu yerga yuklang')}
            onFileSelected={setBackImage}
            type="image/*"
          />
          <TouchableOpacity
            style={[styles.button, isLoading && { opacity: 0.7 }]}
            onPress={openTelegramWithImage}
            disabled={isLoading}
          >
            {isLoading ? (
              <ActivityIndicator size="small" color="#fff" />
            ) : (
              <Text style={styles.btnText}>{t('Manzilni tekshirish')}</Text>
            )}
          </TouchableOpacity>
        </View>
      </ScrollView>
    </LayoutTwo>
  );
};

export default Warehouses;

const styles = StyleSheet.create({
  container: { flex: 1 },
  card: {
    width: '95%',
    marginTop: 20,
    margin: 'auto',
    gap: 10,
  },
  title: {
    fontSize: 20,
    fontWeight: '500',
  },
  text: {
    fontSize: 18,
    color: '#000000B2',
    fontWeight: '400',
  },
  button: {
    backgroundColor: '#28A7E8',
    height: 56,
    borderRadius: 8,
    textAlign: 'center',
    display: 'flex',
    justifyContent: 'center',
  },
  btnText: {
    color: '#fff',
    fontSize: 20,
    textAlign: 'center',
  },
});
