import { memo, useState, useId } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { client, type WorkspaceGroupResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { workspaceColor, workspaceInitial } from "@/components/shell/shared";
import { Plus, Trash2 } from "lucide-react";

const GroupRow = memo(function GroupRow({
  group,
  onRemove,
}: {
  group: WorkspaceGroupResponse;
  onRemove: (name: string) => void;
}) {
  return (
    <div className="flex items-center gap-3 border-b border-border/60 px-5 py-3 last:border-b-0 transition-colors hover:bg-muted/30">
      <span
        aria-hidden="true"
        className={cn(
          "grid size-7 shrink-0 place-items-center overflow-hidden rounded-full bg-gradient-to-br text-xs font-bold text-white",
          workspaceColor(group.name),
        )}
      >
        {group.avatar_url ? (
          <img alt="" className="size-full object-cover" src={group.avatar_url} />
        ) : (
          workspaceInitial(group.name)
        )}
      </span>
      <span className="text-sm font-medium text-foreground">{group.name}</span>
      {group.is_deleted && (
        <span className="rounded bg-muted/60 px-2 py-0.5 text-[11px] text-muted-foreground">Deleted</span>
      )}
      <div className="ml-auto">
        <Button
          aria-label={`Delete group ${group.name}`}
          className="size-8 text-muted-foreground hover:text-destructive"
          onClick={() => onRemove(group.name)}
          size="icon"
          type="button"
          variant="ghost"
        >
          <Trash2 aria-hidden="true" className="size-4" />
        </Button>
      </div>
    </div>
  );
});

function ListSkeleton() {
  return (
    <div aria-busy="true" className="px-5 py-3 space-y-3">
      {Array.from({ length: 2 }).map((_, i) => (
        <div className="h-8 animate-pulse rounded-lg bg-muted/50" key={i} />
      ))}
    </div>
  );
}

export default function GroupsTab({ projectName }: { projectName: string }) {
  const qc = useQueryClient();
  const [newName, setNewName] = useState("");
  const groupInputId = useId();

  const { data: groups = [], isLoading } = useQuery({
    queryKey: ["workspace", projectName, "groups"],
    queryFn: async () => {
      const res = await client.workspaceListGroups(projectName);
      return res.data;
    },
    retry: false,
  });

  const createGroup = useMutation({
    mutationFn: async () => {
      await client.workspaceCreateGroup(projectName, { name: newName.trim() });
    },
    onSuccess: () => {
      setNewName("");
      qc.invalidateQueries({ queryKey: ["workspace", projectName, "groups"] });
    },
  });

  const deleteGroup = useMutation({
    mutationFn: async (groupName: string) => {
      await client.workspaceDeleteGroup(projectName, groupName);
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["workspace", projectName, "groups"] }),
  });

  return (
    <div className="max-w-2xl space-y-8">
      {/* Create group card */}
      <div className="rounded-xl border border-border bg-card p-6 space-y-4">
        <div>
          <h2 className="text-sm font-semibold text-foreground mb-1">Create a group</h2>
          <p className="text-xs text-muted-foreground">Groups help organize members and manage permissions.</p>
        </div>

        <div className="flex items-center gap-3">
          <Input
            className="h-10 flex-1 text-sm"
            id={groupInputId}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="Group name"
            value={newName}
          />
          <Button
            className="h-10 px-4 text-sm"
            disabled={!newName.trim()}
            onClick={() => createGroup.mutate()}
            type="button"
          >
            <Plus aria-hidden="true" className="mr-1.5 size-4" />
            Create
          </Button>
        </div>
      </div>

      {/* Group list card */}
      <div className="rounded-xl border border-border bg-card overflow-hidden">
        <div className="border-b border-border px-5 py-3">
          <h2 className="text-sm font-semibold text-foreground">
            All groups
            {groups.length > 0 && (
              <span className="ml-2 font-normal text-muted-foreground">
                ({groups.filter((g) => !g.is_deleted).length})
              </span>
            )}
          </h2>
        </div>

        {isLoading ? (
          <ListSkeleton />
        ) : (() => {
          const active = groups.filter((g) => !g.is_deleted);
          return active.length > 0 ? (
            active.map((g) => (
              <GroupRow key={g.name} group={g} onRemove={(n) => deleteGroup.mutate(n)} />
            ))
          ) : (
            <div className="py-16 text-center">
              <p className="text-sm text-muted-foreground">No groups yet</p>
              <p className="mt-1 text-xs text-muted-foreground/60">Create a group above to get started.</p>
            </div>
          );
        })()}
      </div>
    </div>
  );
}
