import Link from 'next/link';
import { accountApi } from '@/lib/session';
import { deleteSearch, setSearchAlert } from '../../actions';
import { fmt, Notice, PageTitle } from '@/components/AccountUi';
import { BellIcon } from '@/components/Icons';

type S = { id: number; name: string; query: Record<string, string | number | boolean>; alert: boolean; lastAlertedAt: string | null; createdAt: string; known: number };

/** Saved query → /search/ URL (the search page's own parameter names) */
function searchHref(q: S['query']) {
  const p = new URLSearchParams();
  for (const [k, v] of Object.entries(q)) {
    if (v === undefined || v === '' || v === false) continue;
    p.set(k === 'verifiedOnly' ? 'verified' : k, String(v));
  }
  return `/search/?${p}`;
}

export default async function Searches({ searchParams }: { searchParams: Promise<{ ok?: string; err?: string }> }) {
  const sp = await searchParams;
  const rows = await accountApi<S[]>('/client/searches', { next: '/account/searches/' });
  return (
    <>
      <PageTitle title="Saved searches" intro="With alerts on, we email you once a day at most when new lawyers match — nothing else." />
      <Notice ok={sp.ok} err={sp.err} />
      {rows.length ? (
        <ul className="card divide-y divide-rule">
          {rows.map((s) => (
            <li key={s.id} className="flex flex-wrap items-center justify-between gap-3 p-4 text-sm">
              <div>
                <Link href={searchHref(s.query)} className="link font-medium">
                  {s.name}
                </Link>
                <p className="text-xs text-muted">
                  Saved {fmt(s.createdAt)}
                  {s.lastAlertedAt && ` · last alert ${fmt(s.lastAlertedAt)}`}
                </p>
              </div>
              <div className="flex items-center gap-2">
                <form action={setSearchAlert}>
                  <input type="hidden" name="id" value={s.id} />
                  <input type="hidden" name="alert" value={s.alert ? 'false' : 'true'} />
                  <button className={`btn btn-sm ${s.alert ? 'btn-primary' : 'btn-quiet'}`}>
                    <BellIcon className="h-4 w-4" /> {s.alert ? 'Alerts on' : 'Alerts off'}
                  </button>
                </form>
                <form action={deleteSearch}>
                  <input type="hidden" name="id" value={s.id} />
                  <button className="btn btn-ghost btn-sm">Delete</button>
                </form>
              </div>
            </li>
          ))}
        </ul>
      ) : (
        <p className="card p-5 text-sm text-muted">
          No saved searches. Run a{' '}
          <Link href="/search/" className="link">
            search
          </Link>{' '}
          and choose “Save this search”.
        </p>
      )}
    </>
  );
}
