'use client';

import * as React from 'react';

/**
 * Scope picker for the connection setup modal.
 *
 * Lets the user store credentials at one of three scopes:
 *   - global  — shared across the whole machine
 *   - project — only resolves when a tool runs in this project's context
 *   - agent   — only resolves when this specific agent runs
 *
 * The picker fetches /api/projects and /api/state (for agents) on mount
 * and renders a dropdown for the chosen scope.
 *
 * @param {{
 *   value: { scope: 'global'|'project'|'agent', project_id: string|null, agent_id: string|null },
 *   onChange: (next) => void,
 *   supportsScopes: ('global'|'project'|'agent')[],
 *   disabled?: boolean,
 * }} props
 */
export default function ScopePicker({ value, onChange, supportsScopes = ['global', 'project', 'agent'], disabled }) {
  const [projects, setProjects] = React.useState([]);
  const [agents, setAgents] = React.useState([]);
  const [loadError, setLoadError] = React.useState(null);

  const needsProjects = supportsScopes.includes('project');
  const needsAgents = supportsScopes.includes('agent');

  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const promises = [];
        if (needsProjects) promises.push(fetch('/api/projects').then(r => r.json()));
        else promises.push(Promise.resolve({ projects: [] }));
        if (needsAgents) promises.push(fetch('/api/state').then(r => r.json()));
        else promises.push(Promise.resolve({ agents: [] }));
        const [projRes, stateRes] = await Promise.all(promises);
        if (cancelled) return;
        setProjects(Array.isArray(projRes?.projects) ? projRes.projects : []);
        const stateAgents = Array.isArray(stateRes?.agents) ? stateRes.agents : [];
        setAgents(stateAgents);
      } catch (err) {
        if (!cancelled) setLoadError(String(err?.message || err));
      }
    }
    load();
    return () => { cancelled = true; };
  }, [needsProjects, needsAgents]);

  function setScope(scope) {
    if (scope === 'global') onChange({ scope: 'global', project_id: null, agent_id: null });
    else if (scope === 'project') onChange({ scope: 'project', project_id: projects[0]?.id || null, agent_id: null });
    else if (scope === 'agent') onChange({ scope: 'agent', project_id: null, agent_id: agents[0]?.id || null });
  }

  // If only one scope is supported, render a static label instead of radios.
  if (supportsScopes.length === 1) {
    return (
      <div className="scope-picker scope-picker--locked">
        <span className="scope-picker-label">Scope</span>
        <span className="scope-picker-locked-value">{supportsScopes[0]}</span>
      </div>
    );
  }

  return (
    <fieldset className="scope-picker" disabled={disabled}>
      <legend className="scope-picker-legend">Scope</legend>

      {supportsScopes.includes('global') ? (
        <label className="scope-picker-radio">
          <input
            type="radio"
            name="scope"
            value="global"
            checked={value.scope === 'global'}
            onChange={() => setScope('global')}
          />
          <span className="scope-picker-radio-body">
            <b>Global</b>
            <small>Available to every project and every agent on this Mac.</small>
          </span>
        </label>
      ) : null}

      {supportsScopes.includes('project') ? (
        <label className="scope-picker-radio">
          <input
            type="radio"
            name="scope"
            value="project"
            checked={value.scope === 'project'}
            onChange={() => setScope('project')}
            disabled={projects.length === 0}
          />
          <span className="scope-picker-radio-body">
            <b>Project</b>
            <small>
              {projects.length === 0
                ? 'No projects yet — create one in the Projects tab.'
                : 'Resolved when a tool runs inside this project.'}
            </small>
            {value.scope === 'project' && projects.length > 0 ? (
              <select
                className="scope-picker-select"
                value={value.project_id || ''}
                onChange={e => onChange({ scope: 'project', project_id: e.target.value, agent_id: null })}
              >
                {projects.map(p => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </select>
            ) : null}
          </span>
        </label>
      ) : null}

      {supportsScopes.includes('agent') ? (
        <label className="scope-picker-radio">
          <input
            type="radio"
            name="scope"
            value="agent"
            checked={value.scope === 'agent'}
            onChange={() => setScope('agent')}
            disabled={agents.length === 0}
          />
          <span className="scope-picker-radio-body">
            <b>Agent</b>
            <small>
              {agents.length === 0
                ? 'No agents yet.'
                : 'Only this specific agent can use these credentials.'}
            </small>
            {value.scope === 'agent' && agents.length > 0 ? (
              <select
                className="scope-picker-select"
                value={value.agent_id || ''}
                onChange={e => onChange({ scope: 'agent', project_id: null, agent_id: e.target.value })}
              >
                {agents.map(a => (
                  <option key={a.id} value={a.id}>{a.name || a.id}</option>
                ))}
              </select>
            ) : null}
          </span>
        </label>
      ) : null}

      {loadError ? (
        <small className="scope-picker-error">Couldn't load projects or agents: {loadError}</small>
      ) : null}
    </fieldset>
  );
}
