import { FormField, Input, Select } from '@cameleer/design-system';
import type { FormState } from '../form-state';
import { applyFireModeChange } from '../form-state';
import { EXCHANGE_FIRE_MODE_OPTIONS, type ExchangeFireMode } from '../../enums';

// ExchangeFilter.status is typed as `String` on the backend (no @Schema
// allowableValues yet) so options stay hand-typed. Follow-up: annotate the
// record component to fold this into alerting-enums.ts.
const STATUSES = [
  { value: '', label: '(any)' },
  { value: 'COMPLETED', label: 'COMPLETED' },
  { value: 'FAILED', label: 'FAILED' },
  { value: 'RUNNING', label: 'RUNNING' },
];

export function ExchangeMatchForm({ form, setForm }: { form: FormState; setForm: (f: FormState) => void }) {
  const c = form.condition as Record<string, unknown>;
  const filter = (c.filter as Record<string, unknown> | undefined) ?? {};
  const patch = (p: Record<string, unknown>) =>
    setForm({ ...form, condition: { ...(form.condition as Record<string, unknown>), ...p } as FormState['condition'] });

  return (
    <>
      <FormField label="Fire mode">
        <Select
          value={(c.fireMode as string) ?? 'PER_EXCHANGE'}
          onChange={(e) => setForm(applyFireModeChange(form, e.target.value as ExchangeFireMode))}
          options={EXCHANGE_FIRE_MODE_OPTIONS}
        />
      </FormField>
      <FormField label="Status filter">
        <Select
          value={(filter.status as string) ?? ''}
          onChange={(e) => patch({ filter: { ...filter, status: e.target.value || undefined } })}
          options={STATUSES}
        />
      </FormField>
      {c.fireMode === 'COUNT_IN_WINDOW' && (
        <>
          <FormField label="Threshold (matches)">
            <Input
              type="number"
              value={(c.threshold as number | undefined) ?? ''}
              onChange={(e) => patch({ threshold: Number(e.target.value) })}
            />
          </FormField>
          <FormField label="Window (seconds)">
            <Input
              type="number"
              value={(c.windowSeconds as number | undefined) ?? 900}
              onChange={(e) => patch({ windowSeconds: Number(e.target.value) })}
            />
          </FormField>
        </>
      )}
    </>
  );
}
