import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { Avatar, Badge, Card, EmptyState, PageHeader, StatusBadge, input } from "@/components/ui";
import { dateRange, fmtDateTime, formatMoney } from "@/lib/utils";
import { ASSET_TYPE_LABELS, ORG_ROLE_LABELS, SPEAKER_TYPE_LABELS, SPONSOR_TIER_LABELS } from "@/lib/constants";

export const metadata = { title: "Search" };

export default async function GlobalSearchPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org) return <EmptyState title="No organization" />;
  const org = ctx.org;
  const { q = "" } = await searchParams;
  const query = q.trim();

  const empty = { conferences: [], visitors: [], speakers: [], sponsors: [], venues: [], assets: [], payments: [], team: [] };
  const results = query.length < 2 ? empty : await searchAll(org.id, query, ctx.modules as string[]);
  const totals = Object.values(results).reduce((s, arr) => s + arr.length, 0);

  return (
    <main>
      <PageHeader title="🔍 Global Search" sub={`Search across everything in ${org.name} — conferences, visitors, speakers, sponsors, venues, assets, transactions and team.`} />
      <form action="/dashboard/search" className="max-w-xl">
        <input type="search" name="q" defaultValue={q} autoFocus placeholder="Try a name, email, conference, transaction id…" className={input} />
      </form>

      {query.length >= 2 && (
        <p className="mt-3 text-sm text-zinc-500">{totals} result{totals === 1 ? "" : "s"} for “{query}”</p>
      )}

      <div className="mt-5 space-y-6">
        {results.conferences.length > 0 && (
          <Section title="📅 Conferences">
            {results.conferences.map((c) => (
              <Link key={c.id} href={`/dashboard/c/${c.id}`} className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="flex min-w-0 items-center gap-2.5">
                  <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-xs font-bold text-white" style={{ background: c.primaryColor }}>{c.name[0]}</span>
                  <span className="truncate font-medium text-zinc-200">{c.name}</span>
                  <StatusBadge status={c.status} />
                </span>
                <span className="shrink-0 text-xs text-zinc-500">{dateRange(c.startAt, c.endAt)}</span>
              </Link>
            ))}
          </Section>
        )}

        {results.visitors.length > 0 && (
          <Section title="👥 Visitors & registrations">
            {results.visitors.map((r) => (
              <Link key={r.id} href={`/dashboard/c/${r.conferenceId}/registrations`} className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="min-w-0">
                  <span className="block truncate font-medium text-zinc-200">{r.name} <span className="font-mono text-[11px] text-zinc-500">{r.regCode}</span></span>
                  <span className="block truncate text-xs text-zinc-500">{r.email}{r.organization ? ` · ${r.organization}` : ""} · {r.conference.name}</span>
                </span>
                <span className="flex shrink-0 items-center gap-2"><StatusBadge status={r.status} /><span className="text-xs tabular-nums text-zinc-400">{formatMoney(r.amount)}</span></span>
              </Link>
            ))}
          </Section>
        )}

        {results.speakers.length > 0 && (
          <Section title="🎤 Speakers">
            {results.speakers.map((s) => (
              <Link key={s.id} href={s.conferenceId ? `/dashboard/c/${s.conferenceId}/speakers` : "/dashboard/speakers"} className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="flex min-w-0 items-center gap-2.5">
                  <Avatar name={s.name} src={s.photoUrl} size={7} />
                  <span className="min-w-0">
                    <span className="block truncate font-medium text-zinc-200">{s.name}</span>
                    <span className="block truncate text-xs text-zinc-500">{[s.designation, s.organization].filter(Boolean).join(", ")} · {s.conference?.name ?? "Speaker pool"}</span>
                  </span>
                </span>
                <Badge className="bg-violet-500/10 text-violet-600">{SPEAKER_TYPE_LABELS[s.speakerType] ?? s.speakerType}</Badge>
              </Link>
            ))}
          </Section>
        )}

        {results.sponsors.length > 0 && (
          <Section title="🤝 Sponsors">
            {results.sponsors.map((s) => (
              <Link key={s.id} href={s.conferenceId ? `/dashboard/c/${s.conferenceId}/sponsors` : "/dashboard/sponsors"} className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="truncate font-medium text-zinc-200">{s.name} <span className="text-xs text-zinc-500">· {s.conference?.name ?? "Partner book"}</span></span>
                <Badge className="bg-amber-500/10 text-amber-600">{SPONSOR_TIER_LABELS[s.tier] ?? s.tier}</Badge>
              </Link>
            ))}
          </Section>
        )}

        {results.venues.length > 0 && (
          <Section title="📍 Venues">
            {results.venues.map((v) => (
              <Link key={v.id} href={v.conferenceId ? `/dashboard/c/${v.conferenceId}/venue` : "/dashboard/venues"} className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="truncate font-medium text-zinc-200">🏛️ {v.name}</span>
                <span className="shrink-0 text-xs text-zinc-500">{[v.city, v.conference?.name ?? "Venue database"].filter(Boolean).join(" · ")}</span>
              </Link>
            ))}
          </Section>
        )}

        {results.assets.length > 0 && (
          <Section title="📁 Assets">
            {results.assets.map((a) => (
              <a key={a.id} href={a.url} target="_blank" rel="noreferrer" className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="truncate font-medium text-zinc-200">{a.name}</span>
                <Badge className="bg-indigo-500/10 text-indigo-600">{ASSET_TYPE_LABELS[a.type] ?? a.type}</Badge>
              </a>
            ))}
          </Section>
        )}

        {results.payments.length > 0 && (
          <Section title="💳 Transactions">
            {results.payments.map((p) => (
              <Link key={p.id} href="/dashboard/finances?tab=transactions" className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="min-w-0">
                  <span className="block truncate font-mono text-xs text-zinc-400">{p.txnId ?? p.id}</span>
                  <span className="block truncate text-xs text-zinc-500">{p.registration.name} · {fmtDateTime(p.createdAt)}</span>
                </span>
                <span className="flex shrink-0 items-center gap-2"><StatusBadge status={p.status} /><span className="text-xs tabular-nums text-zinc-400">{formatMoney(p.amount)}</span></span>
              </Link>
            ))}
          </Section>
        )}

        {results.team.length > 0 && (
          <Section title="👨‍💼 Team">
            {results.team.map((m) => (
              <Link key={m.id} href="/dashboard/team" className="flex items-center justify-between gap-3 rounded-xl px-3 py-2.5 transition hover:bg-white/60">
                <span className="flex min-w-0 items-center gap-2.5">
                  <Avatar name={m.user.name} src={m.user.avatarUrl} size={7} />
                  <span className="min-w-0">
                    <span className="block truncate font-medium text-zinc-200">{m.user.name}</span>
                    <span className="block truncate text-xs text-zinc-500">{m.user.email}</span>
                  </span>
                </span>
                <Badge className="bg-sky-500/10 text-sky-600">{ORG_ROLE_LABELS[m.role] ?? m.role}</Badge>
              </Link>
            ))}
          </Section>
        )}

        {query.length >= 2 && totals === 0 && (
          <EmptyState title={`Nothing found for “${query}”`} body="Try a shorter query — search matches names, emails, codes and titles." />
        )}
      </div>
    </main>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div>
      <h3 className="mb-1.5 text-sm font-bold text-zinc-200">{title}</h3>
      <Card className="divide-y divide-zinc-800/30 p-1.5">{children}</Card>
    </div>
  );
}

