import { useQuery } from '@tanstack/react-query';
import { authApi } from 'api/auth';
import AppText from 'components/AppText';
import SingleFileDrop from 'components/FileDrop';
import LayoutTwo from 'components/LayoutTwo';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Image,
  Linking,
  RefreshControl,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import AppLink from 'react-native-app-link';
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 }),
    [],
  );
  const openTelegram = React.useCallback(async () => {
    try {
      await AppLink.maybeOpenURL('tg://resolve?domain=cpost_admin', {
        appName: 'Telegram',
        appStoreId: 686449807,
        appStoreLocale: 'us',
        playStoreId: 'org.telegram.messenger',
      });
    } catch (err) {
      Linking.openURL('https://t.me/cpost_admin');
    }
  }, []);
  return (
    <LayoutTwo title={t('Xitoy omborlari manzili')}>
      <ScrollView
        keyboardShouldPersistTaps="handled"
        refreshControl={refreshControl}
        contentContainerStyle={contentContainerStyle}
      >
        <View style={styles.card}>
          <AppText style={[styles.title]}>
            {t('Bizning Xitoy manzilimiz')}
          </AppText>
          <AppText style={[styles.text]}>
            {t(
              'Taobao, pinduoduo, 1688 ,alibaba va Xitoyning istalgan platformasiga kiritish uchun',
            )}
          </AppText>
          <TabsAviaWarehouses />
          <TabsAutoWarehouses />
          <AppText style={[styles.title]}>
            {t('Xitoy omborlarimiz manzilini programmaga kiriting')}
          </AppText>
          <View style={{ gap: 20 }}>
            <AppText style={[styles.text]}>
              {t(
                "Diqqat! Iltimos, Xitoy omborimiz manzilini Xitoy programmalariga kiritganingizdan so'ng, kiritilgan holatdagi skrenshotni bizga yuborib, tekshirtiring",
              )}
            </AppText>
            <AppText style={[styles.text]}>
              {t(
                "Xitoy ombori manzilini to'g'ri kiritish, mahsulotingiz yo'qolib qolish oldini oladi.",
              )}
            </AppText>
            <AppText style={[styles.text]}>
              {t(
                "Agar sizda savol tug'ilsa yoki biron narsaga tushunmasangiz bizga murojaat qiling",
              )}
            </AppText>
          </View>
          <AppText style={[styles.title]}>
            {t('Skrenshot rasmini yuklang')}
          </AppText>
          <Image
            source={Shablon}
            style={{ width: '100%', height: 400, objectFit: 'cover' }}
          />
          <View
            style={{
              backgroundColor: '#ffff',
              padding: 8,
              borderRadius: 8,
              shadowColor: '#000',
              shadowOffset: { width: 0, height: 2 },
              shadowOpacity: 0.15,
              shadowRadius: 3,
              elevation: 3,
            }}
          >
            <AppText style={[{ fontSize: 16, fontWeight: 500 }]}>
              {t(
                "Hurmatli mijoz, ushbu berilgan ID manzil, ma'lumotlarni siz shu namunadagidek 1- va 4- qatorlarga oʻz ID kodingizni yozing! Aks holda sizning kargoingiz bilan muammo chiqishi mumkin.",
              )}
            </AppText>
          </View>
          <View
            style={{
              backgroundColor: '#fff',
              padding: 8,
              marginTop: 6,
              borderRadius: 8,
              shadowColor: '#000',
              shadowOffset: { width: 0, height: 2 },
              shadowOpacity: 0.15,
              shadowRadius: 3,
              elevation: 3,
            }}
          >
            <AppText style={[{ fontSize: 16, fontWeight: '500' }]}>
              {t(
                'Ilovaga kirib huddi shunday to’ldirganingizdan keyin ekranni rasmga(skrinshot) olib, sizga bot tomonidan berilgan ID kod vamanzilni ushbu',
              )}{' '}
              <AppText style={{ color: '#28A7E8' }} onPress={openTelegram}>
                @cpost_admin
              </AppText>{' '}
              {t('admindan tasdiqlatib olishingiz kerak bo’ladi.')}
            </AppText>
          </View>
          <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" />
            ) : (
              <AppText style={[styles.btnText]}>
                {t('Manzilni tekshirish')}
              </AppText>
            )}
          </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',
  },
});
