import { useQuery } from '@tanstack/react-query';
import packetsApi from 'api/packets';
import AppText from 'components/AppText';
import Layout from 'components/Layout';
import LoadingScreen from 'components/LoadingScreen';
import NoResult from 'components/NoResult';
import Pagination from 'components/Pagination';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  RefreshControl,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import Payment from './Payment';

const Wallet = () => {
  const { t } = useTranslation();
  const [refreshing, setRefreshing] = useState(false);
  const [page, setPage] = useState(0);
  const [pageAvia, setPageAvia] = useState(0);
  const [selectedType, setSelectedType] = useState<'AVIA' | 'AUTO'>('AVIA');
  const {
    data: packets,
    isFetching,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ['packets', page],
    queryFn: () =>
      packetsApi.getPackets({
        page,
        size: 10,
        cargoType: 'AUTO',
        direction: 'ASC',
        sort: 'id',
      }),
  });

  const {
    data: packetsAvia,
    isFetching: isFetchingAvia,
    isLoading: isLoadingAvia,
    isError: isErrorAvia,
    refetch: refetchAvia,
  } = useQuery({
    queryKey: ['packetsAvia', pageAvia],
    queryFn: () =>
      packetsApi.getPackets({
        page: pageAvia,
        size: 10,
        cargoType: 'AVIA',
        direction: 'ASC',
        sort: 'id',
      }),
  });

  useEffect(() => {
    const loadInitialData = async () => {
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
        refetch();
        refetchAvia();
      } catch (error) {
        console.error('Wallet loading error:', error);
        refetch();
        refetchAvia();
      }
    };

    loadInitialData();
  }, []);

  useEffect(() => {
    setPageAvia(0);
  }, [selectedType]);

  const onRefresh = useCallback(async () => {
    try {
      await refetch();
      await refetchAvia();
    } catch (error) {
      console.error('Refresh error:', error);
    } finally {
    }
  }, [refetch]);

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

  if (isLoading || isFetching || isLoadingAvia || isFetchingAvia) {
    return (
      <Layout>
        <LoadingScreen />
      </Layout>
    );
  }

  if (isError || isErrorAvia) {
    return (
      <Layout>
        <ScrollView
          refreshControl={refreshControl}
          style={{ flex: 1 }}
          contentContainerStyle={{ flexGrow: 1 }}
          removeClippedSubviews={true}
          keyboardShouldPersistTaps="handled"
        >
          <NoResult message="Xatolik yuz berdi" />
        </ScrollView>
      </Layout>
    );
  }

  if (selectedType === 'AUTO' && packets && !(packets?.data.length > 0)) {
    return (
      <Layout>
        <ScrollView
          refreshControl={refreshControl}
          style={{ flex: 1 }}
          contentContainerStyle={{ flexGrow: 1 }}
          removeClippedSubviews={true}
          keyboardShouldPersistTaps="handled"
        >
          <View style={styles.container}>
            <View style={styles.header}>
              <AppText style={styles.title}>{t("To'lov")}</AppText>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <TouchableOpacity
                  style={{
                    padding: 5,
                    backgroundColor: '#F3FAFF',
                    borderTopLeftRadius: 8,
                    borderBottomLeftRadius: 8,
                  }}
                  onPress={() => setSelectedType('AVIA')}
                >
                  <AppText
                    style={{
                      color: '#28A7E8',
                      fontSize: 14,
                    }}
                  >
                    AVIA
                  </AppText>
                </TouchableOpacity>
                <View style={{ width: 1 }} />
                <TouchableOpacity
                  style={{
                    padding: 5,
                    backgroundColor:
                      selectedType === 'AUTO' ? '#28A7E8' : '#F3FAFF',
                    borderTopRightRadius: 8,
                    borderBottomRightRadius: 8,
                  }}
                  onPress={() => setSelectedType('AUTO')}
                >
                  <AppText
                    style={{
                      color: selectedType === 'AUTO' ? '#fff' : '#28A7E8',
                      fontSize: 14,
                      fontWeight: '500',
                    }}
                  >
                    AUTO
                  </AppText>
                </TouchableOpacity>
              </View>
            </View>
            <NoResult />
          </View>
        </ScrollView>
      </Layout>
    );
  }
  if (
    selectedType === 'AVIA' &&
    packetsAvia &&
    !(packetsAvia?.data.length > 0)
  ) {
    return (
      <Layout>
        <ScrollView
          refreshControl={refreshControl}
          style={{ flex: 1 }}
          contentContainerStyle={{ flexGrow: 1 }}
          removeClippedSubviews={true}
          keyboardShouldPersistTaps="handled"
        >
          <View style={styles.container}>
            <View style={styles.header}>
              <AppText style={styles.title}>{t("To'lov")}</AppText>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <TouchableOpacity
                  style={{
                    padding: 5,
                    backgroundColor:
                      selectedType === 'AVIA' ? '#28A7E8' : '#F3FAFF',
                    borderTopLeftRadius: 8,
                    borderBottomLeftRadius: 8,
                  }}
                  onPress={() => setSelectedType('AVIA')}
                >
                  <AppText
                    style={{
                      color: selectedType === 'AVIA' ? '#fff' : '#28A7E8',
                      fontSize: 14,
                    }}
                  >
                    AVIA
                  </AppText>
                </TouchableOpacity>
                <View style={{ width: 1 }} />
                <TouchableOpacity
                  style={{
                    padding: 5,
                    backgroundColor: '#F3FAFF',
                    borderTopRightRadius: 8,
                    borderBottomRightRadius: 8,
                  }}
                  onPress={() => setSelectedType('AUTO')}
                >
                  <AppText
                    style={{
                      color: '#28A7E8',
                      fontSize: 14,
                      fontWeight: '500',
                    }}
                  >
                    AUTO
                  </AppText>
                </TouchableOpacity>
              </View>
            </View>
            <NoResult />
          </View>
        </ScrollView>
      </Layout>
    );
  }

  return (
    <Layout>
      <ScrollView
        refreshControl={refreshControl}
        style={{ flex: 1 }}
        contentContainerStyle={{ flexGrow: 1 }}
        removeClippedSubviews={true}
        keyboardShouldPersistTaps="handled"
      >
        <View style={{ flex: 1, justifyContent: 'space-between' }}>
          <View>
            <View style={styles.header}>
              <AppText style={styles.title}>{t("To'lov")}</AppText>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <TouchableOpacity
                  style={{
                    padding: 5,
                    backgroundColor:
                      selectedType === 'AVIA' ? '#28A7E8' : '#F3FAFF',
                    borderTopLeftRadius: 8,
                    borderBottomLeftRadius: 8,
                  }}
                  onPress={() => setSelectedType('AVIA')}
                >
                  <AppText
                    style={{
                      color: selectedType === 'AVIA' ? '#fff' : '#28A7E8',
                      fontSize: 14,
                    }}
                  >
                    AVIA
                  </AppText>
                </TouchableOpacity>
                <View style={{ width: 1 }} />
                <TouchableOpacity
                  style={{
                    padding: 5,
                    backgroundColor:
                      selectedType === 'AUTO' ? '#28A7E8' : '#F3FAFF',
                    borderTopRightRadius: 8,
                    borderBottomRightRadius: 8,
                  }}
                  onPress={() => setSelectedType('AUTO')}
                >
                  <AppText
                    style={{
                      color: selectedType === 'AUTO' ? '#fff' : '#28A7E8',
                      fontSize: 14,
                      fontWeight: '500',
                    }}
                  >
                    AUTO
                  </AppText>
                </TouchableOpacity>
              </View>
            </View>
            <Payment
              packets={selectedType === 'AUTO' ? packets! : packetsAvia!}
            />
          </View>

          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'flex-end',
              width: '95%',
              alignSelf: 'center',
              paddingRight: 20,
              paddingVertical: 10,
            }}
          >
            <Pagination
              page={selectedType === 'AUTO' ? page : pageAvia}
              totalPages={
                selectedType === 'AUTO'
                  ? packets?.totalPages ?? 1
                  : packetsAvia?.totalPages ?? 1
              }
              setPage={selectedType === 'AUTO' ? setPage : setPageAvia}
            />
          </View>
        </View>
      </ScrollView>
    </Layout>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    paddingHorizontal: 20,
    paddingTop: 5,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
  },
  cards: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingHorizontal: 20,
    paddingBottom: 10,
  },
  card: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 100,
    height: 100,
    backgroundColor: '#f0f0f0',
    borderRadius: 10,
    padding: 10,
  },
  cardText: {
    marginTop: 5,
    fontSize: 12,
    color: '#555',
    textAlign: 'center',
  },
});

export default Wallet;
