"use client";

import SocialAuthButtons from "./SocialAuthButtons";
import React from "react";
import { Formik, Form } from "formik";
import Input from "@/components/ui/Input";
import CheckBox from "@/components/ui/CheckBox";
import Button from "@/components/ui/Button";
import Link from "next/link";

import Loader from "@/components/ui/Loader";
import { useTranslation } from "react-i18next";
import { useLoginForm } from "./useLoginForm";
import type { MandatePrefillUser } from "./volunteerMandateParts";
import type { OtpType } from "@/features/auth/services/authApi";
import type { FormikProps } from "formik";
import type { LoginFormValues } from "./useLoginForm";

export interface LoginFormProps {
  /** From `?user_type=` on the standalone page; drives where new social users land. */
  userType?: string | null;
  /** Where to go after a successful login on the standalone page. */
  returnTo?: string;
  /**
   * Modal mode. The opportunity pages host this form inside a Modal instead of
   * navigating to /login, so every "go to another page" branch becomes a
   * callback the host swaps its own modal content with.
   */
  isModal?: boolean;
  onClose?: () => void;
  onShowEmailVerification?: (email: string, otpType: OtpType) => void;
  onShowRegistration?: () => void;
  onShowVolunteerMandateDetails?: (userData: MandatePrefillUser) => void;
  onShowForgotPassword?: () => void;
}

export default function LoginForm({
  userType = null,
  returnTo = "/",
  isModal = false,
  onClose,
  onShowEmailVerification,
  onShowRegistration,
  onShowVolunteerMandateDetails,
  onShowForgotPassword,
}: LoginFormProps) {
  const { t } = useTranslation();
  const {
    initialFormValues,
    validationSchema,
    loginMutation,
    handleSubmit,
    googleLogin,
    isSocialLoading,
    isLoading,
  } = useLoginForm({
    userType,
    returnTo,
    isModal,
    onClose,
    onShowEmailVerification,
    onShowRegistration,
    onShowVolunteerMandateDetails,
    onShowForgotPassword,
  });

  const form = (
    <>
      {isSocialLoading && (
        <div className="fixed inset-0 flex items-center justify-center z-50 bg-white/50">
          <Loader />
        </div>
      )}
      {!isModal && (
        <h2 className="2xl:pb-11 lg:pb-5 pb-5 text-center font-bold text-[28px] 2xl:text-[50px] tracking-[0px] text-[#29246D]">
          {t("COMMON.LOGIN")}
        </h2>
      )}

      <Formik
        initialValues={initialFormValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
        enableReinitialize={true}
      >
        {({ values, setFieldValue }: FormikProps<LoginFormValues>) => (
          <div className="flex justify-center">
            <div className="w-[90%] 2xl:w-[568px] lg:w-[568px] md:w-[90%] rounded-lg bg-white">
              <Form>
                <Input
                  name="email"
                  type="text"
                  label={t("COMMON.EMAILPLACEHOLDER")}
                />
                <Input
                  name="password"
                  type="password"
                  label={t("COMMON.PASSWORDPLACEHOLDER")}
                />
                <div className="flex items-center mb-6 justify-between">
                  <CheckBox
                    id="rememberMe"
                    label={t("COMMON.KEEP_ME_LOGGED_IN")}
                    checked={values.rememberMe}
                    onChange={(checked) => setFieldValue("rememberMe", checked)}
                  />
                  <span className="pt-[10px] extrasmall:text-xs text-end text-primary-504 border-b border-b-primary-504 pb-1 text-lg xss:text-base font-bold">
                    {isModal ? (
                      <button
                        type="button"
                        onClick={(event) => {
                          event.preventDefault();
                          onShowForgotPassword?.();
                        }}
                      >
                        {t("COMMON.FORGOT_PASSWORD")}
                      </button>
                    ) : (
                      <Link href="/forgot-password">
                        {t("COMMON.FORGOT_PASSWORD")}
                      </Link>
                    )}
                  </span>
                </div>
                <Button className="mx-auto mt-[25px]" variant="primary" size="medium" type="submit" disabled={isLoading} loading={loginMutation.isPending} >
                  {t("COMMON.LOGIN")}
                </Button>

                <div>
                  <p className="font-semibold text-[18px] xss:text-base leading-[24.51px] py-8 text-primary-5 flex items-center w-full before:flex-1 before:border-t before:border-primary-5 before:mr-4 after:flex-1 after:border-t after:border-primary-5 after:ml-4 rtl:gap-[20px]">
                    {isModal ? t("COMMON.OR.BY") : t("COMMON.SIGNINWITH")}
                  </p>
                </div>

                <SocialAuthButtons
                  onGoogle={googleLogin}
                />
                {/* A19 — the password login answers a legacy LinkedIn account only "uses social login". */}
                {/* <p className="pt-4 text-center text-sm text-secondary-102">{t("COMMON.LEGACY_LINKEDIN_HINT")}</p> */}

                <p className="items-center text-primary-5 text-center font-[400] text-[20px] leading-[27.24px] pt-7 xss:text-base gap-[10px] flex justify-center">
                  {isModal
                    ? t("COMMON.DONT.HAVE.ACCOUNT")
                    : t("COMMON.NO_ACCOUNT")}
                  {isModal ? (
                    <button
                      type="button"
                      onClick={onShowRegistration}
                      dir="rtl"
                      className="border-b-2 text-primary-504 border-b-primary-504 font-bold"
                    >
                      {t("COMMON.SIGN.UP")}
                    </button>
                  ) : (
                    <Link
                      href="/joinus"
                      dir="rtl"
                      className="border-b-2 pb-1 pt-1 text-primary-504 font-bold border-b-primary-504"
                    >
                      {t("COMMON.CREATE_ACCOUNT")}
                    </Link>
                  )}
                </p>
              </Form>
            </div>
          </div>
        )}
      </Formik>
    </>
  );

  if (isModal) {
    return (
      <div className="loguser">
        <div className="relative">{form}</div>
      </div>
    );
  }

  return (
    <div className="border-t border-[#000]">
      <div className="2xl:py-[40px] laptopmain:py-[50px] laptop:py-[40px] lg:py-[40px] py-[40px] relative">
        {form}
      </div>
    </div>
  );
}
