import { ConfirmBillingDetailsForm } from "@/components/billing/billing-details-form";
import { useUserBillingProfile } from "@/components/billing/hooks";
import { PaymentMethodsSelect } from "@/components/billing/payment-methods-select";
import {
  type PaymentCheckoutPreparingState,
  PaymentCheckoutStep,
} from "@/components/billing/store";
import { updateUserBillingDetails } from "@/lib/api/billing";

export function Preparing({ state }: { state: PaymentCheckoutPreparingState }) {
  const { data: profile, refetch: refreshProfile } = useUserBillingProfile();

  if (!profile) {
    return null;
  }

  switch (state.step) {
    case PaymentCheckoutStep.completingBillingAddress:
      return (
        <ConfirmBillingDetailsForm
          defaultValues={profile.billing_details}
          onSubmit={async (address, isDirty) => {
            if (isDirty || profile.billing_details == null) {
              await updateUserBillingDetails(address);
              await refreshProfile();
            }
            state.setBillingDetails(address);
            state.selectPaymentMethod();
          }}
        />
      );
    case PaymentCheckoutStep.selectingPaymentMethod:
      if (!state.billingDetails) {
        return null;
      }
      return (
        <PaymentMethodsSelect
          billingDetails={state.billingDetails}
          methods={profile.stripe_payment_methods}
          value={state.paymentMethod?.stripe_pm_id}
          onCreated={(paymentMethodId) =>
            refreshProfile().then((res) => {
              const found = res.data?.stripe_payment_methods.find(
                (method) => method.stripe_pm_id === paymentMethodId
              );
              if (found) {
                state.setPaymentMethod(found);
              }
            })
          }
          onValueChange={(paymentMethodId) => {
            const found = profile.stripe_payment_methods.find(
              (method) => method.stripe_pm_id === paymentMethodId
            );
            if (found) {
              state.setPaymentMethod(found);
            }
          }}
          onConfirm={() => {
            state.createOrder();
          }}
        />
      );
  }
}
