import Link from "next/link";
import { db } from "@/lib/db";
import { AdminPageHeader } from "@/components/admin/page-header";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Plus, Pencil, GripVertical, User } from "lucide-react";

export const dynamic = "force-dynamic";

function getInitials(name: string) {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase() ?? "")
    .join("");
}

export default async function AdminTeamPage() {
  const members = await db.teamMember.findMany({
    orderBy: [{ order: "asc" }, { createdAt: "desc" }],
  });

  return (
    <>
      <AdminPageHeader title="Team" description={`${members.length} team members`}>
        <Button asChild className="brand-gradient text-white">
          <Link href="/admin/team/new"><Plus className="size-4 mr-1.5" /> Add Member</Link>
        </Button>
      </AdminPageHeader>

      <Card className="rounded-2xl overflow-hidden">
        <div className="divide-y divide-border">
          {members.map((m) => (
            <div key={m.id} className="flex items-center gap-4 p-4 hover:bg-accent/40 transition-colors">
              <GripVertical className="size-4 text-muted-foreground/40 shrink-0" />
              <div className="grid place-items-center size-10 rounded-full bg-[var(--brand-royal)]/10 text-[var(--brand-royal)] shrink-0 overflow-hidden">
                {m.image ? (
                  <img src={m.image} alt={m.name} className="size-full object-cover" />
                ) : (
                  <span className="text-sm font-bold">{getInitials(m.name) || <User className="size-5" />}</span>
                )}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="font-semibold truncate">{m.name}</span>
                  {!m.isEnabled && <Badge variant="secondary" className="text-xs">Disabled</Badge>}
                </div>
                <div className="text-xs text-muted-foreground truncate">{m.position}</div>
              </div>
              <div className="hidden sm:block text-xs text-muted-foreground">Order: {m.order}</div>
              <Button asChild variant="outline" size="sm" className="shrink-0">
                <Link href={`/admin/team/edit/${m.id}`}><Pencil className="size-3.5 mr-1" /> Edit</Link>
              </Button>
            </div>
          ))}
          {members.length === 0 && (
            <div className="p-12 text-center text-muted-foreground">No team members yet. Click &ldquo;Add Member&rdquo; to create one.</div>
          )}
        </div>
      </Card>
    </>
  );
}
