import Link from "next/link";
import { redirect } from "next/navigation";
import { requestPasswordResetAction } from "@/app/actions/session";
import { AuthPageShell } from "@/components/auth-page-shell";
import { DismissibleBottomToast } from "@/components/dismissible-bottom-toast";
import { SubmitButton } from "@/components/submit-button";
import {
  getMailEntryUrlForCurrentRequest,
  getSessionUser,
  redirectToCanonicalMailAuthHostIfNeeded,
} from "@/lib/auth";
import { toSearchString } from "@/lib/mail-urls";

type ResetPasswordPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

function pickParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

export default async function ResetPasswordPage({
  searchParams,
}: ResetPasswordPageProps) {
  const params = searchParams ? await searchParams : {};
  await redirectToCanonicalMailAuthHostIfNeeded(
    "/reset-password",
    toSearchString(params),
  );
  const user = await getSessionUser();
  const error = pickParam(params.error);
  const success = pickParam(params.success);
  const masked = pickParam(params.masked);
  const notice = error
    ? {
        tone: "error" as const,
        message:
          error === "required"
            ? "로그인 이메일과 사업자명을 모두 입력해주세요."
            : error === "not-found"
              ? "일치하는 계정을 찾지 못했습니다. 이메일과 사업자명을 다시 확인해주세요."
              : error === "recovery-email-missing"
                ? "보조 이메일이 등록되지 않았거나 아직 인증되지 않은 계정입니다."
                : "비밀번호 재설정 링크 발송 중 오류가 발생했습니다.",
      }
    : success === "link-sent"
      ? {
          tone: "success" as const,
          message: masked
            ? `보조 이메일 ${masked} 로 비밀번호 재설정 링크를 보냈습니다.`
            : "보조 이메일로 비밀번호 재설정 링크를 보냈습니다.",
        }
      : null;

  if (user) {
    redirect(await getMailEntryUrlForCurrentRequest(user));
  }

  return (
    <AuthPageShell
      title="비밀번호 찾기"
      description="가입한 로그인 이메일과 사업자명을 입력하면 보조 이메일로 5분 동안 유효한 재설정 링크를 보냅니다."
    >
      <DismissibleBottomToast
        notice={notice}
        clearSearchParams={["error", "success", "details", "masked"]}
      />
      <form action={requestPasswordResetAction} className="space-y-4">
        <label className="block">
          <span className="mb-2 block text-[14px] font-medium text-[#6f7784]">
            로그인 이메일
          </span>
          <input
            required
            type="email"
            name="email"
            className="h-[54px] w-full rounded-[12px] border border-[#d7deea] px-4 text-[16px] text-[#101418] outline-none transition-colors focus:border-[#2f6df6]"
            placeholder="이메일 주소를 입력하세요"
          />
        </label>

        <label className="block">
          <span className="mb-2 block text-[14px] font-medium text-[#6f7784]">
            사업자명
          </span>
          <input
            required
            type="text"
            name="companyName"
            className="h-[54px] w-full rounded-[12px] border border-[#d7deea] px-4 text-[16px] text-[#101418] outline-none transition-colors focus:border-[#2f6df6]"
            placeholder="사업자명을 입력하세요"
          />
        </label>

        <SubmitButton
          label="재설정 링크 보내기"
          pendingLabel="발송 중..."
          className="om-btn-primary h-[56px] w-full rounded-[12px] px-5 text-[18px] tracking-[-0.04em]"
        />
      </form>

      <div className="mt-6 text-center text-[14px] text-[#7f8791]">
        로그인 페이지로 돌아가려면{" "}
        <Link href="/login" className="font-semibold text-[#2f6df6]">
          로그인
        </Link>
      </div>
    </AuthPageShell>
  );
}