async function searchAll(orgId: string, q: string, modules: string[]) {
  const TAKE = 8;
  const [conferences, visitors, speakers, sponsors, venues, assets, payments, team] = await Promise.all([
    db.conference.findMany({ where: { orgId, name: { contains: q } }, take: TAKE, select: { id: true, name: true, status: true, startAt: true, endAt: true, primaryColor: true } }),
    modules.includes("visitors")
      ? db.registration.findMany({
          where: { conference: { orgId }, OR: [{ name: { contains: q } }, { email: { contains: q } }, { regCode: { contains: q } }, { organization: { contains: q } }] },
          take: TAKE,
          include: { conference: { select: { name: true } } },
        })
      : [],
    modules.includes("speakers")
      ? db.speaker.findMany({
          where: {
            OR: [{ conference: { orgId } }, { orgId, conferenceId: null }],
            AND: [{ OR: [{ name: { contains: q } }, { organization: { contains: q } }] }],
          },
          take: TAKE,
          include: { conference: { select: { name: true } } },
        })
      : [],
    modules.includes("sponsors")
      ? db.sponsor.findMany({ where: { OR: [{ conference: { orgId } }, { orgId, conferenceId: null }], name: { contains: q } }, take: TAKE, include: { conference: { select: { name: true } } } })
      : [],
    modules.includes("venues")
      ? db.venue.findMany({ where: { AND: [{ OR: [{ conference: { orgId } }, { orgId, conferenceId: null }] }, { OR: [{ name: { contains: q } }, { city: { contains: q } }] }] }, take: TAKE, include: { conference: { select: { name: true } } } })
      : [],
    modules.includes("assets")
      ? db.asset.findMany({ where: { orgId, OR: [{ name: { contains: q } }, { tags: { contains: q } }] }, take: TAKE })
      : [],
    modules.includes("finances")
      ? db.payment.findMany({
          where: { registration: { conference: { orgId } }, OR: [{ txnId: { contains: q } }, { registration: { name: { contains: q } } }] },
          take: TAKE,
          include: { registration: { select: { name: true } } },
        })
      : [],
    modules.includes("team")
      ? db.orgMember.findMany({
          where: { orgId, user: { OR: [{ name: { contains: q } }, { email: { contains: q } }] } },
          take: TAKE,
          include: { user: { select: { name: true, email: true, avatarUrl: true } } },
        })
      : [],
  ]);
  return { conferences, visitors, speakers, sponsors, venues, assets, payments, team };
}
