"use client";

import uploadInvoice from "@/app/api-requests/uploadInvoice";
import { useCartStore } from "@/app/store/cartStore";
import {
  currentUserInfoInPaymentStore,
  userInfoStore,
} from "@/app/store/userInfoStore";
import LangLink from "@/components/ui/localization/LangLink";
import TranslateClient from "@/components/ui/localization/TranslateClient";
import MainButton from "@/components/ui/MainButton";
import Modal from "@/components/ui/Modal";
import { toast } from "@/components/ui/use-toast";
import useCurrentLanguage from "@/hooks/useCurrentLanguage";
import { images } from "@/lib/images";
import { postData } from "@/lib/requests";
import { Address_TP } from "@/modules/payment/address_TP";
import { useMutation } from "@tanstack/react-query";
import { Loader } from "lucide-react";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { useState } from "react";
import PinCode from "../login-signup/forget password/PinCode";
import PinCodeMessage from "../login-signup/forget password/PinCodeMessage";
import ForgetPassword from "../login-signup/forget password/ForgetPassword";
import ForgetPasswordInPayment from "./ForgetPasswordInPayment";

type Props = {
  className?: string;
  selectedAddress: Address_TP | null;
  selectedPayment: any;
  imageSrc: string[];
  files: File[];
  notes: string;
};

const PaymentBtns = ({
  className,
  selectedAddress,
  selectedPayment,
  imageSrc,
  files,
  notes,
}: Props) => {
  const pathname = usePathname();
  const inPayment = pathname.endsWith("payment");
  const { cart } = useCartStore();
  const { locale } = useCurrentLanguage();
  const { is_verify, phone, username, title, email } = userInfoStore();
  const { paymentUsername, paymentTitle, paymentEmail, paymentPhone } =
    currentUserInfoInPaymentStore();
  const [forgetFormState, setForgetState] =
    useState<ForgetPassFormState>("virifyPhone");
  const [token, setToken] = useState("");
  const [open, setOpen] = useState(false);
  const { isLoading, mutate } = uploadInvoice();

  // forgetpassword > otp > invoice

  const {
    data,
    mutate: mutateUpdateProfile,
    isPending,
    error,
    status,
  } = useMutation({
    mutationKey: ["update-profile"],
    mutationFn: (values: any) => {
      return postData({
        endpoint: `api/Profile`,
        values,
        formData: true,
      });
    },
    onSuccess: (data) => {
      if (!!!data.errors) {
        // setForgetState("virifyPhone")
        if (data?.data?.is_verify) {
          // TODO: m => sent data to invoice (payment)
          mutate({
            files: files.flat(Infinity),
            addressId: selectedAddress?.id,
            paymentMethodId: selectedPayment?.id,
            notes: notes,
            username: paymentUsername,
            title: paymentTitle,
            email: paymentEmail,
            phone: paymentPhone,
          });
        } else {
          setOpen(true);
        }
        toast({
          title: locale?.["profile_information_update_successfully"],
          className: "bg-green-700 text-white rounded-xl",
        });

        // setIsSuccessModalOpen(true)
        // setResetFields(true)
        // ---------------
        // if (type === "create") {
        //     form.reset()
        // }
        // queryClient.refetchQueries({ queryKey: ["about"] })
      }
    },
    onError: (error) => {
      toast({
        variant: "destructive",
        title: locale?.["oops_something_went_wrong"],
        className: "bg-red-700 text-white rounded-xl",
      });
    },
  });

  return (
    <div className={`${className ? className : ""}`}>
      <MainButton
        size={"sm"}
        intent={"primary"}
        disabled={isLoading || status === "pending"}
        onClick={() => {
          if (!selectedAddress || !selectedPayment) {
            toast({
              title: locale?.["warning"],
              description: locale?.["please_select_address_and_payment_method"],
              className: "bg-red-700 text-white rounded-xl",
            });
          } else {
            if (files?.length || imageSrc?.length) {
              if (
                is_verify &&
                paymentPhone === phone &&
                paymentUsername === username &&
                paymentTitle === title &&
                paymentEmail === email
              ) {
                mutate({
                  files: files.flat(Infinity),
                  addressId: selectedAddress?.id,
                  paymentMethodId: selectedPayment?.id,
                  notes: notes,
                  username: paymentUsername,
                  title: paymentTitle,
                  email: paymentEmail,
                  phone: paymentPhone,
                });
              } else {
                // if change any value in form of user info form

                // TODO: check if input values is verify then  call mutateUpdateProfile is true and show toast if false
                mutateUpdateProfile({
                  username: paymentUsername,
                  title: paymentTitle,
                  email: paymentEmail,
                  phone: paymentPhone,
                });
              }
            } else {
              toast({
                title: locale?.["warning"],
                description: locale?.["please_upload_invoice_image"],
                className: "bg-red-700 text-white rounded-xl",
              });
            }
          }
        }}
        fullWidth
        className={`my-5 flex items-center gap-x-2 ${!cart.length && "hidden"}`}
      >
        {isLoading || status === "pending" ? (
          <Loader className="w-4 h-4 animate-spin" />
        ) : (
          <Image src={images?.bag2} alt="bag" width={20} hidden={inPayment} />
        )}
        <TranslateClient text={inPayment ? "continue_pay" : "buy"} />
      </MainButton>

      <Modal open={open} setOpen={setOpen}>
        {
          <ForgetPasswordInPayment
            setOpen={setOpen}
            files={files}
            selectedAddress={selectedAddress}
            selectedPayment={selectedPayment}
            notes={notes}
          />
        }
        {/* {forgetFormState === "pinCode" && <PinCode setForgetState={setForgetState} phone={phone} setToken={setToken} />} */}
      </Modal>

      {/* checkout button */}
      <LangLink href="products">
        <MainButton size={"sm"} intent={"secondary"} fullWidth>
          <TranslateClient text="continue_shopping" />
        </MainButton>
      </LangLink>
    </div>
  );
};

export default PaymentBtns;
