"use client";

import React, { useCallback, useEffect, useState } from "react";
import { Formik, Form, useFormikContext } from "formik";
import * as Yup from "yup";
import InputField from "@/components/ui/InputField";
import CheckboxField from "@/components/ui/CheckboxField";
import { useMutation } from "@tanstack/react-query";
import apiClient from "@/lib/apiClient";
import { useRouter } from "next/navigation";
import axios, { AxiosError } from "axios";
import PhoneInput from "@/components/ui/PhoneInputField";
import Link from "next/link";

interface ApiErrorResponse {
  success: boolean;
  message: string;
  error: string;
}

const ClearApiErrorOnInputChange: React.FC<{ clearError: () => void }> = ({
  clearError,
}) => {
  const { values } = useFormikContext<{ email: string; phone: string }>();

  useEffect(() => {
    clearError(); // Clear API error when user types
  }, [values.email, values.phone, clearError]);

  return null; // This component doesn't render anything
};

const getValidationSchema = (activeTab: "mobile" | "email") =>
  Yup.object().shape({
    email:
      activeTab === "email"
        ? Yup.string()
            .required("Enter your email ID")
            .email("Enter a valid email ID")
        : Yup.string(),
    phone:
      activeTab === "mobile"
        ? Yup.string()
            .required("Enter your mobile number")
            .matches(/^[0-9]{10}$/, "Must be a 10-digit mobile number")
        : Yup.string(),
    countryCode:
      activeTab === "mobile"
        ? Yup.string().required("Country code is required")
        : Yup.string(),
    rememberMe: Yup.boolean(),
  });

