import { useMutation, useQuery } from '@tanstack/react-query';
import { authApi } from 'api/auth';
import packetsApi from 'api/packets';
import AppText from 'components/AppText';
import React, { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Animated,
  Dimensions,
  StyleSheet,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Check from 'svg/Check';
import CreditCard from 'svg/CreditCard';
import Usd from 'svg/Dollar';
import { PaymentStyle } from '../../payment/ui/style';

const SCREEN_HEIGHT = Dimensions.get('window').height;

interface ModalPayProps {
  isModalVisible: boolean;
  setModalVisible: React.Dispatch<React.SetStateAction<boolean>>;
  selectedId: 'card' | 'pay' | null;
  setSelectedId: React.Dispatch<React.SetStateAction<'card' | 'pay' | null>>;
  cardModal: boolean;
  setCardModal: React.Dispatch<React.SetStateAction<boolean>>;
  payModal: boolean;
  paymentStatus: string;
  packId: number;
  paymentType: string | null;
  setPayModal: React.Dispatch<React.SetStateAction<boolean>>;
  success: boolean;
  setSuccess: React.Dispatch<React.SetStateAction<boolean>>;
}

const ModalPay = ({
  isModalVisible,
  setModalVisible,
  selectedId,
  paymentType,
  setSelectedId,
  packId,
  setCardModal,
  setPayModal,
  paymentStatus,
}: ModalPayProps) => {
  const translateY = useRef(new Animated.Value(SCREEN_HEIGHT)).current;
  const opacity = useRef(new Animated.Value(0)).current;
  const { bottom } = useSafeAreaInsets();
  const [load, setLoad] = React.useState(false);
  const { t } = useTranslation();
  const { data: getMe } = useQuery({
    queryKey: ['getMe'],
    queryFn: authApi.getMe,
  });

  const { mutate, isPending } = useMutation({
    mutationFn: ({ id, payType }: { id: number; payType: string }) =>
      packetsApi.payPackets(id, { payType }),
    onSuccess: res => {
      console.log(res, 'url');
      setPayModal(true);
    },
    onError: err => {
      console.dir(err);
    },
  });

  useEffect(() => {
    if (isModalVisible) {
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: 0,
          duration: 300,
          useNativeDriver: true,
        }),
        Animated.timing(opacity, {
          toValue: 1,
          duration: 300,
          useNativeDriver: true,
        }),
      ]).start();
    } else {
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: SCREEN_HEIGHT,
          duration: 300,
          useNativeDriver: true,
        }),
        Animated.timing(opacity, {
          toValue: 0,
          duration: 200,
          useNativeDriver: true,
        }),
      ]).start();
    }
  }, [isModalVisible]);

  const handleBackdropPress = () => {
    setModalVisible(false);
    setSelectedId(null);
  };

  const handlePayment = () => {
    setLoad(true);

    setTimeout(() => {
      if (selectedId === 'pay') {
        mutate({ id: packId, payType: 'CASH' });
      }
      if (selectedId === 'card') setCardModal(true);

      setModalVisible(false);
      setSelectedId(null);
      setLoad(false);
    }, 200);
  };

  if (!isModalVisible) return null;

  return (
    <TouchableWithoutFeedback onPress={handleBackdropPress}>
      <Animated.View
        style={[
          styles.overlay,
          {
            opacity: opacity,
            bottom,
          },
        ]}
      >
        <TouchableWithoutFeedback>
          <Animated.View
            style={[
              styles.modalContent,
              {
                transform: [{ translateY: translateY }],
              },
            ]}
          >
            {getMe && !getMe.aviaCargoId.includes('CP') && (
              <TouchableOpacity
                style={[
                  styles.option,
                  {
                    backgroundColor:
                      selectedId === 'card' ? '#28A7E81A' : '#fff',
                  },
                ]}
                onPress={() => setSelectedId('card')}
              >
                <View style={PaymentStyle.paymentCard}>
                  <CreditCard
                    color={selectedId == 'card' ? '#28A7E8' : '#000000'}
                    width={28}
                    height={28}
                  />
                  <AppText
                    style={[
                      PaymentStyle.titleMethod,
                      { color: selectedId == 'card' ? '#28A7E8' : '#000' },
                    ]}
                  >
                    {t('Bank kartasi')}
                  </AppText>
                </View>
                <View
                  style={[
                    PaymentStyle.select,
                    {
                      backgroundColor:
                        selectedId === 'card' ? '#28A7E8' : '#FFFFFF',
                      borderColor:
                        selectedId === 'card' ? '#28A7E8' : '#383838',
                    },
                  ]}
                >
                  {selectedId === 'card' && (
                    <Check color="#fff" width={20} height={20} />
                  )}
                </View>
              </TouchableOpacity>
            )}
            {paymentType !== 'CASH' && (
              <TouchableOpacity
                style={[
                  styles.option,
                  {
                    backgroundColor:
                      selectedId === 'pay' ? '#28A7E81A' : '#fff',
                  },
                ]}
                onPress={() => {
                  setSelectedId('pay');
                }}
              >
                <View style={PaymentStyle.paymentCard}>
                  <Usd
                    color={selectedId == 'pay' ? '#28A7E8' : '#000000'}
                    width={28}
                    height={28}
                    colorCircle={selectedId == 'pay' ? '#28A7E8' : '#000000'}
                  />
                  <AppText
                    style={[
                      PaymentStyle.titleMethod,
                      { color: selectedId == 'pay' ? '#28A7E8' : '#000' },
                    ]}
                  >
                    {t('Naqt pul')}
                  </AppText>
                </View>
                <View
                  style={[
                    PaymentStyle.select,
                    {
                      backgroundColor:
                        selectedId === 'pay' ? '#28A7E8' : '#FFFFFF',
                      borderColor: selectedId === 'pay' ? '#28A7E8' : '#383838',
                    },
                  ]}
                >
                  {selectedId === 'pay' && (
                    <Check color="#fff" width={20} height={20} />
                  )}
                </View>
              </TouchableOpacity>
            )}
            <TouchableOpacity
              style={[
                PaymentStyle.modalBtn,
                {
                  backgroundColor:
                    load || selectedId === null ? '#88888840' : '#28A7E8',
                },
              ]}
              onPress={handlePayment}
              disabled={load || selectedId === null}
            >
              {load ? (
                <ActivityIndicator size="small" color="#fff" />
              ) : (
                <AppText
                  style={[
                    PaymentStyle.btnText,
                    {
                      color:
                        load || selectedId === null ? '#000000b9' : '#FFFF',
                    },
                  ]}
                >
                  {t("To'lash")}
                </AppText>
              )}
            </TouchableOpacity>
          </Animated.View>
        </TouchableWithoutFeedback>
      </Animated.View>
    </TouchableWithoutFeedback>
  );
};

export default ModalPay;

const styles = StyleSheet.create({
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    backgroundColor: 'rgba(0,0,0,0.4)',
    justifyContent: 'flex-end',
    zIndex: 30,
  },
  modalContent: {
    backgroundColor: '#F3FAFF',
    padding: 20,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    minHeight: 'auto',
    gap: 10,
  },
  option: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderRadius: 10,
    gap: 10,
    alignItems: 'center',
    padding: 20,
  },
});
