import { FormField, Input, Select } from '@cameleer/design-system';
import { useCatalog } from '../../../api/queries/catalog';
import { useAgents } from '../../../api/queries/agents';
import { useSelectedEnv } from '../../../api/queries/alertMeta';
import type { FormState } from './form-state';
import { SEVERITY_OPTIONS } from '../../../api/alerting-enums';

const SCOPE_OPTIONS = [
  { value: 'env', label: 'Environment-wide' },
  { value: 'app', label: 'Single app' },
  { value: 'route', label: 'Single route' },
  { value: 'agent', label: 'Single agent' },
];

type AgentSummary = {
  instanceId?: string;
  displayName?: string;
  applicationId?: string;
};

export function ScopeStep({ form, setForm }: { form: FormState; setForm: (f: FormState) => void }) {
  const env = useSelectedEnv();
  const { data: catalog } = useCatalog(env);
  const { data: agents } = useAgents();

  const apps = (catalog ?? []).map((a) => ({
    slug: a.slug,
    name: a.displayName ?? a.slug,
    routes: a.routes ?? [],
  }));
  const selectedApp = apps.find((a) => a.slug === form.appSlug);
  const routes = selectedApp?.routes ?? [];
  const appAgents: AgentSummary[] = Array.isArray(agents)
    ? (agents as AgentSummary[]).filter((a) => a.applicationId === form.appSlug)
    : [];

  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 600 }}>
      <FormField label="Name">
        <Input
          value={form.name}
          onChange={(e) => setForm({ ...form, name: e.target.value })}
          placeholder="Order API error rate"
        />
      </FormField>
      <FormField label="Description">
        <Input
          value={form.description}
          onChange={(e) => setForm({ ...form, description: e.target.value })}
        />
      </FormField>
      <FormField label="Severity">
        <Select
          value={form.severity}
          onChange={(e) => setForm({ ...form, severity: e.target.value as FormState['severity'] })}
          options={SEVERITY_OPTIONS}
        />
      </FormField>
      <FormField label="Scope">
        <Select
          value={form.scopeKind}
          onChange={(e) => setForm({ ...form, scopeKind: e.target.value as FormState['scopeKind'] })}
          options={SCOPE_OPTIONS}
        />
      </FormField>
      {form.scopeKind !== 'env' && (
        <FormField label="App">
          <Select
            value={form.appSlug}
            onChange={(e) => setForm({ ...form, appSlug: e.target.value, routeId: '', agentId: '' })}
            options={[{ value: '', label: '-- select --' }, ...apps.map((a) => ({ value: a.slug, label: a.name }))]}
          />
        </FormField>
      )}
      {form.scopeKind === 'route' && (
        <FormField label="Route">
          <Select
            value={form.routeId}
            onChange={(e) => setForm({ ...form, routeId: e.target.value })}
            options={[{ value: '', label: '-- select --' }, ...routes.map((r) => ({ value: r.routeId, label: r.routeId }))]}
          />
        </FormField>
      )}
      {form.scopeKind === 'agent' && (
        <FormField label="Agent">
          <Select
            value={form.agentId}
            onChange={(e) => setForm({ ...form, agentId: e.target.value })}
            options={[
              { value: '', label: '-- select --' },
              ...appAgents.map((a) => ({ value: a.instanceId ?? '', label: a.displayName ?? a.instanceId ?? '' })),
            ]}
          />
        </FormField>
      )}
    </div>
  );
}
