"use client";

import {
  SimpleForm,
  TextInput,
  Edit,
  ArrayInput,
  SimpleFormIterator,
  regex,
  required,
  EditProps,
  FormDataConsumer,
} from "react-admin";
import { BackendTypeInput, BackendIdInput, HttpMethodInput } from "./shared";

const WebhookTitle = ({ record }: any) => {
  let title = "";
  if (record) title = record.name ?? record.email;
  return <span>Webhook {title}</span>;
};

const WebhookEdit = (props: EditProps) => (
  <Edit title={<WebhookTitle />} {...props}>
    <SimpleForm>
      <TextInput source="name" validate={[required()]} />
      <BackendTypeInput />
      <FormDataConsumer subscription={{ values: true }}>
        {BackendIdInput}
      </FormDataConsumer>
      <TextInput
        source="endpointUrl"
        validate={[required(), regex(/^https?:\/\/[^/]+/, "validation.url")]}
      />
      <HttpMethodInput />
      <ArrayInput source="headers">
        <SimpleFormIterator>
          <TextInput
            source="header"
            validate={[required(), regex(/^[\w-]+$/, "validation.headerName")]}
          />
          <TextInput source="value" validate={[required()]} />
        </SimpleFormIterator>
      </ArrayInput>
    </SimpleForm>
  </Edit>
);

export default WebhookEdit;
