"use client";

import { useParams } from "next/navigation";

import { cn } from "@/lib/utils";
import { api } from "@/lib/trpc";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

function memberInitials(name: string | null | undefined, email: string) {
  const n = name?.trim();
  if (n) return n.slice(0, 1).toUpperCase();
  return email.trim().slice(0, 1).toUpperCase();
}

function formatRoleLabel(role: string) {
  const key = role.toLowerCase();
  const labels: Record<string, string> = {
    owner: "Owner",
    admin: "Admin",
    member: "Member",
  };
  return labels[key] ?? role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();
}

function MemberCardSkeleton({ className }: { className?: string }) {
  return (
    <Card className={cn("overflow-hidden", className)}>
      <CardContent className="flex items-center gap-4 p-6">
        <div className="size-10 shrink-0 animate-pulse rounded-full bg-muted" />
        <div className="min-w-0 flex-1 space-y-2">
          <div className="h-4 w-32 animate-pulse rounded-md bg-muted" />
          <div className="h-3 w-48 max-w-full animate-pulse rounded-md bg-muted" />
        </div>
        <div className="h-5 w-16 shrink-0 animate-pulse rounded-full bg-muted" />
      </CardContent>
    </Card>
  );
}

export default function TeamsPage() {
  const params = useParams();
  const rawSlug = params?.workspaceSlug;
  const workspaceSlug = typeof rawSlug === "string" ? rawSlug : undefined;

  const { data: members, isLoading } = api.workspaces.listMembers.useQuery(
    { workspace: workspaceSlug as string },
    { enabled: Boolean(workspaceSlug) },
  );

  return (
    <div className="mx-auto max-w-5xl px-8 py-10">
      <div className="mb-8 flex flex-wrap items-center justify-between gap-4">
        <h1 className="text-3xl font-bold tracking-tight">Teams</h1>
        <Button type="button" onClick={() => window.alert("Invite coming soon")}>
          Invite
        </Button>
      </div>

      {!workspaceSlug ? (
        <p className="text-sm text-muted-foreground">Missing workspace.</p>
      ) : isLoading ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <MemberCardSkeleton key={i} />
          ))}
        </div>
      ) : !members?.length ? (
        <div
          className={cn(
            "rounded-lg border border-dashed border-border bg-muted/30 p-12 text-center text-sm text-muted-foreground",
          )}
        >
          No members in this workspace yet.
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {members.map((m) => {
            const displayName = m.name?.trim() || m.email;
            return (
              <Card key={m.id} className="overflow-hidden">
                <CardContent className="flex items-center gap-4 p-6">
                  <Avatar className="size-10 shrink-0">
                    {m.avatarUrl ? (
                      <AvatarImage src={m.avatarUrl} alt="" />
                    ) : null}
                    <AvatarFallback>{memberInitials(m.name, m.email)}</AvatarFallback>
                  </Avatar>
                  <div className="min-w-0 flex-1">
                    <p className="truncate font-medium">{displayName}</p>
                    <p className="truncate text-sm text-muted-foreground">{m.email}</p>
                  </div>
                  <Badge variant="secondary" className="shrink-0 capitalize">
                    {formatRoleLabel(m.role)}
                  </Badge>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
