"use client";

import { API_SECTIONS, presetScopes, type ScopeLevel, type TokenScopes } from "@/lib/developers/scopes";
import { cn } from "@/lib/utils";

const LEVELS: Array<{ value: ScopeLevel; label: string }> = [
  { value: "none", label: "No access" },
  { value: "read", label: "Read" },
  { value: "write", label: "Read + write" },
];

/** Rights per section + presets (all read / all write / none). Write always includes read. */
export function TokenScopesEditor({
  value,
  onChange,
  disabled,
}: {
  value: TokenScopes;
  onChange: (next: TokenScopes) => void;
  disabled?: boolean;
}) {
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap gap-2">
        {([
          ["read", "Read everything"],
          ["write", "Read + write everything"],
          ["none", "No access"],
        ] as const).map(([kind, label]) => (
          <button
            key={kind}
            type="button"
            disabled={disabled}
            onClick={() => onChange(presetScopes(kind))}
            className="rounded-full border border-border/60 px-3 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50"
          >
            {label}
          </button>
        ))}
      </div>
      <div className="divide-y divide-border/50 rounded-xl border border-border/60">
        {API_SECTIONS.map((section) => (
          <div key={section.id} className="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
            <span className="text-sm font-medium">{section.label}</span>
            <div role="radiogroup" aria-label={`${section.label} access`} className="flex rounded-lg border border-border/60 p-0.5">
              {LEVELS.map((level) => {
                const unavailable = level.value === "write" && !section.writable;
                const active = value[section.id] === level.value;
                return (
                  <button
                    key={level.value}
                    type="button"
                    role="radio"
                    aria-checked={active}
                    disabled={disabled || unavailable}
                    title={unavailable ? "Only reading is possible through the API" : undefined}
                    onClick={() => onChange({ ...value, [section.id]: level.value })}
                    className={cn(
                      "rounded-md px-2.5 py-1 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-40",
                      active
                        ? level.value === "none"
                          ? "bg-muted text-foreground"
                          : level.value === "read"
                            ? "bg-sky-500/15 text-sky-400"
                            : "bg-emerald-500/15 text-emerald-400"
                        : "text-muted-foreground hover:text-foreground"
                    )}
                  >
                    {level.label}
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/** Short summary for the token list, e.g. "Tasks ✎ · Finances 👁". */
export function scopesSummary(scopes: TokenScopes) {
  const write = API_SECTIONS.filter((s) => scopes[s.id] === "write").map((s) => s.label);
  const read = API_SECTIONS.filter((s) => scopes[s.id] === "read").map((s) => s.label);
  if (!write.length && !read.length) return "No access";
  if (write.length === API_SECTIONS.filter((s) => s.writable).length && !read.some((r) => r !== "Vault (documents)")) {
    return read.length ? "Everything (Vault read-only)" : "Everything except Vault";
  }
  return [write.length ? `Write: ${write.join(", ")}` : "", read.length ? `Read: ${read.join(", ")}` : ""].filter(Boolean).join(" · ");
}
