import Link from "next/link";
import { redirect } from "next/navigation";
import { AuthPageShell } from "@/components/auth-page-shell";
import {
  getMailEntryUrlForCurrentRequest,
  getSessionUser,
  redirectToCanonicalMailAuthHostIfNeeded,
} from "@/lib/auth";
import { toSearchString } from "@/lib/mail-urls";
import { findUserEmailsByCompanyName } from "@/lib/official-mail";

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

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

export default async function FindIdPage({ searchParams }: FindIdPageProps) {
  const params = searchParams ? await searchParams : {};
  await redirectToCanonicalMailAuthHostIfNeeded(
    "/find-id",
    toSearchString(params),
  );
  const user = await getSessionUser();
  const companyName = pickParam(params.companyName)?.trim() ?? "";

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

  const matchedUsers = companyName
    ? await findUserEmailsByCompanyName(companyName)
    : [];

  return (
    <AuthPageShell
      title="아이디 찾기"
      description="가입한 사업자명을 입력하면 등록된 로그인 이메일을 마스킹된 형태로 확인할 수 있습니다."
    >
      <form method="get" action="/find-id" className="space-y-4">
        <label className="block">
          <span className="mb-2 block text-[14px] font-medium text-[#6f7784]">
            사업자명
          </span>
          <input
            required
            type="text"
            name="companyName"
            defaultValue={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>

        <button
          type="submit"
          className="om-btn-primary h-[56px] w-full rounded-[12px] px-5 text-[18px] tracking-[-0.04em]"
        >
          이메일 찾기
        </button>
      </form>

      {companyName ? (
        <div className="mt-6 rounded-[14px] border border-[#dbe2ec] bg-[#f8fbff] px-5 py-5">
          {matchedUsers.length > 0 ? (
            <>
              <p className="text-[14px] font-medium text-[#5d6777]">
                <span className="font-semibold text-[#121a2f]">
                  {companyName}
                </span>
                으로 등록된 계정입니다.
              </p>
              <ul className="mt-4 space-y-3">
                {matchedUsers.map((matchedUser) => (
                  <li
                    key={`${matchedUser.maskedEmail}:${matchedUser.displayName ?? matchedUser.companyName}`}
                    className="rounded-[12px] border border-white bg-white px-4 py-3 text-[15px] text-[#121a2f]"
                  >
                    <span className="font-semibold">
                      {matchedUser.maskedEmail}
                    </span>
                    <span className="ml-2 text-[#7f8791]">
                      ({matchedUser.displayName || matchedUser.companyName})
                    </span>
                  </li>
                ))}
              </ul>
            </>
          ) : (
            <p className="text-[14px] leading-7 text-[#d9485c]">
              입력한 사업자명으로 등록된 계정을 찾지 못했습니다.
            </p>
          )}
        </div>
      ) : null}

      <div className="mt-6 text-center text-[14px] text-[#7f8791]">
        비밀번호를 재설정하려면{" "}
        <Link href="/reset-password" className="font-semibold text-[#2f6df6]">
          비밀번호 찾기
        </Link>
      </div>
    </AuthPageShell>
  );
}
