import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useQuery } from '@tanstack/react-query';
import { authApi } from 'api/auth';
import passportApi from 'api/passport';
import AppText from 'components/AppText';
import Layout from 'components/Layout';
import LoadingScreen from 'components/LoadingScreen';
import Navbar from 'components/Navbar';
import Navigation from 'components/Navigation';
import NoResult from 'components/NoResult';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  RefreshControl,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import PassportIcon from 'svg/Passport';
import Plus from 'svg/Plus';
import MyPassport from './MyPassport';

const Passport = () => {
  const { t } = useTranslation();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const [refreshing, setRefreshing] = useState(false);

  const {
    data: myPassport,
    isLoading: passportLoad,
    isFetching: passFetching,
    refetch: passRef,
    isError: isErrorPass,
  } = useQuery({
    queryKey: ['myPassport'],
    queryFn: passportApi.getPassport,
  });

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

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await passRef();
  }, [passRef]);

  useEffect(() => {
    if (!passportLoad && refreshing) {
      setRefreshing(false);
    }
  }, [passportLoad, refreshing]);

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

  const handleNavigateToCreatePassword = useCallback(() => {
    navigation.navigate('create-password');
  }, [navigation]);

  if (passportLoad || getMeLoad || passFetching) {
    return (
      <View style={styles.container}>
        <Navbar />
        <LoadingScreen message="Pasport sahifasi yuklanmoqda..." />
        <Navigation />
      </View>
    );
  }

  if (isErrorPass) {
    return (
      <View style={styles.container}>
        <Navbar />
        <NoResult message="Xatolik yuz berdi" />
        <Navigation />
      </View>
    );
  }

  return (
    <Layout>
      <ScrollView
        refreshControl={refreshControl}
        removeClippedSubviews={true}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.header}>
          <AppText style={styles.title}>{t('Passportlarim')}</AppText>
        </View>
        {myPassport && myPassport.length === 0 ? (
          <View style={styles.content}>
            <View style={styles.emptyState}>
              <PassportIcon color="#ccc" width={80} height={80} />
              <AppText style={styles.emptyText}>
                {t("Hali pasport qo'shilmagan")}
              </AppText>
              <AppText style={styles.emptySubtext}>
                {t("Yangi pasport qo'shish uchun tugmani bosing")}
              </AppText>
            </View>
          </View>
        ) : (
          <MyPassport getMe={getMe!} myPassport={myPassport!} />
        )}
      </ScrollView>
      <TouchableOpacity
        style={styles.addButton}
        onPress={handleNavigateToCreatePassword}
        activeOpacity={0.7}
      >
        <Plus color="#fff" width={24} height={24} />
        <AppText style={styles.addButtonText}>
          {t("Yangi pasport qo'shish")}
        </AppText>
      </TouchableOpacity>
    </Layout>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    paddingHorizontal: 10,
    paddingTop: 5,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
  },
  content: {
    paddingHorizontal: 20,
    paddingBottom: 20,
  },
  emptyState: {
    alignItems: 'center',
    marginTop: 50,
    marginBottom: 30,
  },
  emptyText: {
    fontSize: 18,
    color: '#666',
    marginTop: 15,
    textAlign: 'center',
  },
  emptySubtext: {
    fontSize: 14,
    color: '#999',
    marginTop: 5,
    textAlign: 'center',
  },
  addButton: {
    backgroundColor: '#28A7E8',
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderRadius: 10,
    marginBottom: 10,
    width: '95%',
    margin: 'auto',
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 10,
  },
  addButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default Passport;
