import {
  addValidator,
  FieldDataType,
  handleInitialValues,
  handleOnFinish,
  ModelType,
} from '@gadmin2/react-common';
import {
  Edit,
  ListButton,
  RefreshButton,
  useFileUploadState,
  useForm,
} from '@refinedev/antd';
import {
  IResourceComponentsProps,
  useApiUrl,
  useTranslate,
} from '@refinedev/core';
import { Form } from 'antd';
import produce from 'immer';
import React from 'react';
import { getFormItem, onFormValuesChange } from '../../helpers';

import { modelsEnum, modelsMap } from '../../generated/models.index';
import {
  logFormConfig as formConfig,
  logFormPrismaSelect as formPrismaSelect,
} from '../../generated/props/log/config';
import { LogForm as transformClass } from '../../generated/props/log/form.validator';
import { logModel, useRelation } from '../../generated/props/log/model';
import { Log } from '../../generated/types/prisma.types';

const model: ModelType = produce(logModel, (draft: FieldDataType) => {
  /*
  (draft["description"] || {}).component = <MDEditor data-color-mode="light" />;
  (draft["status"] || {}).normalize = (value: any) => value ? "1" : "0";
  */
});
const fields: FieldDataType[] = formConfig.fields
  .map((fieldName: string) => model[fieldName])
  .filter((field) => field)
  .map((field) => {
    if (field.name === 'id') {
      return field;
    }
    /*
      if(field.name === "run_cron") {
        return produce(field, (draft: any) => {
          draft.validator = {validator: runCronValidator};
        });
      }
      */
    return addValidator(field, transformClass) as unknown as FieldDataType;
  });

export const LogEdit: React.FC<IResourceComponentsProps> = () => {
  const resourceName = 'log';
  const t = useTranslate();

  const { formProps, saveButtonProps, onFinish, form } = useForm<Log>({
    meta: { select: formPrismaSelect },
  });
  formProps.initialValues = handleInitialValues(
    formProps.initialValues || {},
    fields,
  );

  const apiUrl = useApiUrl();
  const { isLoading, onChange } = useFileUploadState();

  const relationSelectProps = useRelation(modelsMap);

  return (
    <Edit
      saveButtonProps={{
        ...saveButtonProps,
        disabled: isLoading,
      }}
      headerButtons={
        <>
          <ListButton />
          <RefreshButton meta={{ select: formPrismaSelect }} />
        </>
      }
    >
      <Form
        {...formProps}
        validateTrigger="onBlur"
        onFinish={(values) => {
          onFinish(handleOnFinish(values, fields, 'edit'));
        }}
        layout="vertical"
        form={form}
        onValuesChange={onFormValuesChange(form, formConfig.reaction)}
      >
        {fields.map((field) => {
          return getFormItem(
            field,
            resourceName,
            t,
            form,
            formConfig.reaction,
            modelsEnum,
            model,
            apiUrl,
            relationSelectProps,
            onChange,
          );
        })}
      </Form>
    </Edit>
  );
};
