import { FormField, Input } from '@cameleer/design-system';
import type { FormState } from '../form-state';
import {
  AGENT_LIFECYCLE_EVENT_TYPE_OPTIONS,
  type AgentLifecycleEventType,
} from '../../enums';

/**
 * Form for `AGENT_LIFECYCLE` conditions. Users pick one or more event types
 * (allowlist only) and a lookback window in seconds. The evaluator queries
 * `agent_events` with those filters; each matching row produces its own
 * {@code AlertInstance}.
 */
export function AgentLifecycleForm({ form, setForm }: { form: FormState; setForm: (f: FormState) => void }) {
  const c = form.condition as Record<string, unknown>;
  const selected = new Set<AgentLifecycleEventType>(
    Array.isArray(c.eventTypes) ? (c.eventTypes as AgentLifecycleEventType[]) : [],
  );

  const patch = (p: Record<string, unknown>) =>
    setForm({
      ...form,
      condition: { ...(form.condition as Record<string, unknown>), ...p } as FormState['condition'],
    });

  const toggle = (t: AgentLifecycleEventType) => {
    const next = new Set(selected);
    if (next.has(t)) next.delete(t); else next.add(t);
    patch({ eventTypes: [...next] });
  };

  return (
    <>
      <FormField
        label="Event types"
        hint="Fires one alert per matching event. Pick at least one."
      >
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {AGENT_LIFECYCLE_EVENT_TYPE_OPTIONS.map((opt) => {
            const active = selected.has(opt.value);
            return (
              <button
                key={opt.value}
                type="button"
                onClick={() => toggle(opt.value)}
                style={{
                  border: `1px solid ${active ? 'var(--amber)' : 'var(--border-subtle)'}`,
                  background: active ? 'var(--amber-bg)' : 'transparent',
                  color: active ? 'var(--text-primary)' : 'var(--text-secondary)',
                  borderRadius: 999,
                  padding: '4px 10px',
                  fontSize: 12,
                  cursor: 'pointer',
                }}
              >
                {opt.label}
              </button>
            );
          })}
        </div>
      </FormField>
      <FormField label="Lookback window (seconds)" hint="How far back to search for matching events each tick.">
        <Input
          type="number"
          min={1}
          value={(c.withinSeconds as number | undefined) ?? 300}
          onChange={(e) => patch({ withinSeconds: Number(e.target.value) })}
        />
      </FormField>
    </>
  );
}
