import { TextInput } from '@mantine/core';
import { useUncontrolled } from '@mantine/hooks';
import { Controller } from 'react-hook-form';

import { Former } from '../Former';

export const ApiFormData = (props: {
  onChange?: (values: Record<string, unknown>) => void;
  primeData?: Record<string, unknown>;
  values?: Record<string, unknown>;
}) => {
  const [values, setValues] = useUncontrolled<Record<string, unknown>>({
    defaultValue: { authToken: '', url: '', ...props.primeData },
    finalValue: { authToken: '', url: '', ...props.primeData },
    onChange: props.onChange,
    value: props.values,
  });

  return (
    <Former
      disableHTMlForm
      id="api-form-data"
      layout={{ saveButtonTitle: 'Save URL Parameters' }}
      onChange={setValues}
      primeData={props.primeData}
      request="update"
      uniqueKeyField="id"
      values={values}
    >
      <Controller
        name="url"
        render={({ field }) => <TextInput label="URL" type="url" {...field} />}
      />
      <Controller
        name="authToken"
        render={({ field }) => <TextInput label="Auth Token" type="password" {...field} />}
      />
    </Former>
  );
};
