import type { FormComponentProps } from './types';
import type { MetaObject } from '@/api/ius/types';
import { mapFieldTypeElement } from '@/config/elements';
import { useFormStore } from '@/store/ius/form';
import { ElementContainer } from '@repo/ui';
import { get, omit } from 'radash';
import { useEffect } from 'react';

function RenderElement({
  fieldType,
  label,
  max,
  min = 0,
  name,
  visible,
  ...props
}: MetaObject & { readonly name: string }) {
  const { setValue, validation, values } = useFormStore();

  if (!visible) return false;

  const Element = mapFieldTypeElement[fieldType];

  return (
    <ElementContainer
      intent={validation[name] ? 'danger' : 'default'}
      message={validation[name]?.message}
      key={name}
      id={name}
      title={label}
    >
      <Element
        loading={!Object.keys(values).length}
        checked={fieldType === 'CHECKBOX' ? Boolean(values[name]) || false : false}
        id={name}
        value={values[name] || ''}
        min={min}
        max={max}
        onChange={(e) => {
          setValue({
            name,
            value:
              fieldType === 'CHECKBOX' ? (e.target as HTMLInputElement).checked : e.target.value,
          });
        }}
        {...props}
      />
    </ElementContainer>
  );
}

export function Elements({ data, metaData }: FormComponentProps) {
  const { init } = useFormStore();

  useEffect(() => {
    init(data);
  }, [data, init]);

  return (
    <>
      <div className="mt-2 grid gap-2 gap-x-4 md:grid md:grid-cols-2 lg:grid-cols-3">
        {(Object.keys(omit(metaData, ['comment'])) as Array<keyof MetaObject>).map((name) => (
          <RenderElement key={name} {...get(metaData, name)} name={name} />
        ))}
      </div>
      <RenderElement {...get(metaData, 'comment')} fieldType="TEXTAREA" name="comment" />
    </>
  );
}
