import Link from "next/link";
import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Avatar, Badge, Card, EmptyState, PageHeader, btn, input, Field } from "@/components/ui";
import { parseJSON } from "@/lib/utils";
import { SPEAKER_TYPES, SPEAKER_TYPE_LABELS } from "@/lib/constants";
import { createSpeaker, deleteSpeaker, importSpeakerFromLinkedIn, updateSpeaker } from "../actions";

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

type Socials = { linkedin?: string; x?: string; website?: string };

function SpeakerFormFields({ speaker }: { speaker?: { name: string; email: string | null; designation: string | null; organization: string | null; bio: string | null; featured: boolean; socialLinks: string | null; photoUrl: string | null; speakerType: string } }) {
  const socials = parseJSON<Socials>(speaker?.socialLinks, {});
  return (
    <>
      <div className="grid grid-cols-2 gap-3">
        <Field name="name" title="Name *"><input name="name" required defaultValue={speaker?.name ?? ""} className={input} /></Field>
        <Field name="email" title="Email"><input name="email" type="email" defaultValue={speaker?.email ?? ""} className={input} /></Field>
        <Field name="designation" title="Designation"><input name="designation" defaultValue={speaker?.designation ?? ""} className={input} /></Field>
        <Field name="organization" title="Organization"><input name="organization" defaultValue={speaker?.organization ?? ""} className={input} /></Field>
        <Field name="speakerType" title="Speaker type">
          <select name="speakerType" className={input} defaultValue={speaker?.speakerType ?? "SPEAKER"}>
            {SPEAKER_TYPES.map((t) => <option key={t} value={t}>{SPEAKER_TYPE_LABELS[t]}</option>)}
          </select>
        </Field>
      </div>
      <Field name="linkedin" title="LinkedIn URL">
        <input name="linkedin" defaultValue={socials.linkedin ?? ""} className={input} placeholder="https://linkedin.com/in/…" />
      </Field>
      <div className="grid grid-cols-2 gap-3">
        <Field name="xUrl" title="X (Twitter) URL"><input name="xUrl" defaultValue={socials.x ?? ""} className={input} placeholder="https://x.com/…" /></Field>
        <Field name="otherUrl" title="Other URL"><input name="otherUrl" defaultValue={socials.website ?? ""} className={input} placeholder="https://…" /></Field>
      </div>
      <Field name="photo" title={speaker?.photoUrl ? "Replace photo (≤5 MB)" : "Photo (≤5 MB)"}>
        <div className="flex items-center gap-3">
          {speaker?.photoUrl && <Avatar name={speaker.name} src={speaker.photoUrl} size={10} />}
          <input
            name="photo"
            type="file"
            accept="image/*"
            className="w-full cursor-pointer rounded-xl border border-white/80 bg-white/70 px-3 py-2 text-sm text-zinc-400 shadow-sm backdrop-blur file:mr-3 file:cursor-pointer file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-3 file:py-1 file:text-xs file:font-semibold file:text-indigo-600"
          />
        </div>
      </Field>
      <Field name="bio" title="Bio"><textarea name="bio" rows={3} defaultValue={speaker?.bio ?? ""} className={input} /></Field>
      <label className="flex items-center gap-2 text-sm text-zinc-400">
        <input type="checkbox" name="featured" defaultChecked={speaker?.featured} className="accent-indigo-500" /> Featured speaker (shown on homepage)
      </label>
    </>
  );
}

