import { db } from "@/lib/db";
import { getOrgContext, canOrgModule } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { Avatar, Badge, btn, Card, EmptyState, Field, PageHeader, StatCard, input } from "@/components/ui";
import { fmtDate } from "@/lib/utils";
import { ORG_ROLES, ORG_ROLE_LABELS, ORG_ROLE_DESCRIPTIONS } from "@/lib/constants";
import { inviteTeamMember, removeTeamMember, updateTeamRole } from "./actions";

export const metadata = { title: "Team & Users" };

export default async function TeamPage({
  searchParams,
}: {
  searchParams: Promise<{ saved?: string; error?: string; tempEmail?: string; tempPassword?: string }>;
}) {
  const me = await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "team")) {
    return <EmptyState title="No access" body="Team management is for organization owners and admins." />;
  }
  const org = ctx.org;
  const sp = await searchParams;

  const members = await db.orgMember.findMany({
    where: { orgId: org.id },
    include: { user: { select: { id: true, name: true, email: true, avatarUrl: true, designation: true, createdAt: true } } },
    orderBy: { role: "asc" },
  });
  const rank: Record<string, number> = { OWNER: 0, ADMIN: 1 };
  members.sort((a, b) => (rank[a.role] ?? 2) - (rank[b.role] ?? 2) || a.user.name.localeCompare(b.user.name));

  return (
    <main>
      <PageHeader
        title="👨‍💼 Team & Users"
        sub={`Internal users of ${org.name} with role-based permissions — each role unlocks exactly the modules it needs.`}
      />
      {sp.saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ {sp.saved}</p>}
      {sp.error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{sp.error}</p>}
      {sp.tempPassword && (
        <Card className="mb-4 border-amber-300/70 bg-amber-500/10 p-4">
          <p className="text-sm font-semibold text-amber-700">🔑 One-time login for {sp.tempEmail}</p>
          <p className="mt-1 text-sm text-amber-700">
            Temporary password: <code className="rounded bg-white/70 px-2 py-0.5 font-mono font-bold">{sp.tempPassword}</code>
            {" "}— share it securely; it is shown only once.
          </p>
        </Card>
      )}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Team Members" value={members.length} />
        <StatCard label="Admins" value={members.filter((m) => ["OWNER", "ADMIN"].includes(m.role)).length} />
        <StatCard label="Managers" value={members.filter((m) => m.role.endsWith("_MANAGER")).length} />
        <StatCard label="Viewers" value={members.filter((m) => m.role === "VIEWER").length} />
      </div>

      {/* Invite */}
      <Card className="mt-5 p-5">
        <h3 className="mb-3 text-sm font-semibold text-zinc-200">Add team member</h3>
        <form action={inviteTeamMember} className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <Field name="name" title="Name *"><input id="name" name="name" required className={input} /></Field>
          <Field name="email" title="Email *"><input id="email" name="email" type="email" required className={input} /></Field>
          <Field name="role" title="Role *">
            <select id="role" name="role" className={input} defaultValue="CONFERENCE_MANAGER">
              {ORG_ROLES.filter((r) => r !== "OWNER").map((r) => <option key={r} value={r}>{ORG_ROLE_LABELS[r]}</option>)}
            </select>
          </Field>
          <div className="flex items-end"><button className={`${btn.primary} w-full`}>Add member</button></div>
        </form>
        <p className="mt-2 text-xs text-zinc-500">If the email has no Confexe account yet, one is created with a one-time password shown to you here.</p>
      </Card>

      {/* Members table */}
      <Card className="mt-5 overflow-x-auto">
        <table className="w-full min-w-[720px] text-sm">
          <thead>
            <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
              <th className="px-4 py-3">Member</th>
              <th className="px-3 py-3">Role</th>
              <th className="px-3 py-3">Member Since</th>
              <th className="px-3 py-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {members.map((m) => (
              <tr key={m.id} className="border-b border-zinc-800/40">
                <td className="px-4 py-3">
                  <div className="flex items-center gap-3">
                    <Avatar name={m.user.name} src={m.user.avatarUrl} size={9} />
                    <div>
                      <div className="font-semibold text-zinc-100">
                        {m.user.name} {m.userId === me.id && <span className="text-xs font-normal text-zinc-500">(you)</span>}
                      </div>
                      <div className="text-[11px] text-zinc-500">{m.user.email}{m.user.designation ? ` · ${m.user.designation}` : ""}</div>
                    </div>
                  </div>
                </td>
                <td className="px-3 py-3">
                  {m.role === "OWNER" ? (
                    <Badge className="bg-fuchsia-500/10 text-fuchsia-600">👑 Owner</Badge>
                  ) : (
                    <form action={updateTeamRole.bind(null, m.id)} className="flex items-center gap-1.5">
                      <select name="role" defaultValue={m.role} className={`${input} !w-48 !py-1.5 text-xs`} aria-label={`Role for ${m.user.name}`}>
                        {ORG_ROLES.filter((r) => r !== "OWNER").map((r) => <option key={r} value={r}>{ORG_ROLE_LABELS[r]}</option>)}
                      </select>
                      <button className={btn.smSecondary}>Update</button>
                    </form>
                  )}
                </td>
                <td className="whitespace-nowrap px-3 py-3 text-xs text-zinc-500">{fmtDate(m.user.createdAt)}</td>
                <td className="px-3 py-3">
                  {m.role !== "OWNER" && m.userId !== me.id && (
                    <form action={removeTeamMember.bind(null, m.id)}>
                      <button className="rounded-lg px-2 py-1.5 text-xs text-red-500 transition hover:bg-red-500/10">Remove</button>
                    </form>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {/* Permission matrix */}
      <h3 className="mt-8 text-base font-bold text-zinc-100">Role permissions</h3>
      <p className="mt-1 text-sm text-zinc-500">What each role can see and do in the Organizer Console.</p>
      <div className="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {ORG_ROLES.map((r) => (
          <Card key={r} className="p-4">
            <div className="text-sm font-bold text-zinc-100">{ORG_ROLE_LABELS[r]}</div>
            <p className="mt-1.5 text-xs leading-relaxed text-zinc-500">{ORG_ROLE_DESCRIPTIONS[r]}</p>
          </Card>
        ))}
      </div>
    </main>
  );
}
