"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { BottomToast, type BottomToastNotice } from "@/components/bottom-toast";
import { COMPOSE_EXIT_NOTICE, readExitDrafts, submitExitDraft } from "@/lib/mail-compose-exit-client";

export function MailExitDraftRecovery({ mailbox }: { mailbox: string }) {
  const [notice, setNotice] = useState<BottomToastNotice | null>(null);
  const router = useRouter();
  const pathname = usePathname();
  const search = useSearchParams().toString();
  useEffect(() => {
    if (sessionStorage.getItem("official-mail-exit-draft-notice") === mailbox) {
      sessionStorage.removeItem("official-mail-exit-draft-notice");
      const timer = window.setTimeout(() => setNotice({ tone: "success", message: COMPOSE_EXIT_NOTICE }), 0);
      return () => window.clearTimeout(timer);
    }
  }, [mailbox, pathname, search]);
  useEffect(() => {
    let active = true;
    let running = false;
    const recover = async () => {
      if (running) return;
      running = true;
      try {
        const drafts = await readExitDrafts(mailbox);
        for (const draft of drafts) {
          if (!active) return;
          await submitExitDraft(draft);
          if (active) setNotice({ tone: "success", message: COMPOSE_EXIT_NOTICE });
        }
        if (active && drafts.length) router.refresh();
      } catch {
        // Retain recovery data through logout/offline failures. Never claim
        // that a draft is in the mailbox before the server confirms it.
      } finally {
        running = false;
      }
    };
    const saved = (event: Event) => {
      if ((event as CustomEvent<{ mailbox: string }>).detail?.mailbox !== mailbox) return;
      setNotice({ tone: "success", message: COMPOSE_EXIT_NOTICE });
      router.refresh();
    };
    const error = () => setNotice({ tone: "error", message: "임시메일 저장에 실패했습니다. 연결 상태를 확인한 뒤 다시 이동해주세요." });
    void recover();
    window.addEventListener("online", recover);
    window.addEventListener("official-mail-draft-saved", saved);
    window.addEventListener("official-mail-draft-error", error);
    return () => {
      active = false;
      window.removeEventListener("online", recover);
      window.removeEventListener("official-mail-draft-saved", saved);
      window.removeEventListener("official-mail-draft-error", error);
    };
  }, [mailbox, router]);
  useEffect(() => {
    if (!notice) return;
    const timer = window.setTimeout(() => setNotice(null), 4200);
    return () => window.clearTimeout(timer);
  }, [notice]);
  return notice ? <BottomToast notice={notice} onClose={() => setNotice(null)} /> : null;
}
