"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

const NOTICE_ID = "dkim-key-rotation-2026-08-18";
const NOTICE_STORAGE_PREFIX = `official-mail:notice:${NOTICE_ID}`;
const SNOOZE_STORAGE_KEY = `${NOTICE_STORAGE_PREFIX}:snooze-until`;
const SESSION_DISMISS_STORAGE_KEY = `${NOTICE_STORAGE_PREFIX}:dismissed`;
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;

function DkimNoticeIcon() {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="h-6 w-6"
    >
      <path d="M12 3 4.5 6.4v5.2c0 4.6 3.1 7.8 7.5 9.4 4.4-1.6 7.5-4.8 7.5-9.4V6.4L12 3Z" />
      <path d="m9.4 12 1.7 1.7 3.7-4" />
    </svg>
  );
}

export function MailServiceNoticeDialog({ domain }: { domain: string }) {
  const [open, setOpen] = useState(false);
  const closeButtonRef = useRef<HTMLButtonElement | null>(null);

  useEffect(() => {
    const snoozeUntil = Number(window.localStorage.getItem(SNOOZE_STORAGE_KEY) ?? "0");
    const dismissedForSession =
      window.sessionStorage.getItem(SESSION_DISMISS_STORAGE_KEY) === "1";

    if (snoozeUntil > Date.now() || dismissedForSession) {
      return;
    }

    if (snoozeUntil) {
      window.localStorage.removeItem(SNOOZE_STORAGE_KEY);
    }

    const openTimer = window.setTimeout(() => setOpen(true), 0);
    return () => window.clearTimeout(openTimer);
  }, []);

  useEffect(() => {
    if (!open) {
      return;
    }

    closeButtonRef.current?.focus();

    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key !== "Escape") {
        return;
      }

      window.sessionStorage.setItem(SESSION_DISMISS_STORAGE_KEY, "1");
      setOpen(false);
    };

    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, [open]);

  const closeForSession = () => {
    window.sessionStorage.setItem(SESSION_DISMISS_STORAGE_KEY, "1");
    setOpen(false);
  };

  const snoozeForSevenDays = () => {
    window.localStorage.setItem(
      SNOOZE_STORAGE_KEY,
      String(Date.now() + SEVEN_DAYS_MS),
    );
    setOpen(false);
  };

  if (!open || typeof document === "undefined") {
    return null;
  }

  return createPortal(
    <div className="fixed inset-0 z-[200] flex items-center justify-center bg-[rgba(13,23,42,0.46)] px-4 py-8 backdrop-blur-[4px]">
      <section
        role="dialog"
        aria-modal="true"
        aria-labelledby="mail-service-notice-title"
        aria-describedby="mail-service-notice-description"
        className="w-full max-w-[520px] overflow-hidden rounded-[24px] border border-[#dce6f7] bg-white shadow-[0_30px_90px_rgba(15,34,68,0.24)]"
      >
        <div className="relative overflow-hidden bg-[linear-gradient(135deg,#eef5ff_0%,#f8fbff_58%,#eef9f4_100%)] px-6 pb-6 pt-7 sm:px-8 sm:pt-8">
          <div className="absolute -right-14 -top-16 h-40 w-40 rounded-full bg-[#bcd2ff]/35 blur-2xl" />
          <button
            ref={closeButtonRef}
            type="button"
            aria-label="공지 닫기"
            onClick={closeForSession}
            className="absolute right-4 top-4 z-10 inline-flex h-9 w-9 cursor-pointer items-center justify-center rounded-full text-[#7486a3] transition-colors hover:bg-white/70 hover:text-[#2d4263] sm:right-5 sm:top-5"
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="h-[17px] w-[17px]"
            >
              <path d="m7 7 10 10" />
              <path d="m17 7-10 10" />
            </svg>
          </button>
          <div className="relative flex items-start gap-4 pr-9 sm:pr-8">
            <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-[16px] bg-[#2f6df6] text-white shadow-[0_12px_28px_rgba(47,109,246,0.25)]">
              <DkimNoticeIcon />
            </div>
            <div className="min-w-0 pt-0.5">
              <p className="text-[12px] font-semibold tracking-[0.08em] text-[#2f6df6]">
                중요 안내
              </p>
              <h2
                id="mail-service-notice-title"
                className="mt-1.5 text-[22px] font-semibold tracking-[-0.04em] text-[#14213a]"
              >
                새 DKIM 키로 변경해주세요
              </h2>
            </div>
          </div>
        </div>

        <div className="px-6 py-6 sm:px-8">
          <div
            id="mail-service-notice-description"
            className="space-y-3 text-[14px] leading-6 text-[#526784]"
          >
            <p>
              메일 서버 신규 이전으로 기존 DKIM 키를 재발급해드렸습니다. 도메인 연결 페이지에서
              <strong className="font-semibold text-[#223653]"> {domain || "연결된 도메인"}</strong>의 새 DKIM 값을 확인해 DNS 값을 변경한 뒤 연결 상태를 다시 확인해주세요.
            </p>
            <p>
              기존 메일 송수신에는 영향이 없지만, Gmail 등 일부 메일사에서는 DKIM 키가 일치하지 않으면 발신 인증 실패로 메일이 반송될 수 있습니다. 안정적인 발송을 위해 가급적 빠른 변경을 권장드립니다.
            </p>
          </div>

          <div className="mt-7 grid grid-cols-[minmax(0,0.86fr)_minmax(0,1.14fr)] gap-3 border-t border-[#edf2fa] pt-5">
            <button
              type="button"
              onClick={snoozeForSevenDays}
              className="h-11 cursor-pointer rounded-[13px] border border-[#d9e4f5] bg-white px-4 text-[13px] font-semibold text-[#526784] transition-colors hover:border-[#c4d5ee] hover:bg-[#f7faff]"
            >
              7일 동안 보지 않기
            </button>
            <Link
              href="/mail?panel=setup&section=domain"
              onClick={closeForSession}
              className="inline-flex h-11 cursor-pointer items-center justify-center rounded-[13px] bg-[#2f6df6] px-4 text-[13px] font-semibold text-white shadow-[0_10px_24px_rgba(47,109,246,0.2)] transition-colors hover:bg-[#245dcc]"
            >
              도메인 연결하러 가기
            </Link>
          </div>
        </div>
      </section>
    </div>,
    document.body,
  );
}
