import { useQuery } from '@tanstack/react-query';
import packetsApi from 'api/packets';
import LoadingScreen from 'components/LoadingScreen';
import Navbar from 'components/Navbar';
import Navigation from 'components/Navigation';
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,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
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();
  }, []);

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

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

  if (isLoading || isFetching || isLoadingAvia || isFetchingAvia) {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <Navbar />
          <LoadingScreen />
          <Navigation />
        </View>
      </SafeAreaView>
    );
  }

  if (isError || isErrorAvia) {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <Navbar />
          <NoResult message="Xatolik yuz berdi" />
          <Navigation />
        </View>
      </SafeAreaView>
    );
  }

  if (
    (packets && !(packets?.data.length > 0)) ||
    (packetsAvia && !(packetsAvia?.data.length > 0))
  ) {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <Navbar />
        <View style={styles.container}>
          <View style={styles.header}>
            <Text style={styles.title}>{t("To'lov")}</Text>
          </View>
          <NoResult />
        </View>
        <Navigation />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <Navbar />
        <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}>
                <Text style={styles.title}>{t("To'lov")}</Text>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <TouchableOpacity
                    style={{
                      padding: 5,
                      backgroundColor:
                        selectedType === 'AVIA' ? '#28A7E8' : '#F3FAFF',
                      borderTopLeftRadius: 8,
                      borderBottomLeftRadius: 8,
                    }}
                    onPress={() => setSelectedType('AVIA')}
                  >
                    <Text
                      style={{
                        color: selectedType === 'AVIA' ? '#fff' : '#28A7E8',
                        fontSize: 14,
                      }}
                    >
                      AVIA
                    </Text>
                  </TouchableOpacity>
                  <View style={{ width: 1 }} />
                  <TouchableOpacity
                    style={{
                      padding: 5,
                      backgroundColor:
                        selectedType === 'AUTO' ? '#28A7E8' : '#F3FAFF',
                      borderTopRightRadius: 8,
                      borderBottomRightRadius: 8,
                    }}
                    onPress={() => setSelectedType('AUTO')}
                  >
                    <Text
                      style={{
                        color: selectedType === 'AUTO' ? '#fff' : '#28A7E8',
                        fontSize: 14,
                        fontWeight: '500',
                      }}
                    >
                      AUTO
                    </Text>
                  </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>

        <Navigation />
      </View>
    </SafeAreaView>
  );
};

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;
