import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule, canOrgMutate } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { Avatar, Badge, btn, Card, EmptyState, Field, PageHeader, StatCard, input } from "@/components/ui";
import { parseJSON } from "@/lib/utils";
import { SPEAKER_TYPES, SPEAKER_TYPE_LABELS } from "@/lib/constants";
import {
  createOrgSpeaker, deleteOrgSpeaker, importOrgSpeakerFromLinkedIn, reuseSpeakerAction, updateOrgSpeaker,
} from "./actions";

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

export default async function SpeakersDirectoryPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; saved?: string; error?: string; add?: string; edit?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "speakers")) {
    return <EmptyState title="No access" body="Speaker management is not part of your role." />;
  }
  const org = ctx.org;
  const canMutate = canOrgMutate(ctx.role);
  const { q = "", saved, error, add, edit } = await searchParams;

  const [speakers, conferences] = await Promise.all([
    db.speaker.findMany({
      where: {
        OR: [{ conference: { orgId: org.id } }, { orgId: org.id, conferenceId: null }],
        ...(q ? { AND: [{ OR: [{ name: { contains: q } }, { organization: { contains: q } }, { designation: { contains: q } }] }] } : {}),
      },
      include: {
        conference: { select: { id: true, name: true } },
        _count: { select: { sessions: true } },
      },
      orderBy: { name: "asc" },
    }),
    db.conference.findMany({ where: { orgId: org.id, status: { notIn: ["ARCHIVED"] } }, orderBy: { startAt: "desc" }, select: { id: true, name: true } }),
  ]);

  // Centralized directory: one profile per person. A profile can be backed by a
  // pool entry (reusable, editable here), conference copies, or both.
  type Grouped = {
    key: string; name: string; email: string | null; photoUrl: string | null;
    organization: string | null; designation: string | null; bio: string | null;
    speakerType: string; socialLinks: string | null; latestId: string;
    poolId: string | null;
    conferences: { id: string; name: string; speakerId: string }[]; sessions: number;
  };
  const byKey = new Map<string, Grouped>();
  for (const s of speakers) {
    const key = (s.email?.toLowerCase() || s.name.toLowerCase()).trim();
    let g = byKey.get(key);
    if (!g) {
      g = {
        key, name: s.name, email: s.email, photoUrl: s.photoUrl,
        organization: s.organization, designation: s.designation, bio: s.bio,
        speakerType: s.speakerType, socialLinks: s.socialLinks, latestId: s.id,
        poolId: null, conferences: [], sessions: 0,
      };
      byKey.set(key, g);
    }
    if (s.conference) {
      g.conferences.push({ id: s.conference.id, name: s.conference.name, speakerId: s.id });
      g.sessions += s._count.sessions;
    } else {
      g.poolId = s.id;
      // the pool entry is the canonical profile — prefer its details
      g.latestId = s.id;
      g.name = s.name; g.email = s.email ?? g.email; g.photoUrl = s.photoUrl ?? g.photoUrl;
      g.organization = s.organization ?? g.organization; g.designation = s.designation ?? g.designation;
      g.bio = s.bio ?? g.bio; g.speakerType = s.speakerType; g.socialLinks = s.socialLinks ?? g.socialLinks;
    }
    if (!g.photoUrl && s.photoUrl) g.photoUrl = s.photoUrl;
    if (!g.bio && s.bio) g.bio = s.bio;
  }
  const directory = [...byKey.values()];
  const multiConf = directory.filter((d) => d.conferences.length > 1).length;
  const poolCount = directory.filter((d) => d.poolId).length;
  const showAddForm = add === "1" || Boolean(error);

  const speakerForm = (defaults?: Grouped) => {
    const social = parseJSON<Record<string, string>>(defaults?.socialLinks ?? null, {});
    return (
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <Field name="name" title="Name *"><input name="name" required defaultValue={defaults?.name ?? ""} className={input} /></Field>
        <Field name="email" title="Email"><input name="email" type="email" defaultValue={defaults?.email ?? ""} className={input} /></Field>
        <Field name="speakerType" title="Speaker type">
          <select name="speakerType" defaultValue={defaults?.speakerType ?? "SPEAKER"} className={input}>
            {SPEAKER_TYPES.map((t) => <option key={t} value={t}>{SPEAKER_TYPE_LABELS[t]}</option>)}
          </select>
        </Field>
        <Field name="designation" title="Designation"><input name="designation" defaultValue={defaults?.designation ?? ""} placeholder="CTO, Professor…" className={input} /></Field>
        <Field name="organization" title="Organization"><input name="organization" defaultValue={defaults?.organization ?? ""} className={input} /></Field>
        <Field name="photo" title={defaults ? "Replace photo" : "Photo"}>
          <input name="photo" type="file" accept="image/*" className={`${input} file:mr-2 file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-2.5 file:py-1 file:text-xs file:font-semibold file:text-indigo-600`} />
        </Field>
        <div className="sm:col-span-2 lg:col-span-3">
          <Field name="bio" title="Biography"><textarea name="bio" rows={2} defaultValue={defaults?.bio ?? ""} className={input} /></Field>
        </div>
        <Field name="linkedin" title="LinkedIn URL"><input name="linkedin" defaultValue={social.linkedin ?? ""} className={input} /></Field>
        <Field name="twitter" title="X / Twitter URL"><input name="twitter" defaultValue={social.twitter ?? ""} className={input} /></Field>
        <Field name="website" title="Website"><input name="website" defaultValue={social.website ?? ""} className={input} /></Field>
      </div>
    );
  };

  return (
    <main>
      <PageHeader
        title="🎤 Speakers"
        sub={`Centralized speaker database for ${org.name} — add speakers once, call them into any conference later.`}
        action={canMutate ? (
          <Link href={showAddForm ? "/dashboard/speakers" : "/dashboard/speakers?add=1"} className={btn.primary}>
            {showAddForm ? "Close" : "+ Add Speaker"}
          </Link>
        ) : undefined}
      />
      {saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ {saved}</p>}
      {error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{error}</p>}

      {canMutate && showAddForm && (
        <div className="mb-6 space-y-4">
          <Card className="p-5">
            <h3 className="text-sm font-bold text-zinc-100">Add speaker to your database</h3>
            <p className="mb-4 text-xs text-zinc-500">Saved to the organization's speaker pool — assign to conferences whenever you need.</p>
            <form action={createOrgSpeaker}>
              {speakerForm()}
              <button className={`${btn.primary} mt-4`}>Save speaker</button>
            </form>
          </Card>
          <Card className="border-sky-200/80 bg-sky-500/5 p-5">
            <h3 className="text-sm font-bold text-zinc-100">⚡ Add from LinkedIn</h3>
            <p className="mb-3 text-xs text-zinc-500">Paste a profile URL — name, designation, organization and photo are imported automatically.</p>
            <form action={importOrgSpeakerFromLinkedIn} className="flex flex-wrap gap-2">
              <input name="linkedinUrl" required placeholder="https://www.linkedin.com/in/…" className={`${input} max-w-md`} aria-label="LinkedIn profile URL" />
              <button className={btn.secondary}>Import profile</button>
            </form>
          </Card>
        </div>
      )}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Unique Speakers" value={directory.length} />
        <StatCard label="In Speaker Pool" value={poolCount} sub="reusable profiles" accent="text-sky-600" />
        <StatCard label="Repeat Speakers" value={multiConf} accent="text-indigo-600" />
        <StatCard label="Sessions Assigned" value={directory.reduce((s, d) => s + d.sessions, 0)} />
      </div>

      <form className="mt-5" action="/dashboard/speakers">
        <input type="search" name="q" defaultValue={q} placeholder="Search speakers by name, organization, designation… 🔍" className={`${input} max-w-md`} />
      </form>

      {directory.length === 0 ? (
        <div className="mt-5">
          <EmptyState
            title={q ? `No speakers matching “${q}”` : "No speakers yet"}
            body="Add speakers here to build a reusable database, or add them inside a conference — they appear here either way."
            action={canMutate && !q ? <Link href="/dashboard/speakers?add=1" className={btn.primary}>+ Add your first speaker</Link> : undefined}
          />
        </div>
      ) : (
        <div className="mt-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {directory.map((d) => {
            const social = parseJSON<Record<string, string>>(d.socialLinks, {});
            const editing = edit === d.poolId && canMutate;
            return (
              <Card key={d.key} className={`fx-lift p-5 ${editing ? "sm:col-span-2 xl:col-span-3" : ""}`}>
                <div className="flex items-start gap-3.5">
                  <Avatar name={d.name} src={d.photoUrl} size={12} />
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="font-bold text-zinc-100">{d.name}</span>
                      {d.speakerType !== "SPEAKER" && (
                        <Badge className="bg-violet-500/10 text-violet-600">{SPEAKER_TYPE_LABELS[d.speakerType] ?? d.speakerType}</Badge>
                      )}
                      {d.poolId && <Badge className="bg-sky-500/10 text-sky-600">📚 In pool</Badge>}
                    </div>
                    <div className="mt-0.5 text-xs text-zinc-500">
                      {[d.designation, d.organization].filter(Boolean).join(", ") || "—"}
                    </div>
                    {d.email && <div className="mt-0.5 truncate text-[11px] text-zinc-600">{d.email}</div>}
                  </div>
                  {d.poolId && canMutate && !editing && (
                    <Link href={`/dashboard/speakers?edit=${d.poolId}`} className={btn.smSecondary}>✏️ Edit</Link>
                  )}
                </div>

                {editing ? (
                  <div className="mt-4 border-t border-zinc-800/50 pt-4">
                    <form action={updateOrgSpeaker.bind(null, d.poolId!)}>
                      {speakerForm(d)}
                      <div className="mt-4 flex flex-wrap items-center gap-2">
                        <button className={btn.primary}>Save changes</button>
                        <Link href="/dashboard/speakers" className={btn.secondary}>Cancel</Link>
                      </div>
                    </form>
                    <form action={deleteOrgSpeaker.bind(null, d.poolId!)} className="mt-2">
                      <button className="text-xs text-red-500 hover:underline">🗑 Remove from speaker database (conference copies stay)</button>
                    </form>
                  </div>
                ) : (
                  <>
                    {d.bio && <p className="mt-3 line-clamp-2 text-xs leading-relaxed text-zinc-500">{d.bio}</p>}
                    <div className="mt-3 flex flex-wrap items-center gap-1.5">
                      {Object.entries(social).filter(([, v]) => v).slice(0, 3).map(([k, v]) => (
                        <a key={k} href={v} target="_blank" rel="noreferrer" className="rounded-md bg-white/60 px-2 py-0.5 text-[10px] font-semibold uppercase text-zinc-500 hover:text-indigo-600">{k}</a>
                      ))}
                      <span className="ml-auto text-[11px] text-zinc-500">{d.sessions} session{d.sessions === 1 ? "" : "s"}</span>
                    </div>
                    <div className="mt-3 border-t border-zinc-800/50 pt-3">
                      <div className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">Conferences</div>
                      <div className="mt-1.5 flex flex-wrap gap-1.5">
                        {d.conferences.length === 0 && (
                          <span className="text-[11px] text-zinc-500">Not assigned yet — call them into a conference below.</span>
                        )}
                        {d.conferences.map((c) => (
                          <Link key={c.speakerId} href={`/dashboard/c/${c.id}/speakers`} className="max-w-full truncate rounded-full border border-white/70 bg-white/50 px-2 py-0.5 text-[11px] text-zinc-400 transition hover:text-indigo-600">
                            {c.name}
                          </Link>
                        ))}
                      </div>
                      {canMutate && conferences.filter((c) => !d.conferences.some((x) => x.id === c.id)).length > 0 && (
                        <form action={reuseSpeakerAction.bind(null, d.latestId)} className="mt-2.5 flex gap-1.5">
                          <select name="targetConferenceId" required className={`${input} !py-1.5 text-xs`} aria-label="Add to conference">
                            <option value="">Add to conference…</option>
                            {conferences.filter((c) => !d.conferences.some((x) => x.id === c.id)).map((c) => (
                              <option key={c.id} value={c.id}>{c.name}</option>
                            ))}
                          </select>
                          <button className={btn.sm}>Add</button>
                        </form>
                      )}
                    </div>
                  </>
                )}
              </Card>
            );
          })}
        </div>
      )}
    </main>
  );
}
