import { unref, computed } from 'vue';
import { ColumnKeyFlag } from '../types/column';
import type { ComputedRef } from 'vue';
import type { FormSchema, SchemaFormProps } from '@/components/lt-a-form/src';

import type { UseTableFormContext } from './useTableForm';

export function useRowForm({ tableState, slots, tableMethods }: UseTableFormContext) {
  const { getProps, loadingRef } = tableState;
  const { getColumnKey } = tableMethods;

  const getRowFormProps = computed((): SchemaFormProps => {
    const { formProps } = unref(getProps);
    const { submitButtonOptions } = formProps || {};
    return {
      showAdvancedButton: false,
      layout: 'horizontal',
      labelWidth: 100,
      ...formProps,
      schemas: formProps.schemas ?? unref(formSchemas),
      submitButtonOptions: { loading: unref(loadingRef), ...submitButtonOptions },
      compact: true,
      showResetButton: false,
      showSubmitButton: false,
    };
  });

  const formSchemas = computed<FormSchema[]>(() => {
    const columnKeyFlags = Object.keys(ColumnKeyFlag);
    return unref(getProps)
      .columns.filter((n) => {
        const field = getColumnKey(n);
        return !!field && !columnKeyFlags.includes(field as string);
      })
      .map((n) => {
        return {
          field: getColumnKey(n) as string,
          component: 'Input',
          // eslint-disable-next-line 
          componentProps: ({ formInstance, formModel }) => ({
            size: 'small',
          }),
          label: n.title as string,
          colProps: {
            span: 8,
          },
          ...n.formItemProps,
        };
      });
    // .sort((a, b) => Number(a?.order) - Number(b?.order)) as FormSchema[];
  });

  const getRowSlotKeys: ComputedRef<string[]> = computed(() => {
    const keys = Object.keys(slots);
    return keys
      .map((item) => (item.startsWith('form-') ? item : null))
      .filter((item): item is string => !!item);
  });

  function replaceRowSlotKey(key: string) {
    if (!key) return '';
    return key?.replace?.(/form-/, '') ?? '';
  }

  return {
    getRowFormProps,
    replaceRowSlotKey,
    getRowSlotKeys,
  };
}
