"use client";

import { useEffect, useState } from "react";
import type { BottomToastNotice } from "@/components/bottom-toast";

export function DismissibleBottomToast({
  notice,
  autoHideMs = 4200,
  clearSearchParams = [],
}: {
  notice: BottomToastNotice | null;
  autoHideMs?: number;
  clearSearchParams?: string[];
}) {
  const noticeKey = notice ? `${notice.tone}:${notice.message}` : "";
  const [dismissedNoticeKey, setDismissedNoticeKey] = useState("");

  useEffect(() => {
    if (!noticeKey || clearSearchParams.length === 0 || typeof window === "undefined") {
      return;
    }

    const url = new URL(window.location.href);
    let changed = false;

    for (const key of clearSearchParams) {
      if (url.searchParams.has(key)) {
        url.searchParams.delete(key);
        changed = true;
      }
    }

    if (!changed) {
      return;
    }

    const nextUrl = `${url.pathname}${url.search}${url.hash}`;
    window.history.replaceState(window.history.state, "", nextUrl);
  }, [clearSearchParams, noticeKey]);

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

    const timer = window.setTimeout(() => {
      setDismissedNoticeKey(noticeKey);
    }, autoHideMs);

    return () => window.clearTimeout(timer);
  }, [autoHideMs, noticeKey]);

  if (!notice || dismissedNoticeKey === noticeKey) {
    return null;
  }

  const isError = notice.tone === "error";
  const isWarning = notice.tone === "warning";

  return (
    <p
      role={isError ? "alert" : "status"}
      aria-live={isError ? "assertive" : "polite"}
      className={`mb-4 text-[13px] font-medium leading-5 ${
        isError ? "text-[#bd4052]" : isWarning ? "text-[#9a651b]" : "text-[#2f6df6]"
      }`}
    >
      {notice.message}
    </p>
  );
}
