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 { fmtDateTime, parseJSON } from "@/lib/utils";
import { VOLUNTEER_AREAS } from "@/lib/constants";
import { createVolunteer, removeVolunteer, updateVolunteer } from "../actions";

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

function VolunteerFormFields({ volunteer }: { volunteer?: { name: string; email: string; phone: string | null; department: string | null; linkedin: string | null; photoUrl: string | null; areas: string } }) {
  const assigned = new Set(parseJSON<string[]>(volunteer?.areas, []));
  return (
    <>
      <div className="grid grid-cols-2 gap-3">
        <Field name="name" title="Name *"><input name="name" required defaultValue={volunteer?.name ?? ""} className={input} /></Field>
        <Field name="email" title={volunteer ? "Email (login — fixed)" : "Email * (becomes their login)"}>
          <input name="email" type="email" required={!volunteer} defaultValue={volunteer?.email ?? ""} disabled={!!volunteer} className={`${input} disabled:opacity-60`} />
        </Field>
        <Field name="phone" title="Phone"><input name="phone" defaultValue={volunteer?.phone ?? ""} className={input} placeholder="+91 98xxxxxx" /></Field>
        <Field name="department" title="Department / class / section"><input name="department" defaultValue={volunteer?.department ?? ""} className={input} placeholder="CSE 3rd yr · Sec B" /></Field>
      </div>
      <Field name="linkedin" title="LinkedIn profile"><input name="linkedin" defaultValue={volunteer?.linkedin ?? ""} className={input} placeholder="https://linkedin.com/in/…" /></Field>
      <Field name="photo" title={volunteer?.photoUrl ? "Replace photo (≤5 MB)" : "Photo (≤5 MB)"}>
        <div className="flex items-center gap-3">
          {volunteer?.photoUrl && <Avatar name={volunteer.name} src={volunteer.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>
      <div>
        <span className="mb-1.5 block text-xs font-semibold text-zinc-400">Assigned areas — they can only manage what's ticked</span>
        <div className="grid grid-cols-2 gap-1.5">
          {VOLUNTEER_AREAS.map((a) => (
            <label key={a.key} className="flex cursor-pointer items-center gap-2 rounded-lg border border-white/80 bg-white/60 px-2.5 py-1.5 text-sm text-zinc-300 backdrop-blur transition has-checked:border-indigo-400 has-checked:bg-indigo-500/10">
              <input type="checkbox" name="areas" value={a.key} defaultChecked={assigned.has(a.key)} className="accent-indigo-500" />
              {a.label}
            </label>
          ))}
        </div>
      </div>
    </>
  );
}

export default async function VolunteersPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ error?: string; added?: string; temp?: string; edit?: string }>;
}) {
  const { id } = await params;
  const { error, added, temp, edit } = await searchParams;
  await requireConfAccess(id, "volunteers.manage");

  const volunteers = await db.volunteer.findMany({ where: { conferenceId: id }, orderBy: { name: "asc" } });
  const userIds = volunteers.map((v) => v.userId);
  const [activityCounts, recentActivity] = await Promise.all([
    db.auditLog.groupBy({ by: ["userId"], where: { conferenceId: id, userId: { in: userIds } }, _count: true }),
    db.auditLog.findMany({
      where: { conferenceId: id, userId: { in: userIds } },
      orderBy: { createdAt: "desc" },
      take: 20,
      include: { user: true },
    }),
  ]);
  const countByUser = new Map(activityCounts.map((a) => [a.userId, a._count]));
  const editing = edit ? volunteers.find((v) => v.id === edit) : undefined;
  const areaLabel = (key: string) => VOLUNTEER_AREAS.find((a) => a.key === key)?.label ?? key;

  return (
    <main>
      <PageHeader title="Volunteers" sub={`${volunteers.length} volunteers — each gets a login scoped to their assigned areas.`} />
      {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>}
      {added && (
        <div className="mb-4 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-600">
          ✓ <strong>{added}</strong> added as a volunteer.
          {temp ? <> A login was created — temporary password: <code className="rounded bg-white/70 px-1.5 py-0.5 font-mono font-bold">{temp}</code> (share it with them securely; shown only once).</> : " They already had a Confexe account — they can sign in with their existing password."}
        </div>
      )}

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="space-y-3 lg:col-span-2">
          {volunteers.length === 0 && <EmptyState title="No volunteers yet" body="Add volunteers with their duties — they log in and see only the sections you assign." />}
          {volunteers.map((v) => {
            const areas = parseJSON<string[]>(v.areas, []);
            return (
              <Card key={v.id} className="flex items-start justify-between gap-4 p-4">
                <div className="flex min-w-0 gap-3">
                  <Avatar name={v.name} src={v.photoUrl} size={12} />
                  <div className="min-w-0">
                    <div className="font-semibold text-zinc-100">{v.name}</div>
                    <div className="text-xs text-zinc-500">
                      {v.email}{v.phone ? ` · ${v.phone}` : ""}{v.department ? ` · ${v.department}` : ""}
                      {v.linkedin && <> · <a href={v.linkedin} target="_blank" rel="noreferrer" className="text-[#0a66c2] hover:underline">LinkedIn</a></>}
                    </div>
                    <div className="mt-1.5 flex flex-wrap gap-1.5">
                      {areas.length === 0 && <Badge className="bg-amber-500/10 text-amber-600">no areas assigned</Badge>}
                      {areas.map((a) => <Badge key={a} className="bg-indigo-500/10 text-indigo-600">{areaLabel(a)}</Badge>)}
                      <Badge className="bg-emerald-500/10 text-emerald-600">{countByUser.get(v.userId) ?? 0} actions</Badge>
                    </div>
                  </div>
                </div>
                <div className="flex shrink-0 gap-1.5">
                  <Link href={`/dashboard/c/${id}/volunteers?edit=${v.id}`} className={btn.smSecondary}>✎ Edit</Link>
                  <form action={removeVolunteer.bind(null, id, v.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 volunteer (their login remains)">✕</button>
                  </form>
                </div>
              </Card>
            );
          })}

          <Card className="p-5">
            <h2 className="text-sm font-semibold text-zinc-300">📜 Volunteer activity log</h2>
            <div className="mt-3 space-y-1.5 font-mono text-xs">
              {recentActivity.length === 0 && <p className="font-sans text-sm text-zinc-500">No volunteer actions recorded yet — check-ins, agenda edits and other work will appear here.</p>}
              {recentActivity.map((a) => (
                <div key={a.id} className="flex justify-between gap-3 text-zinc-500">
                  <span className="truncate">
                    <span className="font-sans font-semibold text-zinc-300">{a.user?.name}</span>
                    <span className="ml-2 text-indigo-600/80">{a.action}</span>
                  </span>
                  <span className="shrink-0 text-zinc-600">{fmtDateTime(a.createdAt)}</span>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <Card className="h-fit p-5">
          <h2 className="text-sm font-semibold text-zinc-200">Add volunteer</h2>
          <p className="mt-1 text-xs text-zinc-500">If the email has no Confexe account, one is created and a temporary password is shown to you once.</p>
          <form action={createVolunteer.bind(null, id)} className="mt-4 space-y-3">
            <VolunteerFormFields />
            <button className={`${btn.primary} w-full`}>Add volunteer</button>
          </form>
        </Card>
      </div>

      {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 volunteer</h2>
                <Link href={`/dashboard/c/${id}/volunteers`} 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={updateVolunteer.bind(null, id, editing.id)} className="space-y-3">
                <VolunteerFormFields volunteer={editing} />
                <div className="flex justify-end gap-2 border-t border-zinc-800/50 pt-4">
                  <Link href={`/dashboard/c/${id}/volunteers`} className={btn.secondary}>Cancel</Link>
                  <button className={btn.primary}>Save changes</button>
                </div>
              </form>
            </Card>
          </div>
        </div>
      )}
    </main>
  );
}
