import { usePluginData, useHostContext } from "@paperclipai/plugin-sdk/ui";
import type { PluginSidebarProps } from "@paperclipai/plugin-sdk/ui";
import { SIDEBAR_PREVIEW_LIMIT, type PermissionKey } from "../constants";

interface AgentPermissionsSummary {
  agentId: string;
  agentName: string;
  permissions: Record<PermissionKey, boolean>;
}

export function PermissionsNav(_props: PluginSidebarProps) {
  const { companyId } = useHostContext();
  const { data: agentsData, loading, error } = usePluginData<AgentPermissionsSummary[]>(
    "all-agents-permissions",
    companyId ? { companyId } : undefined
  );

  if (loading) return (
    <div role="status" style={{ padding: "1rem" }}>
      Loading permissions...
    </div>
  );
  if (error) return (
    <div role="alert" style={{ padding: "1rem", color: "#c00" }}>
      <strong>Error:</strong> {error.message}
    </div>
  );
  if (!agentsData || agentsData.length === 0) {
    return (
      <div style={{ padding: "1rem" }}>
        <h3 style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.5rem" }}>Permissions</h3>
        <p style={{ color: "#666", fontSize: "0.875rem" }}>No agents found</p>
      </div>
    );
  }

  const agentsWithPermissions = agentsData.filter(a => 
    Object.values(a.permissions).some(v => v)
  );

  return (
    <div style={{ padding: "1rem" }}>
      <h3 id="permissions-nav-heading" style={{ fontSize: "1rem", fontWeight: 600, marginBottom: "0.75rem" }}>Permissions</h3>
      <p aria-labelledby="permissions-nav-heading" style={{ color: "#666", fontSize: "0.75rem", marginBottom: "1rem" }}>
        {agentsWithPermissions.length} agent(s) with custom permissions
      </p>
      <ul style={{ display: "flex", flexDirection: "column", gap: "0.5rem", padding: 0, margin: 0, listStyle: "none" }}>
        {agentsData.slice(0, SIDEBAR_PREVIEW_LIMIT).map(agent => {
          const permCount = Object.values(agent.permissions).filter(Boolean).length;
          return (
            <li 
              key={agent.agentId}
              style={{ 
                fontSize: "0.875rem", 
                padding: "0.5rem", 
                backgroundColor: "#f9f9f9", 
                borderRadius: "4px" 
              }}
            >
              <div style={{ fontWeight: 500 }}>{agent.agentName}</div>
              <div style={{ color: "#888", fontSize: "0.75rem" }}>
                {permCount} permission(s) granted
              </div>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
