'use client';

import { useState } from 'react';
import { useCompleteLoyaltyPaymentMutation } from '@akinon/next/data/client/checkout';
import { useAppSelector } from '@akinon/next/redux/hooks';
import { useForm } from 'react-hook-form';
import { checkPaymentWillRedirect } from '@akinon/next/utils';

export default function LoyaltyPayment() {
  const { payment_option } = useAppSelector((state) => state.checkout.preOrder);
  const { handleSubmit } = useForm();
  const [completeLoyaltyPayment, { isLoading: isCompletingPayment }] =
    useCompleteLoyaltyPaymentMutation();
  const [isProcessing, setIsProcessing] = useState(false);

  const isButtonDisabled = isCompletingPayment || isProcessing;

  const onSubmit = async () => {
    if (isButtonDisabled) return;

    setIsProcessing(true);

    try {
      const response = await completeLoyaltyPayment().unwrap();

      if (response?.errors || !checkPaymentWillRedirect(response)) {
        setIsProcessing(false);
      }
    } catch (error) {
      console.error('Error completing loyalty payment:', error);
      setIsProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} id={payment_option.slug}></form>
  );
}
