
import { FormAbstract, FormArray, FormGroup } from '@websolutespa/bom-mixer-forms';
import { useLabel } from '@websolutespa/bom-mixer-hooks';
import styled from 'styled-components';
import { Divider, Grid, GridProps } from '../components';
import { FIELDS, FieldType, IFields } from './fields';

type FieldCollectionProps = {
  collection: FormGroup | FormArray;
  fields?: IFields;
  columProps?: (control: FormAbstract) => Partial<GridProps>;
};

const StyledGrid = styled(Grid)`
  flex-direction: column;
  align-items: flex-start;

  &:has(input[type=hidden]) {
    display: none;
  }
`;

function FieldCollectionItem({ control, fields }: {
  control: FormAbstract;
  fields?: IFields;
}) {
  const customFields = { ...FIELDS, ...fields };
  if (control instanceof FormGroup || control instanceof FormArray) {
    return <FieldCollection collection={control} fields={fields} />;
  } else {
    if (control.schema in customFields) {
      return customFields[control.schema as FieldType](control);
    } else {
      return customFields.text(control);
    }
  }
}

export function FieldCollection({
  collection,
  fields,
  columProps = (control) => ({
    xs: 12,
    sm: [
      'accept',
      'checkbox',
      'consent',
      'implicit',
      'textarea',
    ].includes(control.schema) ? 12 : 6,
  }),
}: FieldCollectionProps) {
  const label = useLabel();

  const controls = (collection instanceof FormGroup) ?
    Object.keys(collection.controls).map(key => {
      return { key, control: (collection as FormGroup).controls[key] };
    }) :
    collection.controls.map((control, i) => {
      return { key: i, control };
    });

  return (
    <>
      {collection.label &&
        <Grid xs={12}>
          <Divider>{label(collection.label)}</Divider>
        </Grid>
      }
      {controls.length > 0 && controls.map((item, i) => {
        const control = item.control;
        if (!control) {
          return;
        }
        if (control instanceof FormGroup || control instanceof FormArray) {
          return <FieldCollectionItem key={i} control={item.control} fields={fields} />;
        } else {
          return <StyledGrid key={i} {...columProps(control)}>
            <FieldCollectionItem control={item.control} fields={fields} />
          </StyledGrid>;
        }
      })}
    </>
  );
}

