"use client";
import React, { use, useState } from "react";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
} from "@/components/ui/input-group";
import { Field } from "@/components/ui/field";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/redux/store";
import Link from "next/link";
import { useForm, SubmitHandler, FormProvider } from "react-hook-form";
import {
  AuthFormValues,
  checkCredentialsResponseType,
  checkCredentialsType,
  registrationType,
} from "@/type/authType";

import CustomForm from "@/components/common/CustomForm";
import { useRouter } from "next/navigation";
import CompleteRegistrationPage from "./components/CompleteComponent";
import StartWithEmailPage from "./components/StartWithEmailPage";
import { register } from "module";
import {
  checkCredentials,
  registrationUser,
} from "@/lib/services/auth.services";
import { RegistrationResponse } from "@/type/responseType";
import { Button } from "@base-ui/react";
import showCustomToast from "@/components/common/toaster/CustomToast";
import ExpertiseComponent from "./components/ExpertiseComponent";
import { useMutation, useQuery } from "@tanstack/react-query";
import { APIResponseType } from "@/type/comonType";
import { AxiosError } from "axios";
import { useApiToast } from "@/hooks/use-apiToast";

const RegistrationPage = () => {
  const dispatch = useDispatch();
  const { getToastData } = useApiToast();
  const [validationStep, setValidationStep] = useState<1 | 2 | null>(null);
  const {
    mutate,
    data: registerResponse,
    error,
    isPending,
    isSuccess,
  } = useMutation<
    APIResponseType<RegistrationResponse>,
    AxiosError<{ message: string }>,
    registrationType
  >({
    mutationFn: registrationUser,
    onSuccess: (data) => {
      if (typeof window !== "undefined") {
        localStorage.setItem("registrationPhone", data.data.user.phone);
        localStorage.setItem("registrationEmail", data.data.user.email);
      }

      showCustomToast({
        type: "success",
        message: data.message,
      });
      console.log("I AM HERE-----------");

      router.push(`/register/code?id=${data.data.user.uuid}`);
    },
    onError: (error) => {
      console.log(
        "Registration error----------------:",
        error.response?.data.message,
      );
      const { message, description } = getToastData(error);

      showCustomToast({
        type: "error",
        message: message ?? "Something went wrong",
        description,
      });
    },
  });
  const { mutate: checkCredentialsData } = useMutation<
    APIResponseType<checkCredentialsResponseType>,
    AxiosError<{ message: string }>,
    checkCredentialsType
  >({
    mutationFn: checkCredentials,
    onSuccess: (data) => {
      if (validationStep === 1) {
        if (data.data.exists) {
          console.log("----------------");

          showCustomToast({
            type: "error",
            message: "Email number already exists",
          });
          return;
        }
        setStep(2);
      } else if (validationStep === 2) {
        console.log("---------------->", data.data.exists);

        if (data.data.exists) {
          showCustomToast({
            type: "error",
            message: "Phone number already exists",
          });
          return;
        }
        setStep(3);
      }
    },
    onError: (error) => {
      console.log(
        "Registration error----------------:",
        error.response?.data.message,
      );
      const { message, description } = getToastData(error);

      showCustomToast({
        type: "error",
        message: message ?? "Something went wrong",
        description,
      });
    },
  });
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState<registrationType>({
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    password: "",
    password_confirmation: "",
    profession_id: "",
    gender: "",
    expertise_ids: [],
  });
  const methods = useForm<AuthFormValues>();
  const router = useRouter();

  const onSubmit: SubmitHandler<AuthFormValues> = async (data) => {
    if (step === 1) {
      setValidationStep(1);
      setFormData((pre) => ({
        ...pre,
        ...data,
      }));

      const payload: checkCredentialsType = {
        text_param: data.email,
        type: "email",
      };

      checkCredentialsData(payload);

      return;
    } else if (step === 2) {
      setValidationStep(2);
      setFormData((prev) => ({
        ...prev,
        ...data,
      }));

      const payload: checkCredentialsType = {
        text_param: data.phone,
        type: "phone",
      };

      checkCredentialsData(payload);
    } else if (step === 3) {
      setFormData((prev) => ({
        ...prev,
        ...data,
      }));

      const body: registrationType = {
        first_name: data.first_name,
        last_name: data.last_name,
        email: data.email,
        phone: data.phone,
        password: data.createPassword,
        password_confirmation: data.password_confirmation,
        profession_id: data.profession?.uuid || "",
        gender: data.gender?.label?.toLowerCase() || "",
        expertise_ids: data.expertise_ids || [],
      };

      try {
        console.log("============body===============", body);
        mutate(body);
      } catch (err) {
        showCustomToast({
          message: "Registration failed",
          description: "Try again",
          type: "error",
        });
      }
    }

    // router.push("/register/complete");
  };

  const steps = [
    StartWithEmailPage,
    CompleteRegistrationPage,
    ExpertiseComponent,
  ];

  const StepComponent = steps[step - 1];
  return (
    <div className="mx-6 flex min-h-screen flex-col items-center justify-center">
      {/* login text */}
      <div className="border-border mt-15 flex min-h-[90vh] w-full flex-col items-center justify-start gap-5 rounded-2xl border py-20">
        <FormProvider {...methods}>
          <StepComponent onSubmit={onSubmit} isLoading={isPending} />
        </FormProvider>
      </div>
    </div>
  );
};

export default RegistrationPage;
