import { markNoticeRead } from '../actions';
import Link from 'next/link';
import { accountApi } from '@/lib/session';
import { LawyerListItem } from '@/components/LawyerItems';
import { ResendVerification } from '@/components/AccountForms';
import { fmt, Notice, PageTitle, StatusPill } from '@/components/AccountUi';
import { AlertIcon, ArrowRightIcon, StarIcon } from '@/components/Icons';
import type { LawyerCard } from '@/lib/types';

type Overview = {
  emailVerified: boolean;
  counts: { enquiries: number; open_enquiries: number; saved_lawyers: number; saved_firms: number; saved_searches: number };
  recentEnquiries: { reference: string; status: string; createdAt: string; practiceArea: string | null; city: string | null; lawyers: { name: string; status: string }[] }[];
  savedLawyers: LawyerCard[];
};
type Reviews = { items: { id: number; rating: number; lawyer: string; slug: string; published: boolean; date: string }[]; note?: string };

export default async function AccountHome({ searchParams }: { searchParams: Promise<{ ok?: string; err?: string }> }) {
  const sp = await searchParams;
  const [d, reviews, notifications] = await Promise.all([accountApi<Overview>('/client/overview'), accountApi<Reviews>('/client/reviews'), accountApi<{ items: { id: number; title: string; body: string | null; readAt: string | null }[] }>('/me/notifications')]);
  const c = d.counts;
  return (
    <>
      <PageTitle title="Your account" />
      <Notice ok={sp.ok} err={sp.err} />
      {!d.emailVerified && (
        <div className="mb-6 flex flex-wrap items-center gap-3 rounded-lg border border-brass/40 bg-brass-soft px-4 py-3 text-sm text-ink-2">
          <AlertIcon className="h-4 w-4 text-brass" />
          <span className="flex-1">Confirm your email to see enquiries you sent and to turn on alerts.</span>
          <ResendVerification />
        </div>
      )}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        {[
          ['Enquiries', c.enquiries, `${c.open_enquiries} open`, '/account/enquiries/'],
          ['Saved lawyers', c.saved_lawyers, '', '/account/saved/'],
          ['Saved firms', c.saved_firms, '', '/account/saved/'],
          ['Saved searches', c.saved_searches, '', '/account/searches/'],
        ].map(([label, value, hint, href]) => (
          <Link key={String(label)} href={String(href)} className="card p-4 transition-shadow hover:shadow-md">
            <p className="text-xs font-medium text-muted">{label}</p>
            <p className="num mt-1 font-serif text-2xl font-semibold">{value}</p>
            {hint && <p className="text-xs text-muted">{hint}</p>}
          </Link>
        ))}
      </div>

      <section className="mt-8">
        <h2 className="flex items-center justify-between font-serif text-xl font-semibold">
          Recent enquiries
          <Link href="/account/enquiries/" className="link text-sm font-normal">
            All enquiries
          </Link>
        </h2>
        {d.recentEnquiries.length ? (
          <ul className="card mt-3 divide-y divide-rule">
            {d.recentEnquiries.map((e) => (
              <li key={e.reference} className="flex flex-wrap items-center justify-between gap-2 p-4 text-sm">
                <span>
                  <strong>{e.practiceArea ?? 'Direct enquiry'}</strong>
                  {e.city && <span className="text-muted"> · {e.city}</span>}
                  <span className="text-muted"> · {fmt(e.createdAt)}</span>
                  <span className="block text-xs text-muted">{e.lawyers.filter((l) => l.status === 'accepted').map((l) => l.name).join(', ') || `${e.lawyers.length} lawyer${e.lawyers.length === 1 ? '' : 's'} contacted`}</span>
                </span>
                <StatusPill value={e.status} />
              </li>
            ))}
          </ul>
        ) : (
          <p className="card mt-3 p-5 text-sm text-muted">
            {d.emailVerified ? 'No enquiries yet.' : 'Enquiries appear here once your email is confirmed.'}{' '}
            <Link href="/search/" className="link">
              Find a lawyer
            </Link>
          </p>
        )}
      </section>

      <section className="mt-8">
        <h2 className="flex items-center justify-between font-serif text-xl font-semibold">
          Saved lawyers
          <Link href="/account/saved/" className="link text-sm font-normal">
            All saved
          </Link>
        </h2>
        {d.savedLawyers.length ? (
          <ul className="mt-2">
            {d.savedLawyers.map((l) => (
              <LawyerListItem key={l.id} l={l} />
            ))}
          </ul>
        ) : (
          <p className="card mt-3 p-5 text-sm text-muted">Use the ♥ Save button on a lawyer’s profile to build a shortlist.</p>
        )}
      </section>

      {reviews.items.length > 0 && (
        <section className="mt-8">
          <h2 className="font-serif text-xl font-semibold">Reviews you wrote</h2>
          <ul className="card mt-3 divide-y divide-rule text-sm">
            {reviews.items.map((r) => (
              <li key={r.id} className="flex items-center justify-between gap-2 p-4">
                <Link href={`/lawyers/${r.slug}/`} className="link inline-flex items-center gap-1">
                  {r.lawyer} <ArrowRightIcon className="h-3 w-3" />
                </Link>
                <span className="flex items-center gap-2 text-xs text-muted">
                  <StarIcon className="h-3.5 w-3.5 text-brass" /> {r.rating.toFixed(1)} · {r.published ? 'Published' : 'Awaiting moderation'} · {fmt(r.date)}
                </span>
              </li>
            ))}
          </ul>
        </section>
      )}
      <section className="card mt-6 p-6">
        <h2 className="font-serif text-lg font-semibold">Notifications</h2>
        {notifications.items.length ? <ul className="mt-3 divide-y divide-rule">{notifications.items.slice(0, 10).map((notice) => <li key={notice.id} className="py-3 text-sm">
          <p className="font-semibold">{notice.title}</p>{notice.body && <p className="mt-1 text-muted">{notice.body}</p>}
          {!notice.readAt && <form action={markNoticeRead} className="mt-2"><input type="hidden" name="id" value={notice.id} /><button className="btn btn-quiet btn-sm">Mark read</button></form>}
        </li>)}</ul> : <p className="mt-2 text-sm text-muted">No notifications yet.</p>}
      </section>
    </>
  );
}
