import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import AppText from 'components/AppText';
import LottieView from 'lottie-react-native';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Animated,
  StyleSheet,
  TouchableOpacity,
  useWindowDimensions,
  View,
} from 'react-native';
import Clock from 'screens/../../assets/lottie/Sand clock.json';
import ProgressBar from 'screens/../../assets/lottie/Success.json';
import Warning from 'screens/../../assets/lottie/Warning animation.json';
import CloseIcon from 'svg/Close';
import { RootStackParamList } from 'types/types';

type NavigationProp = NativeStackNavigationProp<
  RootStackParamList,
  'PaymentMethod'
>;

interface ModalSuccessViewProps {
  visible: boolean;
  setVisible: React.Dispatch<React.SetStateAction<boolean>>;
  setPayModal: React.Dispatch<React.SetStateAction<boolean>>;
}

const ModalSuccess = ({
  visible,
  setVisible,
  setPayModal,
}: ModalSuccessViewProps) => {
  const navigation = useNavigation<NavigationProp>();
  const [successMet, setSuccessMet] = useState(false);
  const [error, setError] = useState(false);
  const opacity = useRef(new Animated.Value(0)).current;
  const translateY = useRef(new Animated.Value(50)).current;
  const { t } = useTranslation();
  const { width } = useWindowDimensions();
  const scale = width < 360 ? 0.8 : 1;

  const closeModal = () => {
    Animated.timing(opacity, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true,
    }).start(() => {
      setVisible(false);
      setPayModal(false);
      navigation.navigate('Wallet');
    });
  };

  useEffect(() => {
    if (visible) {
      Animated.parallel([
        Animated.timing(opacity, {
          toValue: 1,
          duration: 250,
          useNativeDriver: true,
        }),
        Animated.spring(translateY, {
          toValue: 0,
          useNativeDriver: true,
        }),
      ]).start();

      const timer = setTimeout(() => setSuccessMet(true), 3000);
      return () => clearTimeout(timer);
    } else {
      setSuccessMet(false);
    }
  }, [visible]);

  if (!visible) return null;

  return (
    <View style={styles.overlay}>
      <Animated.View
        style={[
          styles.modalContent,
          {
            opacity: opacity,
            transform: [{ translateY }],
          },
        ]}
      >
        <View style={styles.header}>
          <AppText style={styles.title}>
            {successMet
              ? t('To’lov muvaffaqqiyatli o’tdi')
              : t('Chop etilmoqda')}
          </AppText>
          <TouchableOpacity
            onPress={closeModal}
            style={styles.closeBtn}
            disabled={!successMet}
          >
            <CloseIcon width={15} height={15} color={'#000000'} />
          </TouchableOpacity>
        </View>

        <View style={styles.divider} />

        <View style={styles.content}>
          {successMet ? (
            <View style={styles.content}>
              {error ? (
                <LottieView
                  source={Warning}
                  loop
                  autoPlay={true}
                  resizeMode="cover"
                  style={{ width: 100 * scale, height: 100 * scale }}
                />
              ) : (
                <LottieView
                  source={ProgressBar}
                  loop
                  autoPlay={true}
                  resizeMode="cover"
                  style={{ width: 100 * scale, height: 100 * scale }}
                />
              )}
            </View>
          ) : (
            <LottieView
              source={Clock}
              loop
              autoPlay={true}
              resizeMode="cover"
              style={{ width: 100 * scale, height: 100 * scale }}
            />
          )}
          <AppText style={styles.status}>
            {successMet
              ? t('Toʻlovingiz tasdiqlandi!')
              : t('Iltimos ozroq kutib turing!')}
          </AppText>
        </View>

        {successMet && (
          <>
            {error ? (
              <TouchableOpacity
                style={styles.btn}
                onPress={() => setPayModal(false)}
              >
                <AppText style={styles.btnText}>{t('Yaxshi')}</AppText>
              </TouchableOpacity>
            ) : (
              <TouchableOpacity style={styles.btn} onPress={closeModal}>
                <AppText style={styles.btnText}>{t('Yaxshi')}</AppText>
              </TouchableOpacity>
            )}
          </>
        )}
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.4)',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1000,
  },
  modalContent: {
    width: '90%',
    backgroundColor: '#fff',
    borderRadius: 10,
    paddingBottom: 20,
    shadowColor: '#000',
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 6,
  },
  header: {
    padding: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  title: {
    fontSize: 16,
    fontWeight: '500',
  },
  closeBtn: {
    padding: 5,
    width: 30,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#0000000D',
    borderRadius: 50,
  },
  divider: {
    height: 1,
    backgroundColor: '#E0E0E0',
    marginBottom: 10,
  },
  content: {
    alignItems: 'center',
    gap: 10,
    paddingVertical: 20,
  },
  circle: {
    backgroundColor: '#28A7E8',
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: 'center',
    alignItems: 'center',
  },
  status: {
    color: '#00000099',
    fontSize: 16,
    fontWeight: '500',
  },
  btn: {
    alignSelf: 'center',
    height: 50,
    width: '90%',
    borderRadius: 8,
    justifyContent: 'center',
    backgroundColor: '#28A7E8',
    marginTop: 10,
  },
  btnText: {
    textAlign: 'center',
    color: '#fff',
    fontSize: 18,
  },
});

export default ModalSuccess;
