"use client";
import { getPublicData } from "@/utils/fetch";
import { useParseError } from "@/utils/lib/helpers";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query";
import { Tabs, TabsRef } from "flowbite-react";
import { useRouter, useSearchParams } from "next/navigation";
import { FC, useEffect, useRef, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { BiArrowBack } from "react-icons/bi";
import { HiPhone } from "react-icons/hi";
import { MdCurrencyExchange } from "react-icons/md";
import { toast } from "react-toastify";
import ActionButton from "../action-button";
import Alerts from "../Alert";
import BkashPayment from "../bkash/bkash-payment";
import Captcha from "../common/captcha";
import { InputField } from "../forms/Inputs";
import {
  clientPaymentSchema,
  TSclientPaymentSchema,
} from "../forms/schema/client-payment";
import PaymentConfirm from "./payment-confirm";

type props = {
  host?: string;
  client?: TSclientPaymentSchema;
};

const Payment: FC<props> = ({ host, client: initClient }) => {
  const params = useSearchParams();
  const route = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);
  const [captcha, setCaptcha] = useState(null);
  const [captchaError, setCaptchaError] = useState(false);
  const [confirmPayment, setConfirmPayment] = useState(false);
  const [phone, setPhone] = useState("");
  const [status, setStatus] = useState<any>(undefined);
  const [client, setClient] = useState<TSclientPaymentSchema>(initClient);
  const clientForm = useForm<any>({
    resolver: zodResolver(clientPaymentSchema),
    mode: "onChange",
  });

  const {
    handleSubmit,
    reset,
    formState: { errors },
  } = clientForm;

  const getClient = async () => {
    const data = await getPublicData(
      `/api/v1/public/get-client?phone=${phone}&host=${host}`
    );
    if (!data?.success) {
      return toast.error(useParseError(data));
    }
    setClient(data?.data);
    return data?.data;
  };

  const {
    data: clientData,
    isLoading,
    isRefetching,
    refetch,
  } = useQuery({
    queryKey: ["invoice-client"],
    queryFn: () => getClient(),
    retry: 0,
    enabled: false,
  });

  const onSubmit = async (data: any) => {
    if (data.captcha !== captcha) {
      setCaptchaError(true);
    } else {
      setPhone(data.phone);
    }
  };

  const onError = async (data: any) => {
    console.log(data);
  };

  useEffect(() => {
    if (params.get("status")) {
      setStatus(params.get("status"));
      setConfirmPayment(true);
    }
  });

  useEffect(() => {
    if (phone) {
      refetch();
    }
  }, [phone]);

  useEffect(() => {
    if (client) {
      setConfirmPayment(true);
    }
  }, [client]);

  return (
    <div className="m-auto max-w-[400px]">
      {params?.get("payment") ? (
        <div className="mt-4">
          <Alerts message="Payment success" />
          <ActionButton
            className="mt-2"
            type="any"
            size="sm"
            title="Back"
            onClick={() => route.push("/pay")}
          >
            <BiArrowBack className="mr-2 mt-1" /> Back
          </ActionButton>
        </div>
      ) : (
        <div className="grid grid-cold-1 mt-6">
          {!confirmPayment && (
            <div className="w-[400px] m-auto px-5">
              <FormProvider {...clientForm}>
                <form onSubmit={handleSubmit(onSubmit, onError)}>
                  <div>
                    <InputField
                      labelText="Phone"
                      name="phone"
                      errors={errors}
                    />
                  </div>
                  <div>
                    <InputField
                      inputType="number"
                      labelText="Captcha"
                      name="captcha"
                    />
                    {captchaError && (
                      <span className="text-red-600">Invalid captcha</span>
                    )}
                  </div>
                  <div className="flex gap-1 font-bold text-2xl disabled:selection pt-2">
                    {<Captcha setCaptcha={setCaptcha} />}
                  </div>
                  <input className="opacity-0" type="submit" ref={inputRef} />
                </form>
              </FormProvider>
              <div className="flex justify-center">
                <div className="flex mr-2">
                  <ActionButton
                    type="submit"
                    size="lg"
                    onClick={() => inputRef?.current?.click()}
                    isLoading={isLoading || isRefetching}
                  />
                </div>
              </div>
            </div>
          )}
          {confirmPayment && (
            <>
              {!status && client && (
                <div>
                  <PaymentConfirm client={client as any} />
                </div>
              )}
              <div className="flex justify-center mx-6 border-t">
                <BkashPayment client={client} />
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default Payment;
