import { FormField, Select } from '@cameleer/design-system';
import type { FormState } from './form-state';
import { RouteMetricForm } from './condition-forms/RouteMetricForm';
import { ExchangeMatchForm } from './condition-forms/ExchangeMatchForm';
import { AgentStateForm } from './condition-forms/AgentStateForm';
import { AgentLifecycleForm } from './condition-forms/AgentLifecycleForm';
import { DeploymentStateForm } from './condition-forms/DeploymentStateForm';
import { LogPatternForm } from './condition-forms/LogPatternForm';
import { JvmMetricForm } from './condition-forms/JvmMetricForm';
import { CONDITION_KIND_OPTIONS } from '../enums';

export function ConditionStep({ form, setForm }: { form: FormState; setForm: (f: FormState) => void }) {
  const onKindChange = (v: string) => {
    const kind = v as FormState['conditionKind'];
    // Reset the condition payload so stale fields from a previous kind don't leak
    // into the save request. Preserve scope — it's managed on the scope step.
    const prev = form.condition as Record<string, unknown>;
    const base: Record<string, unknown> = { kind, scope: prev.scope };
    // EXCHANGE_MATCH must carry a fireMode — the backend ctor now rejects null.
    // Seed PER_EXCHANGE so a user can save without touching every sub-field
    // (matches what the form's Select displays by default).
    if (kind === 'EXCHANGE_MATCH') {
      base.fireMode = 'PER_EXCHANGE';
      base.filter = {};
    }
    if (kind === 'AGENT_LIFECYCLE') {
      // Sensible defaults so a rule can be saved without touching every sub-field.
      // WENT_DEAD is the most "alert-worthy" event out of the six; a 5-minute
      // window matches the registry's STALE→DEAD cadence + slack for tick jitter.
      base.eventTypes = ['WENT_DEAD'];
      base.withinSeconds = 300;
    }
    setForm({
      ...form,
      conditionKind: kind,
      condition: base as FormState['condition'],
    });
  };

  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 720 }}>
      <FormField label="Condition kind">
        <Select
          value={form.conditionKind}
          onChange={(e) => onKindChange(e.target.value)}
          options={CONDITION_KIND_OPTIONS}
        />
      </FormField>
      {form.conditionKind === 'ROUTE_METRIC' && <RouteMetricForm form={form} setForm={setForm} />}
      {form.conditionKind === 'EXCHANGE_MATCH' && <ExchangeMatchForm form={form} setForm={setForm} />}
      {form.conditionKind === 'AGENT_STATE' && <AgentStateForm form={form} setForm={setForm} />}
      {form.conditionKind === 'AGENT_LIFECYCLE' && <AgentLifecycleForm form={form} setForm={setForm} />}
      {form.conditionKind === 'DEPLOYMENT_STATE' && <DeploymentStateForm form={form} setForm={setForm} />}
      {form.conditionKind === 'LOG_PATTERN' && <LogPatternForm form={form} setForm={setForm} />}
      {form.conditionKind === 'JVM_METRIC' && <JvmMetricForm form={form} setForm={setForm} />}
    </div>
  );
}