export default async function SpeakersAdminPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ error?: string; imported?: string; partial?: string; edit?: string }>;
}) {
  const { id } = await params;
  const { error, imported, partial, edit } = await searchParams;
  await requireConfAccess(id, "speakers.manage");
  const speakers = await db.speaker.findMany({
    where: { conferenceId: id },
    orderBy: [{ featured: "desc" }, { name: "asc" }],
    include: { sessions: { include: { session: true } } },
  });
  const editing = edit ? speakers.find((s) => s.id === edit) : undefined;

  return (
    <main>
      <PageHeader title="Speakers" sub={`${speakers.length} speakers — profile pages are generated automatically on the public site.`} />
      {error && <div className="mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600">{error}</div>}
      {imported && (
        <div className="mb-4 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-600">
          ✓ Imported <strong>{imported}</strong> from LinkedIn{partial ? " — LinkedIn limited what we could read, so we filled in what the URL tells us. Review and complete the profile." : ". Review the details below."}
        </div>
      )}

      {/* USP: LinkedIn import */}
      <div className="fx-shine mb-6 rounded-2xl bg-gradient-to-r from-[#0a66c2] to-indigo-600 p-[1.5px] shadow-lg shadow-indigo-500/20">
        <div className="rounded-2xl bg-white/85 p-5 backdrop-blur-xl">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div>
              <h2 className="text-sm font-bold text-zinc-100">⚡ Add speaker from LinkedIn</h2>
              <p className="mt-0.5 text-xs text-zinc-500">
                Paste a profile URL — we pull the name, headline, company, bio and photo automatically, then you review.
              </p>
            </div>
            <form action={importSpeakerFromLinkedIn.bind(null, id)} className="flex min-w-0 flex-1 justify-end gap-2 sm:min-w-[24rem]">
              <input
                name="linkedinUrl"
                required
                className={`${input} max-w-md`}
                placeholder="https://www.linkedin.com/in/username"
              />
              <button className="shrink-0 rounded-xl bg-[#0a66c2] px-4 py-2 text-sm font-semibold text-white shadow-md transition hover:brightness-110">
                Import
              </button>
            </form>
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="space-y-3 lg:col-span-2">
          {speakers.length === 0 && <EmptyState title="No speakers yet" body="Import from LinkedIn above, or add one manually — then assign them to sessions in the agenda builder." />}
          {speakers.map((s) => {
            const socials = parseJSON<Socials>(s.socialLinks, {});
            return (
              <Card key={s.id} className="flex items-start justify-between gap-4 p-4">
                <div className="flex min-w-0 gap-3">
                  <Avatar name={s.name} src={s.photoUrl} size={12} />
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2 font-semibold text-zinc-100">
                      {s.name} {s.featured && <span title="Featured" className="text-xs">⭐</span>}
                      {s.speakerType !== "SPEAKER" && (
                        <Badge className="bg-violet-500/10 text-violet-600">{SPEAKER_TYPE_LABELS[s.speakerType] ?? s.speakerType}</Badge>
                      )}
                    </div>
                    <div className="text-xs text-zinc-500">
                      {[s.designation, s.organization].filter(Boolean).join(", ")}{s.email ? ` · ${s.email}` : ""}
                    </div>
                    <div className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px] font-semibold">
                      {socials.linkedin && <a href={socials.linkedin} target="_blank" rel="noreferrer" className="rounded-md bg-[#0a66c2]/10 px-1.5 py-0.5 text-[#0a66c2] hover:underline">in LinkedIn</a>}
                      {socials.x && <a href={socials.x} target="_blank" rel="noreferrer" className="rounded-md bg-zinc-800/80 px-1.5 py-0.5 text-zinc-100 hover:underline">𝕏</a>}
                      {socials.website && <a href={socials.website} target="_blank" rel="noreferrer" className="rounded-md bg-indigo-500/10 px-1.5 py-0.5 text-indigo-600 hover:underline">🔗 Web</a>}
                    </div>
                    {s.sessions.length > 0 && (
                      <div className="mt-1.5 flex flex-wrap gap-1.5">
                        {s.sessions.map(({ session }) => (
                          <span key={session.id} className="rounded-md bg-zinc-800 px-2 py-0.5 text-[11px] text-zinc-400">{session.title}</span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
                <div className="flex shrink-0 gap-1.5">
                  <Link href={`/dashboard/c/${id}/speakers?edit=${s.id}`} className={btn.smSecondary}>✎ Edit</Link>
                  <form action={deleteSpeaker.bind(null, id, s.id)}>
                    <button className="rounded-md px-2 py-1.5 text-xs text-zinc-600 transition hover:bg-red-500/10 hover:text-red-600" title="Remove speaker">✕</button>
                  </form>
                </div>
              </Card>
            );
          })}
        </div>

        <Card className="h-fit p-5">
          <h2 className="text-sm font-semibold text-zinc-200">Add speaker manually</h2>
          <form action={createSpeaker.bind(null, id)} className="mt-4 space-y-3">
            <SpeakerFormFields />
            <button className={`${btn.primary} w-full`}>Add speaker</button>
          </form>
        </Card>
      </div>

      {/* Edit modal */}
      {editing && (
        <div className="fixed inset-0 z-50 overflow-y-auto bg-zinc-50/50 p-4 backdrop-blur-sm" role="dialog" aria-modal="true">
          <div className="fx-pop-in mx-auto my-8 max-w-xl">
            <Card className="!bg-white/90 p-6 shadow-2xl">
              <div className="mb-4 flex items-center justify-between">
                <h2 className="text-base font-bold text-zinc-100">Edit speaker</h2>
                <Link href={`/dashboard/c/${id}/speakers`} className="rounded-lg px-2 py-1 text-sm text-zinc-500 transition hover:bg-zinc-800/50" aria-label="Close">✕</Link>
              </div>
              <form action={updateSpeaker.bind(null, id, editing.id)} className="space-y-3">
                <SpeakerFormFields speaker={editing} />
                <div className="flex justify-end gap-2 border-t border-zinc-800/50 pt-4">
                  <Link href={`/dashboard/c/${id}/speakers`} className={btn.secondary}>Cancel</Link>
                  <button className={btn.primary}>Save changes</button>
                </div>
              </form>
            </Card>
          </div>
        </div>
      )}
    </main>
  );
}