const LoginForm: React.FC = () => {
  const router = useRouter();
  const [errorMessage, setErrorMessage] = useState<React.ReactNode | null>(
    null
  );
  const [activeTab, setActiveTab] = useState<"mobile" | "email">("mobile");
  const [isOtpSent, setIsOtpSent] = useState(false);

  const clearError = useCallback(() => {
    setErrorMessage(null);
  }, []);

  const mutation = useMutation({
    mutationFn: async (values: {
      email: string;
      phone: string;
      countryCode: string;
      rememberMe: boolean;
    }) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      const phoneRegex = /^[0-9]{10}$/;

      if (activeTab === "email" && emailRegex.test(values.email)) {
        return apiClient.post("/auth/send-email-otp", { email: values.email });
      }

      if (activeTab === "mobile" && phoneRegex.test(values.phone)) {
        return apiClient.post("/auth/send-otp", {
          phone: values.phone,
          countryCode: values.countryCode,
        });
      }

      return Promise.reject("Invalid input format");
    },
  });

  return (
    <section className="py-md-5 py-4 contact-section login-form-section">
      <div className="container webContent login-form-container mb-3 py-md-5">
        <div className="row justify-content-center mb-3">
          <div className="col-xxl-4 col-xl-5 col-lg-6 col-md-7 col-sm-8 col-12">
            <div className="card form-container-area mx-md-0 mx-2 shadow-sm">
              <div className="form-container p-4">
                <div className="text-center text-white mb-3">
                  <h3 className="subHeading check-text text-center mb-2">
                    Login
                  </h3>
                  <p className="form-text-p px-0 px-md-3">
                    Code will be sent to your registered mobile number or email
                    ID
                  </p>
                </div>

                <Formik
                  enableReinitialize
                  initialValues={{
                    email: "",
                    phone: "",
                    countryCode: "",
                    rememberMe: false,
                  }}
                  validationSchema={getValidationSchema(activeTab)}
                  validateOnChange={true}
                  validateOnBlur={true}
                  onSubmit={(values, { setSubmitting }) => {
                    clearError();
                    mutation.mutate(values, {
                      onSuccess: () => {
                        setErrorMessage(null);
                        setIsOtpSent(true);
                        setSubmitting(false);

                        const identifier =
                          activeTab === "email" ? values.email : values.phone;
                        router.push(
                          `/login-verify?userId=${encodeURIComponent(
                            identifier
                          )}${
                            activeTab === "mobile"
                              ? `&countryCode=${encodeURIComponent(
                                  values.countryCode
                                )}`
                              : ""
                          }`
                        );
                      },
                      onError: (error: unknown) => {
                        if (axios.isAxiosError(error)) {
                          const axiosError =
                            error as AxiosError<ApiErrorResponse>;
                          const apiErrorMessage =
                            axiosError.response?.data?.message;
                          if (
                            apiErrorMessage
                              ?.toLowerCase()
                              .includes("no account found")
                          ) {
                            setErrorMessage(
                              <div className="text-center">
                                <div className="text-danger">
                                  No account found for this email/number.
                                </div>
                                <div className="text-white mt-1">
                                  Would you like to{" "}
                                  <Link
                                    href="/contact"
                                    className="fw-bold text-white"
                                  >
                                    Get in touch?
                                  </Link>
                                </div>
                              </div>
                            );
                          } else {
                            setErrorMessage(
                              apiErrorMessage ||
                                "Failed to request OTP. Please try again."
                            );
                          }
                        } else {
                          setErrorMessage(
                            "An unknown error occurred. Please try again."
                          );
                        }
                        setIsOtpSent(false);
                        setSubmitting(false);
                      },
                    });
                  }}
                >
                  {({ isSubmitting, isValid, setErrors, setTouched, setFieldValue }) => {
                    const isButtonDisabled = isSubmitting || !isValid || isOtpSent;
                    return (
                      (<Form className="form-validation my-2 mb-0">
                        <fieldset disabled={isSubmitting || isOtpSent}>
                          <ClearApiErrorOnInputChange clearError={clearError} />
                          <div className="col-12 mb-3">
                            <nav>
                              <div
                                className="nav nav-tabs mb-3 border-0 d-flex justify-content-center align-items-center w-100"
                                id="login-nav-tab"
                                role="tablist"
                              >
                                <button
                                  className={`nav-link ${
                                    activeTab === "mobile" ? "active" : ""
                                  }`}
                                  type="button"
                                  onClick={() => {
                                    setActiveTab("mobile");
                                    setFieldValue("email", "");
                                    setErrors({});
                                    setTouched({});
                                    setIsOtpSent(false);
                                    clearError();
                                  }}
                                >
                                  Mobile
                                </button>
                                <button
                                  className={`nav-link ${
                                    activeTab === "email" ? "active" : ""
                                  }`}
                                  type="button"
                                  onClick={() => {
                                    setActiveTab("email");
                                    setFieldValue("phone", "");
                                    setFieldValue("countryCode", "");
                                    setErrors({});
                                    setTouched({});
                                    setIsOtpSent(false);
                                    clearError();
                                  }}
                                >
                                  Email
                                </button>
                              </div>
                            </nav>
                            <div
                              className="tab-content"
                              id="login-nav-tabContent"
                            >
                              {activeTab === "mobile" && (
                                <div className="login-text-area">
                                  <PhoneInput />
                                </div>
                              )}
                              {activeTab === "email" && (
                                <div className="login-text-area">
                                  <InputField
                                    name="email"
                                    type="email"
                                    placeholder="Enter email ID"
                                  />
                                </div>
                              )}
                            </div>
                          </div>

                          <div className="col-12 mb-3">
                            <CheckboxField
                              name="rememberMe"
                              label="Remember me"
                            />
                          </div>

                          <div className="col-12">
                            <button
                              type="submit"
                              className="button btn-first btn-first-pink w-100 fw-normal"
                              disabled={isButtonDisabled}
                              style={
                                isButtonDisabled
                                  ? { pointerEvents: "none", opacity: 0.6, cursor: "not-allowed" }
                                  : {}
                              }
                            >
                              {isSubmitting ? "Sending..." : isOtpSent ? "Redirecting..." : "Request Code"}
                            </button>
                            {errorMessage && (
                              <div className="text-danger text-center mt-2">
                                {errorMessage}
                              </div>
                            )}
                          </div>
                        </fieldset>
                      </Form>
                    ));
                  }}
                </Formik>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default LoginForm;
