import DynamicFormFields from "@/components/ui/DynamicFormFields";
import { getQueryClient } from "@/configs/query-client";
import { useTranslations } from "@/providers/TranslationProviders";
import {
  AmazonPayParams,
  BrainTreeConfigTypes,
  DepositFormType,
  PaymentMethodType,
  StripeConfigTypes,
} from "@/types/payment";
import { useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useGetQuery } from "./mutate/useGetQuery";
import { useQueryMutation } from "./mutate/useQueryMutation";
import { showToast } from "@/utils/toast";
type PropsType = {
  depositForm: DepositFormType | null;
  setShowCheckoutModal: React.Dispatch<React.SetStateAction<boolean>>;
  setPaymentConfig: React.Dispatch<
    React.SetStateAction<{
      stripe: StripeConfigTypes | null;
      braintree: BrainTreeConfigTypes | null;
      amazon: AmazonPayParams | null;
    }>
  >;
};

export interface ManualGatewayFormTypes {
  fields: {
    value: string | number | boolean | null;
    type: string;
    label: string;
  }[];
}
export const usePaymentHandler = ({
  depositForm,
  setShowCheckoutModal,
  setPaymentConfig,
}: PropsType) => {
  const [showRedirectUrlModal, setShowRedirectUrlModal] = useState(false);
  const [redirectUrl, setRedirectUrl] = useState<string | null>(null);
  const [manualGatewayForm, setManualGatewayForm] =
    useState<ManualGatewayFormTypes>({
      fields: [],
    });

  const { control, handleSubmit } = useForm<ManualGatewayFormTypes>();

  const { tran } = useTranslations();

  const [validationError, setValidationError] = useState<Record<
    string,
    string
  > | null>(null);

  const { data: paymentGateways, isLoading } = useGetQuery<PaymentMethodType[]>(
    {
      isPublic: false,
      url: `/client/payments/methods`,
    },
  );

  const checkFrontendValidation = () => {
    if (!depositForm?.slug) {
      setValidationError((prev) => ({
        ...prev,
        gateway: tran("Payment method is required!"),
      }));
      return false;
    }

    if (!depositForm?.amount) {
      setValidationError((prev) => ({
        ...prev,
        amount: tran("Amount is required!"),
      }));
      return false;
    }

    if (!depositForm?.currency) {
      setValidationError((prev) => ({
        ...prev,
        currency: tran("Currency is required!"),
      }));
      return false;
    }

    if (depositForm?.type === "manual" && manualGatewayForm.fields.length) {
      let isAllFieldsFilled = true;
      manualGatewayForm.fields.forEach((field, index) => {
        if (!field.value) {
          setValidationError((prev) => ({
            ...prev,
            [`fields.${index}.value`]: tran("Field is required!"),
          }));
          isAllFieldsFilled = false;
        }
      });

      if (!isAllFieldsFilled) {
        return false;
      }
    }

    return true;
  };

  const {
    mutate: depositMutate,
    isLoading: isDepositsLoading,
    backendErrors,
  } = useQueryMutation({
    isPublic: false,
    url: `/client/deposits`,
  });

  const onSubmit = (nonce?: string) =>
    handleSubmit((data) => {
      setValidationError(null);
      if (!checkFrontendValidation()) {
        return;
      }

      depositMutate(
        {
          amount: depositForm?.amount,
          currency: depositForm?.currency,
          gateway: depositForm?.slug,
          payment_method_id: depositForm?.id,
        },
        {
          onSuccess: (response) => {
            const data = response?.data;
            if (!data) {
              // toast.error(tran("Something went wrong. Please try again."));
              return;
            }

            // Handle checkout modal for matching gateway
            if (depositForm?.slug === data.gateway) {
              setShowCheckoutModal(true);
              setPaymentConfig((prev) => ({
                ...prev,
                [data.gateway]: data,
              }));
              return; // stop here to avoid triggering other redirects
            }

            // Redirect if payment URL exists
            if (data.payment_url) {
              setRedirectUrl(data.payment_url);
              setShowRedirectUrlModal(true);
              return;
            }

            // Handle manual payment type
            if (depositForm?.type === "manual") {
              // toast.success(tran(data.message));

              showToast({
                type: "success",
                text: "Deposit request submitted successfully",
              });
              // router.push("/BuyCoins");
            }
            getQueryClient().invalidateQueries({ queryKey: ["deposits"] });
          },
          onError: (error: any) => {
            console.log(error);
          },
        },
      );
    })();

  const forms = useMemo(() => {
    if (depositForm?.type !== "manual") {
      return [];
    }

    const metaData = depositForm?.meta?.sort(
      (a: any, b: any) => a?.order - b?.order,
    );

    return (
      metaData?.map((form: any) => {
        return {
          ...form,
          field: (
            <Controller
              key={form.id}
              control={control}
              name={`fields.${form.id}`}
              rules={{ required: form.required }}
              render={({ field: { onChange, value } }) => (
                <DynamicFormFields
                  id={form.id}
                  label={form.label}
                  type={form.field_type}
                  required={form.required}
                  options={form.options}
                  value={value}
                  onChange={onChange}
                  validationError={backendErrors?.fields?.[form.id]}
                />
              )}
            />
          ),
        };
      }) || []
    );
  }, [depositForm?.meta, depositForm?.type, control, backendErrors]);

  return {
    paymentGateways,
    tran,
    onSubmit,
    setManualGatewayForm,
    validationError: validationError || backendErrors,
    forms,
    isLoading,
    isDepositsLoading,
    redirectUrl,
    showRedirectUrlModal,
    setShowRedirectUrlModal,
  };
};
