"use client";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import AuthOtpInput from "@/components/auth/AuthOtpInput";
import AuthNextButton from "@/components/auth/AuthNextButton";
import useAxios from "@/hooks/useAxios";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type TotpStatus = {
  enabled: boolean;
};

type TotpSetup = {
  secret: string;
  otpauth_url: string;
};

function getApiErrorMessage(err: unknown): string | undefined {
  const data = (
    err as { response?: { data?: { message?: string; en_message?: string } } }
  )?.response?.data;

  if (!data) return undefined;

  const generic = "خطایی در عملیات مورد نظر رخ داده است.";
  if (data.message && data.message !== generic) return data.message;
  if (data.en_message) return data.en_message;

  return data.message;
}

export default function TwoFactorSettingsPage() {
  const { t } = useTranslation("common");
  const { request, loading } = useAxios();
  const [status, setStatus] = useState<TotpStatus | null>(null);
  const [setup, setSetup] = useState<TotpSetup | null>(null);
  const [code, setCode] = useState("");
  const [pageLoading, setPageLoading] = useState(true);

  const qrCodeUrl = useMemo(() => {
    if (!setup?.otpauth_url) return null;
    return `https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=${encodeURIComponent(
      setup.otpauth_url
    )}`;
  }, [setup?.otpauth_url]);

  const loadStatus = useCallback(async () => {
    setPageLoading(true);
    try {
      const data = (await request("GET", "/auth/totp/status")) as TotpStatus;
      setStatus(data);
    } catch {
      toast.error(t("settings.edit.twoFactor.loadError"));
    } finally {
      setPageLoading(false);
    }
  }, [request, t]);

  useEffect(() => {
    loadStatus();
  }, [loadStatus]);

  const startSetup = async () => {
    try {
      const data = (await request("POST", "/auth/totp/setup", {})) as TotpSetup;
      setSetup(data);
      setCode("");
    } catch (err: unknown) {
      const detail = getApiErrorMessage(err);
      toast.error(
        detail
          ? `${t("settings.edit.twoFactor.setupError")} (${detail})`
          : t("settings.edit.twoFactor.setupError")
      );
    }
  };

  const cancelSetup = () => {
    setSetup(null);
    setCode("");
  };

  const copySecret = async () => {
    if (!setup?.secret) return;
    try {
      await navigator.clipboard.writeText(setup.secret);
      toast.success(t("settings.edit.twoFactor.secretCopied"));
    } catch {
      toast.error(t("settings.edit.twoFactor.copyFailed"));
    }
  };

  const enableTotp = async () => {
    if (code.length !== 6) return;
    try {
      await request("POST", "/auth/totp/enable", { code });
      toast.success(t("settings.edit.twoFactor.enableSuccess"));
      setSetup(null);
      setCode("");
      await loadStatus();
    } catch (err: unknown) {
      const detail = getApiErrorMessage(err);
      toast.error(detail || t("settings.edit.twoFactor.invalidCode"));
    }
  };

  const disableTotp = async () => {
    if (code.length !== 6) return;
    try {
      await request("POST", "/auth/totp/disable", { code });
      toast.success(t("settings.edit.twoFactor.disableSuccess"));
      setCode("");
      await loadStatus();
    } catch (err: unknown) {
      const detail = getApiErrorMessage(err);
      toast.error(detail || t("settings.edit.twoFactor.invalidCode"));
    }
  };

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.edit.nav.twoFactor")}</PageTitle>
        <div className="mx-auto flex max-w-md flex-col items-center py-8">
          {pageLoading ? (
            <p className="text-sm text-neutral-500">{t("common.loading")}</p>
          ) : status?.enabled ? (
            <>
              <p className="mb-6 text-center text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.twoFactor.enabledHint")}
              </p>
              <AuthOtpInput value={code} onChange={setCode} className="mt-2" />
              <AuthNextButton
                type="button"
                className="mt-6"
                loading={loading}
                disabled={loading || code.length !== 6}
                onClick={disableTotp}
              >
                {t("settings.edit.twoFactor.disableButton")}
              </AuthNextButton>
            </>
          ) : setup ? (
            <>
              <p className="mb-4 text-center text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.twoFactor.scanHint")}
              </p>
              {qrCodeUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={qrCodeUrl}
                  alt={t("settings.edit.nav.twoFactor")}
                  width={220}
                  height={220}
                  className="mb-4 rounded-lg bg-white p-2"
                />
              ) : null}
              <p
                className="mb-2 text-center text-xs text-neutral-500"
                dir="ltr"
              >
                {setup.secret}
              </p>
              <button
                type="button"
                onClick={copySecret}
                className="mb-4 text-xs text-[#0033EA] underline"
              >
                {t("settings.edit.twoFactor.copySecret")}
              </button>
              <AuthOtpInput value={code} onChange={setCode} />
              <AuthNextButton
                type="button"
                className="mt-6"
                loading={loading}
                disabled={loading || code.length !== 6}
                onClick={enableTotp}
              >
                {t("settings.edit.twoFactor.enableButton")}
              </AuthNextButton>
              <button
                type="button"
                onClick={cancelSetup}
                className="mt-4 text-sm text-neutral-500 underline"
              >
                {t("settings.edit.twoFactor.cancelSetup")}
              </button>
            </>
          ) : (
            <>
              <p className="mb-6 text-center text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.twoFactor.disabledHint")}
              </p>
              <AuthNextButton
                type="button"
                loading={loading}
                disabled={loading}
                onClick={startSetup}
              >
                {t("settings.edit.twoFactor.startSetup")}
              </AuthNextButton>
            </>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}
