/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import AuthHead from "@/components/auth/AuthHead";
import AuthInput from "@/components/auth/AuthInput";
import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import React, { useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import AuthNextButton from "@/components/auth/AuthNextButton";
import toast from "react-hot-toast";
import { getSafeRedirectPath } from "@/lib/auth/postLogin";

const schema = yup.object().shape({
  name: yup.string().trim().required("نام الزامی است").min(2, "نام کوتاه است"),
  family: yup.string().trim().optional(),
});

function FullNamePage() {
  const router = useRouter();
  const { request, loading } = useAxios();
  const [nameSaved, setNameSaved] = useState(false);
  const [choiceLoading, setChoiceLoading] = useState<"app" | "continue" | null>(
    null
  );

  const formik = useFormik({
    initialValues: {
      family: "",
      name: "",
    },
    validationSchema: schema,
    onSubmit: async (values, { setSubmitting }) => {
      try {
        await request("POST", "/register/fullname", {
          first_name: values.name.trim(),
          last_name: values.family.trim() || undefined,
        });

        localStorage.setItem("first_name", values.name.trim());
        if (values.family.trim()) {
          localStorage.setItem("last_name", values.family.trim());
        } else {
          localStorage.removeItem("last_name");
        }

        setNameSaved(true);
        toast.success("نام با موفقیت ثبت شد");
      } catch (err: any) {
        toast.error(err?.response?.data?.message || "خطا در ذخیره نام");
      } finally {
        setSubmitting(false);
      }
    },
  });

  const finishRegistration = async (action: "app" | "continue") => {
    setChoiceLoading(action);
    try {
      await request("POST", "/register/user_type", {
        user_type: "user",
      });
      localStorage.setItem("usertype", "user");

      if (action === "continue") {
        router.push("/verify/avatar");
      } else {
        router.push(getSafeRedirectPath());
      }
    } catch (err: any) {
      toast.error(err?.response?.data?.message || "خطا در تکمیل ثبت‌نام");
    } finally {
      setChoiceLoading(null);
    }
  };

  return (
    <AuthPageLayout>
      <form
        onSubmit={formik.handleSubmit}
        className="flex w-full flex-1 flex-col items-center"
      >
        <AuthPageContent>
          <AuthHead title="نام و نام خانوادگی" />
          <div className="w-full max-w-sm flex flex-col items-center">
            <AuthInput
              name="name"
              type="text"
              placeholder="نام *"
              dir="rtl"
              disabled={nameSaved || loading}
              className={`border mt-4 ${
                formik.touched.name && formik.errors.name
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.name && formik.errors.name && (
              <small className="text-red-500 mt-2 block text-center">
                {formik.errors.name}
              </small>
            )}

            <AuthInput
              name="family"
              type="text"
              placeholder="نام خانوادگی (اختیاری)"
              dir="rtl"
              disabled={nameSaved || loading}
              className={`border mt-4 ${
                formik.touched.family && formik.errors.family
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.family}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.family && formik.errors.family && (
              <small className="text-red-500 mt-2 block text-center">
                {formik.errors.family}
              </small>
            )}

            {nameSaved && (
              <p className="text-sm text-green-600 text-center mt-4">
                نام شما ثبت شد. یکی از گزینه‌های زیر را انتخاب کنید.
              </p>
            )}
          </div>
        </AuthPageContent>

        <AuthFormFooter>
          {!nameSaved ? (
            <AuthNextButton
              type="submit"
              disabled={loading || !formik.values.name.trim()}
              loading={loading}
            >
              ثبت و ادامه
            </AuthNextButton>
          ) : (
            <div className="flex flex-col sm:flex-row gap-3 w-full max-w-sm justify-center items-center">
              <AuthNextButton
                type="button"
                onClick={() => finishRegistration("continue")}
                className="!border-[#0C8002] !text-[#0C8002] w-full sm:w-auto"
                disabled={Boolean(choiceLoading)}
                loading={choiceLoading === "continue"}
              >
                ادامه ثبت نام
              </AuthNextButton>
              <AuthNextButton
                type="button"
                onClick={() => finishRegistration("app")}
                className="!border-[#FF0000] !text-[#FF0000] w-full sm:w-auto"
                disabled={Boolean(choiceLoading)}
                loading={choiceLoading === "app"}
              >
                ورود به برنامه
              </AuthNextButton>
            </div>
          )}
        </AuthFormFooter>
      </form>
    </AuthPageLayout>
  );
}

export default FullNamePage;
