import React from 'react';
import { observer } from 'mobx-react';
import { CSSProperties } from 'glamor';
import { useLocalStyles } from '../../styles/defaults/useLocalStyles';
import { ApphouseComponent } from '../component.interfaces';
import { FormV2 as FormModel } from '../../models/Form/FormV2';
import { Form } from './Form';
import {
  Button,
  DatePicker,
  Input,
  InputColor,
  InputSelect,
  View,
  makeTitle,
  omit
} from '../..';
import { onSubmissionFormCompletedCallback } from '../../models/Form/FormV2';
import { BoxSizeStyles } from '../../styles/defaults/themes.interface';
import { getGutterStyles } from '../../styles/getGutterStyles';
import { InputCheckbox } from '../InputCheckbox';

export interface ApphouseFormV2Styles {
  container?: CSSProperties;
}

export interface ApphouseFormV2Props
  extends ApphouseComponent<ApphouseFormV2Styles> {
  form: FormModel;
  /**
   * A callback function needs to called when the form is submitted
   * Note: this callback is added for convenience
   * this callback does not alter any data in this form
   * @optional
   */
  onSubmit?: onSubmissionFormCompletedCallback;
  /**
   * The label of the submit button
   * @default 'Submit'
   * @optional
   */
  submitButtonLabel?: React.ReactNode;
  /**
   * if the submit button is loading
   * it true, it will display a spinner in the submit button
   * @default false
   */
  loading?: boolean;
  /**
   * if true, the submit button will be hidden
   * @default false - the submit button will be visible
   */
  hideSubmitButton?: boolean;
  /**
   * The size of the input
   */
  inputSize?: keyof BoxSizeStyles;
}
/**
 * ApphouseFormV2 renders the fields of a form smartly
 * It detects the type of the field and renders the appropriate input
 */
export const ApphouseFormV2: React.FC<ApphouseFormV2Props> = observer(
  (props) => {
    const {
      styleOverwrites,
      gutters,
      form,
      submitButtonLabel = 'Submit',
      hideSubmitButton,
      loading,
      onSubmit,
      inputSize = 'm'
    } = props;
    const componentStyles: ApphouseFormV2Styles = {
      container: {
        ...getGutterStyles(gutters)
      }
    };
    const fields = form.fields.values;
    const localStyles = useLocalStyles<ApphouseFormV2Styles>(
      componentStyles,
      styleOverwrites
    );
    return (
      <Form
        data-xray="ApphouseFormV2"
        styleOverwrites={localStyles.container}
        data-style="ApphouseFormV2.container"
      >
        {fields?.map((field) => {
          const { type, id } = field;
          const formField = form.getField(id);
          const error =
            formField?.valid === false && formField.value !== ''
              ? 'Invalid'
              : undefined;
          const fieldInput = field.input;
          const label = fieldInput?.label || makeTitle(id);
          const { required, disabled, variant } = fieldInput || {};
          const value = form.getValue(id) as any;
          if (type === 'date') {
            return (
              <DatePicker
                key={id}
                id={id}
                label={label}
                required={required}
                disabled={disabled}
                value={value}
                error={error}
                size={variant || inputSize}
                min={fieldInput?.min ? (`${fieldInput.min}` as any) : undefined}
                max={fieldInput?.max ? (`${fieldInput.max}` as any) : undefined}
                onDateSelect={(v) => {
                  form.setValue(id, v);
                }}
                {...omit(fieldInput, [
                  'label',
                  'id',
                  'value',
                  'required',
                  'disabled',
                  'onChange',
                  'min',
                  'max'
                ])}
              />
            );
          }

          if (type === 'color') {
            return (
              <InputColor
                disabled={disabled}
                error={error}
                id={id}
                key={id}
                label={label}
                required={required}
                value={value}
                variant={variant || inputSize}
                onChange={(v) => {
                  console.log({ v });
                  form.setValue(id, v);
                }}
              />
            );
          }

          if (type === 'checkbox') {
            return (
              <InputCheckbox
                id="checkbox"
                onChange={(value) => {
                  console.log({ value });
                  form.setValue(id, value + '');
                }}
                checked={value === 'true'}
                label={label}
                required={required}
                disabled={disabled}
                error={error}
              />
            );
          }
          if (type === 'option') {
            return (
              <InputSelect
                disabled={disabled}
                error={error}
                id={id}
                key={`input-select-${id}-${id}`}
                label={label}
                options={field.options}
                value={value}
                required={required}
                variant={variant || inputSize}
                onChange={(v) => {
                  form.setValue(id, v);
                }}
                styleOverwrites={
                  {
                    select: {
                      select: {
                        width: '100%'
                      }
                    }
                  } as any
                }
                {...fieldInput}
              />
            );
          }
          return (
            <Input
              disabled={disabled}
              error={error}
              id={id}
              key={id}
              label={label}
              password={type === 'password'}
              required={required}
              value={value}
              variant={variant || inputSize}
              onChange={(v) => {
                form.setValue(id, v);
              }}
              {...fieldInput}
            />
          );
        })}

        {!hideSubmitButton && (
          <View>
            <Button
              disabled={!form.valid || loading}
              loading={loading}
              onClick={() => {
                console.log({ form: form.data });
                if (onSubmit && form.valid) {
                  onSubmit(form.data);
                }
              }}
            >
              {submitButtonLabel}
            </Button>
          </View>
        )}
      </Form>
    );
  }
);
