import { memo, useState, useId } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { client, type WorkspaceMemberResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { workspaceColor, workspaceInitial } from "@/components/shell/shared";
import { Trash2, UserPlus, Crown } from "lucide-react";

const MemberRow = memo(function MemberRow({
  member,
  onRemove,
  onUpdateRole,
}: {
  member: WorkspaceMemberResponse;
  onRemove: (username: string) => void;
  onUpdateRole: (username: string, admin: boolean) => void;
}) {
  const name = member.display_name ?? member.username;
  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(name),
        )}
      >
        {member.avatar_url ? (
          <img alt="" className="size-full object-cover" src={member.avatar_url} />
        ) : (
          workspaceInitial(name)
        )}
      </span>

      <div className="min-w-0 flex-1">
        <div className="text-sm font-medium text-foreground">{member.display_name ?? member.username}</div>
        <div className="text-xs text-muted-foreground">@{member.username}</div>
      </div>

      {member.owner ? (
        <span className="inline-flex items-center gap-1.5 rounded bg-warning/10 px-2.5 py-1 text-[11px] font-medium text-warning dark:text-warning">
          <Crown className="size-3" /> Owner
        </span>
      ) : (
        <div className="flex items-center gap-2">
          <Select
            aria-label={`Change role for ${member.username}`}
            defaultValue={member.admin ? "admin" : "member"}
            onValueChange={(v) => onUpdateRole(member.username, v === "admin")}
          >
            <SelectTrigger className="h-8 w-[100px] text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="admin">Admin</SelectItem>
              <SelectItem value="member">Member</SelectItem>
            </SelectContent>
          </Select>
          <Button
            aria-label={`Remove ${member.username} from workspace`}
            className="size-8 text-muted-foreground hover:text-destructive"
            onClick={() => onRemove(member.username)}
            size="icon"
            type="button"
            variant="ghost"
          >
            <Trash2 aria-hidden="true" className="size-4" />
          </Button>
        </div>
      )}
    </div>
  );
});

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

export default function MembersTab({ projectName }: { projectName: string }) {
  const qc = useQueryClient();
  const [addUsername, setAddUsername] = useState("");
  const [addAdmin, setAddAdmin] = useState(false);
  const userInputId = useId();

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

  const addMember = useMutation({
    mutationFn: async () => {
      await client.workspaceAddMember(projectName, {
        username: addUsername.trim(),
        admin: addAdmin,
      });
    },
    onSuccess: () => {
      setAddUsername("");
      setAddAdmin(false);
      qc.invalidateQueries({ queryKey: ["workspace", projectName, "members"] });
    },
  });

  const removeMember = useMutation({
    mutationFn: async (username: string) => {
      await client.workspaceRemoveMember(projectName, username);
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["workspace", projectName, "members"] }),
  });

  const updateMember = useMutation({
    mutationFn: async ({ username, admin }: { username: string; admin: boolean }) => {
      await client.workspaceUpdateMember(projectName, username, { admin });
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["workspace", projectName, "members"] }),
  });

  return (
    <div className="max-w-2xl space-y-8">
      {/* Add member 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">Add a member</h2>
          <p className="text-xs text-muted-foreground">Invite users to collaborate in this workspace.</p>
        </div>

        <div className="flex items-center gap-3">
          <Input
            className="h-10 flex-1 text-sm"
            id={userInputId}
            onChange={(e) => setAddUsername(e.target.value)}
            placeholder="Username"
            value={addUsername}
          />
          <label className="flex shrink-0 cursor-pointer items-center gap-2 text-sm text-muted-foreground">
            <input
              checked={addAdmin}
              className="size-4 rounded border-border accent-primary"
              onChange={(e) => setAddAdmin(e.target.checked)}
              type="checkbox"
            />
            Admin
          </label>
          <Button
            className="h-10 px-4 text-sm"
            disabled={!addUsername.trim()}
            onClick={() => addMember.mutate()}
            type="button"
          >
            <UserPlus aria-hidden="true" className="mr-1.5 size-4" />
            Add
          </Button>
        </div>
      </div>

      {/* Member list card */}
      <div className="rounded-xl border border-border bg-card overflow-hidden">
        <div className="border-b border-border px-5 py-3 flex items-center justify-between">
          <h2 className="text-sm font-semibold text-foreground">
            Members
            {members.length > 0 && (
              <span className="ml-2 font-normal text-muted-foreground">
                ({members.length})
              </span>
            )}
          </h2>
          <span className="text-xs text-muted-foreground">
            {members.filter((m) => m.admin || m.owner).length} admins
          </span>
        </div>

        {isLoading ? (
          <ListSkeleton />
        ) : members.length > 0 ? (
          members.map((m) => (
            <MemberRow
              key={m.username}
              member={m}
              onRemove={(u) => removeMember.mutate(u)}
              onUpdateRole={(u, a) => updateMember.mutate({ username: u, admin: a })}
            />
          ))
        ) : (
          <div className="py-16 text-center">
            <p className="text-sm text-muted-foreground">No members found</p>
            <p className="mt-1 text-xs text-muted-foreground/60">Add a member above to get started.</p>
          </div>
        )}
      </div>
    </div>
  );
}
