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

import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import React, { useEffect, useMemo } 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 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";
import { useUser } from "@/hooks/useUser";
import { useTranslation } from "react-i18next";
import {
  getIranBankName,
  isValidIranSheba,
  stripShebaPrefix,
} from "@/lib/iranSheba";
import { isValidIranNationalCode } from "@/lib/iranNationalCode";

const p2e = (es: string): string =>
  es.replace(/[۰-۹]/g, (d) => String.fromCharCode("۰۱۲۳۴۵۶۷۸۹".indexOf(d) + 48));

function ShabaPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const user = useUser();

  const schema = useMemo(
    () =>
      yup.object().shape({
        nationalCode: yup
          .string()
          .matches(/^\d{10}$/, t("auth.nationalCodeInvalid"))
          .test(
            "checksum",
            t("settings.edit.shaba.nationalCodeInvalid"),
            (value) => !!value && isValidIranNationalCode(value)
          )
          .required(t("auth.nationalCodeRequired")),
        birthDate: yup.string().required(t("auth.birthDateRequired")),
        shaba: yup
          .string()
          .matches(/^\d{24}$/, t("settings.edit.shaba.invalid"))
          .test(
            "checksum",
            t("settings.edit.shaba.invalid"),
            (value) => !!value && isValidIranSheba(value)
          )
          .required(t("settings.edit.shaba.required")),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      nationalCode: "",
      birthDate: "",
      shaba: "",
    },
    validationSchema: schema,
    onSubmit: async (values, { setSubmitting }) => {
      try {
        await request("POST", "/verify/auth", {
          birthday: moment(p2e(values.birthDate), "jYYYY/jMM/jDD").format(
            "YYYY/MM/DD"
          ),
          national_code: values.nationalCode,
          shaba: values.shaba,
        });
        toast.success(t("settings.edit.shaba.saveSuccess"));
        router.push("/settings/edit");
      } catch (err: any) {
        const status = err?.response?.status;
        const message =
          status === 409
            ? t("settings.edit.shaba.nationalCodeDuplicate")
            : err?.response?.data?.message || t("settings.edit.shaba.saveError");
        toast.error(message);
      } finally {
        setSubmitting(false);
      }
    },
  });

  useEffect(() => {
    if (!user) return;

    const patch: Partial<typeof formik.values> = {};
    if (user.shaba) patch.shaba = stripShebaPrefix(user.shaba);
    if (user.national_code) patch.nationalCode = user.national_code;
    if (user.birthday) {
      patch.birthDate = moment(user.birthday, "YYYY/MM/DD").format(
        "jYYYY/jMM/jDD"
      );
    }

    if (Object.keys(patch).length > 0) {
      formik.setValues((prev) => ({ ...prev, ...patch }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.shaba, user?.national_code, user?.birthday]);

  const nationalCodeValid = isValidIranNationalCode(formik.values.nationalCode);
  const shebaValid = isValidIranSheba(formik.values.shaba);
  const bankName = shebaValid ? getIranBankName(formik.values.shaba) : null;

  const isVerified = user?.is_verified;
  const verifyDisabled = isVerified === "pending" || isVerified === "verified";
  const verifyLabel =
    isVerified === "verified"
      ? t("settings.edit.shaba.verifyIdentityDone")
      : isVerified === "pending"
        ? t("settings.edit.shaba.verifyIdentityPending")
        : t("settings.edit.shaba.verifyIdentityButton");

  const canSave =
    nationalCodeValid && shebaValid && Boolean(formik.values.birthDate) && !loading;

  return (
    <LocalePageShell>
      <Container>
        <div className="p-4 flex flex-col items-center min-h-screen justify-center auth-page">
          <span className="text-xl font-bold text-foreground">
            {t("settings.edit.nav.shaba")}
          </span>
          <form
            onSubmit={formik.handleSubmit}
            className="w-full max-w-sm flex flex-col items-center"
          >
            <small className="font-bold mt-10 mb-4 text-center">
              {t("settings.edit.shaba.forPayout")}
            </small>

            <div className="flex w-full gap-2 max-w-[300px]">
              <div>
                <AuthInput
                  name="nationalCode"
                  type="text"
                  inputMode="numeric"
                  maxLength={10}
                  placeholder={t("auth.nationalCodePlaceholder")}
                  className="!p-1 h-[36px] mt-2"
                  success={nationalCodeValid}
                  error={Boolean(
                    formik.touched.nationalCode && formik.errors.nationalCode
                  )}
                  value={formik.values.nationalCode}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                />
              </div>
              <div className="relative">
                <DatePicker
                  id="birthDate"
                  calendar={persian}
                  locale={persian_fa}
                  value={formik.values.birthDate}
                  onChange={(value) => {
                    formik.setFieldValue(
                      "birthDate",
                      value?.format("YYYY/MM/DD") || ""
                    );
                  }}
                  calendarPosition="bottom-center"
                  placeholder={t("auth.birthDatePlaceholder")}
                  inputClass={`w-full dir-ltr max-w-[290px] p-3 !pr-6 text-center rounded-2xl border bg-secondary-light dark:bg-secondary-dark font-medium mt-2 !p-1 h-[36px] ${
                    formik.touched.birthDate && formik.errors.birthDate
                      ? "border-red-500 dark:border-red-500"
                      : "border-gray-300"
                  }`}
                />
                <label htmlFor="birthDate" 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>
            )}

            <div className="flex flex-col w-full relative mt-8">
              <span className="absolute left-4 top-1.5 z-10">IR</span>
              <AuthInput
                name="shaba"
                type="text"
                inputMode="numeric"
                maxLength={24}
                placeholder={t("settings.edit.shaba.placeholder")}
                className="w-full mx-auto h-[36px] p-2 max-w-full pl-8 text-sm"
                success={shebaValid}
                error={Boolean(formik.touched.shaba && formik.errors.shaba)}
                value={formik.values.shaba}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
              {bankName && (
                <small className="mt-2 text-center text-xs font-semibold text-green-600 dark:text-green-400">
                  {bankName}
                </small>
              )}
              {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 text-center">
              {t("settings.edit.shaba.mustBeOwn")}
            </small>

            <AuthNextButton
              type="button"
              className="mt-10"
              disabled={verifyDisabled}
              onClick={() => router.push("/settings/edit/Authentication")}
            >
              {verifyLabel}
            </AuthNextButton>
            {isVerified === "rejected" && (
              <small className="text-red-500 mt-2 block text-center">
                {t("settings.edit.shaba.verifyIdentityRejectedHint")}
              </small>
            )}

            <AuthNextButton
              type="submit"
              variant="primary"
              className="mt-5"
              loading={loading}
              disabled={!canSave}
            >
              {t("settings.edit.shaba.saveButton")}
            </AuthNextButton>
          </form>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default ShabaPage;
