'use client';

import { useEffect, useState } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { AlertIcon, CheckCircleIcon, XIcon } from './Icons';

/** Action result banner. Drops ?ok=/?err= from the URL so a refresh or shared link doesn't repeat it. */
export function FlashBanner({ tone, message }: { tone: 'success' | 'error'; message: string }) {
  const [shown, setShown] = useState(true);
  const path = usePathname();
  const params = useSearchParams();

  useEffect(() => {
    setShown(true);
    if (!params.has('ok') && !params.has('err')) return;
    const next = new URLSearchParams(params);
    next.delete('ok');
    next.delete('err');
    const qs = next.toString();
    // history.replaceState rewrites the URL without a server round trip (router.replace would
    // re-render the page without ?ok= and unmount this banner straight away)
    window.history.replaceState(null, '', qs ? `${path}?${qs}` : path);
    // Success messages fade on their own; errors stay until dismissed
    if (tone === 'success') {
      const t = setTimeout(() => setShown(false), 6000);
      return () => clearTimeout(t);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [message]);

  if (!shown) return null;
  const err = tone === 'error';
  return (
    <div
      role={err ? 'alert' : 'status'}
      className={`fade-up mb-5 flex items-start gap-3 rounded-lg border px-4 py-3 text-sm ${err ? 'border-danger/40 bg-danger-soft text-danger' : 'border-ledger/30 bg-ledger-soft text-ledger'}`}
    >
      {err ? <AlertIcon className="mt-0.5 h-4 w-4" /> : <CheckCircleIcon className="mt-0.5 h-4 w-4" />}
      <span className="flex-1 font-medium">{message}</span>
      <button type="button" onClick={() => setShown(false)} aria-label="Dismiss" className="-m-1 grid h-6 w-6 place-items-center rounded transition-colors hover:bg-black/5">
        <XIcon className="h-3.5 w-3.5" />
      </button>
    </div>
  );
}
