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

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import React 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 AuthUserDetails from "@/components/auth/AuthUserDetails";
import AuthInput from "@/components/auth/AuthInput";
import DatePicker from "react-multi-date-picker";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";
import Image from "next/image";
import moment from "jalali-moment";

// Validation schema using Yup
const schema = yup.object().shape({
  birthDate: yup.string().required(" انتخاب تاریخ تولد الزامی است"),
  shaba: yup
    .string()
    .matches(/^(?=.{24}$)[0-9]*$/, "شماره شبا باید ۲۴ رقم باشد")
    .required("شماره شبا الزامی است"),
  nationalCode: yup
    .string()
    .matches(/^\d{10}$/, "کد ملی باید ۱۰ رقم باشد")
    .required("کد ملی الزامی است"),
});

function AuthPage() {
  const router = useRouter();
  const { request, loading } = useAxios();
  
  const p2e = (es: string): string =>
    es.replace(/[۰-۹]/g, (d) => String.fromCharCode("۰۱۲۳۴۵۶۷۸۹".indexOf(d) + 48));
  
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const formik = useFormik({
    initialValues: {
      nationalCode: "",
      birthDate: "",
      shaba: "",
    },
    validationSchema: schema,
    onSubmit: async (values, { setSubmitting }) => {
      try {
        await request("POST", "/verify/auth", {
          mobile: mobile,
          birthday: moment(p2e(values.birthDate), "jYYYY/jMM/jDD").format(
            "YYYY/MM/DD"
          ), // تبدیل به میلادی
          national_code: values.nationalCode,
          shaba: values.shaba,
        });
        router.push("/verify/location");
      } catch (err: any) {
        toast.error(err?.message || "خطای نامشخصی رخ داد.");
      } finally {
        setSubmitting(false);
      }
    },
  });

  console.log(formik.values);

  return (
    <AuthPageLayout className="auth-page">
      <form
        onSubmit={formik.handleSubmit}
        className="flex w-full flex-1 flex-col items-center"
      >
        <AuthPageContent>
          <span className="text-xl font-bold">احراز هویت</span>
          <div className="mt-5">
            <AuthUserDetails />
          </div>

          <div className="w-full max-w-sm flex flex-col items-center">
          <small className="font-bold mt-10 mb-4"> جهت احراز هویت</small>
          <div className="flex w-full gap-2 max-w-[300px]">
            <div>
              {/* کد ملی */}
              <AuthInput
                name="nationalCode"
                type="text"
                placeholder="کد ملی"
                className={`border mt-2 !p-1 h-[36px] ${
                  formik.touched.nationalCode && formik.errors.nationalCode
                    ? "border-red-500 dark:border-red-500"
                    : "border-gray-300"
                }`}
                value={formik.values.nationalCode}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            </div>
            {/* تاریخ تولد */}
            <div className="relative">
              <DatePicker
                id="ss"
                calendar={persian}
                locale={persian_fa}
                value={formik.values.birthDate}
                onChange={(value) => {
                  const formattedDate = value?.format("YYYY/MM/DD") || ""; // اگر مقدار `null` بود، رشته خالی
                  formik.setFieldValue("birthDate", formattedDate); // مقدار فرم را تنظیم کنید
                }}
                calendarPosition="bottom-center"
                placeholder="تاریخ تولد"
                inputClass={`w-full dir-ltr max-w-[290px] p-3 !pr-6 text-center rounded-2xl border border-border-primary-light dark:border-border-primary-dark bg-secondary-light dark:bg-secondary-dark font-medium border mt-2 !p-1 h-[36px] ${
                  formik.touched.birthDate && formik.errors.birthDate
                    ? "border-red-500 dark:border-red-500"
                    : "border-gray-300"
                }`}
              />
              <label htmlFor="ss" className="absolute right-4 top-3.5">
                <Image
                  width={24}
                  height={24}
                  alt="calendar icon"
                  src={"/images/icons/calendar.svg"}
                />
              </label>
            </div>
          </div>

          {formik.touched.nationalCode && formik.errors.nationalCode && (
            <small className="text-red-500 mt-2 block text-center">
              {formik.errors.nationalCode}
            </small>
          )}
          {formik.touched.birthDate && formik.errors.birthDate && (
            <small className="text-red-500 mt-2 block text-center">
              {formik.errors.birthDate}
            </small>
          )}
          <small className="font-bold mt-10"> جهت واریز حق الزحمه</small>
          {/* شماره شبا */}
          <div className="flex flex-col w-full relative mt-4 ">
            <span className="absolute left-4 top-1.5">IR</span>
            <AuthInput
              name="shaba"
              type="text"
              placeholder="شماره شبا"
              className={`border w-full mx-auto h-[36px] p-2 max-w-full pl-8 text-sm ${
                formik.touched.shaba && formik.errors.shaba
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.shaba}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
            />
            {formik.touched.shaba && formik.errors.shaba && (
              <small className="text-red-500 mt-2 block text-center">
                {formik.errors.shaba}
              </small>
            )}
          </div>

          <small className="font-bold mt-10">
            شماره شبا باید به نام خود شخص باشد
          </small>
          </div>
        </AuthPageContent>

        <AuthFormFooter onSkip={() => router.push("/verify/location")}>
          <AuthNextButton type="submit" loading={loading} disabled={loading}>
            ثبت و ادامه
          </AuthNextButton>
        </AuthFormFooter>
      </form>
    </AuthPageLayout>
  );
}

export default AuthPage;
