import { RouteProp, useRoute } from '@react-navigation/native';
import NavbarBack from 'components/NavbarBack';
import Navigation from 'components/Navigation';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { PaymentStyle } from '../../payment/ui/style';
import ModalCard from './ModalCard';
import ModalPay from './ModalPay';
import ModalSuccess from './ModalSuccess';
import PaymentProduct from './PaymentProduct';

const PaymentMethod = () => {
  const route = useRoute<RouteProp<any, 'PaymentMethod'>>();
  const packets = route.params?.packets;

  const [isModalVisible, setModalVisible] = React.useState(false);
  const { t } = useTranslation();
  const [selectedId, setSelectedId] = React.useState<'card' | 'pay' | null>(
    null,
  );
  const [selectedCard, setSelectedCard] = React.useState<
    'click' | 'payme' | null
  >(null);
  const [cardModal, setCardModal] = React.useState(false);
  const [payModal, setPayModal] = React.useState(false);
  const [success, setSuccess] = React.useState(false);

  const toggleModal = () => setModalVisible(true);

  React.useEffect(() => {
    if (payModal) {
      const timeout = setTimeout(() => setSuccess(true), 1000);
      return () => clearTimeout(timeout);
    }
  }, [payModal]);

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 }}>
        <NavbarBack title={t("To'lov usuli")} />
        <PaymentProduct packet={packets!} />
        <ModalPay
          isModalVisible={isModalVisible}
          selectedId={selectedId}
          setModalVisible={setModalVisible}
          setSelectedId={setSelectedId}
          cardModal={cardModal}
          setCardModal={setCardModal}
          payModal={payModal}
          setPayModal={setPayModal}
          success={success}
          setSuccess={setSuccess}
        />
        {cardModal && (
          <ModalCard
            isVisible={cardModal}
            packId={packets.id}
            setIsVisible={setCardModal}
            selectedId={selectedCard}
            setSelectedId={setSelectedCard}
          />
        )}
        {success && (
          <ModalSuccess
            visible={success}
            setVisible={setSuccess}
            setPayModal={setPayModal}
          />
        )}
        <TouchableOpacity style={[PaymentStyle.button]} onPress={toggleModal}>
          <Text style={PaymentStyle.btnText}>{t("To'lash")}</Text>
        </TouchableOpacity>
        <Navigation />
      </View>
    </SafeAreaView>
  );
};

export default PaymentMethod;
