import React, { useCallback, useRef } from 'react';
import { SilkeSchemaFields } from '../silke-schema-fields';
import { SilkeTextField } from '../../silke-text-field';
import { FieldRegisterModel, FormObjectProvider } from '../../silke-form/form-context';
import { SilkeText } from '../../silke-text';
import { SilkeBox } from '../../silke-box';
import { SilkeButton } from '../../silke-button';
import { generateTitle } from './utils';
import { VevProps } from '@vev/utils';

type Props = {
  selected: number;
  value: any[];
  schema: VevProps | string;
  disabled?: boolean;
  onChange: (value: any[]) => void;
  onDelete: () => void;
  onClose: () => void;
};

export function ArrayFieldInline({
  value,
  disabled,
  selected,
  schema,
  onChange,
  onDelete,
  onClose,
}: Props) {
  const valueRef = useRef<any>(value);
  const fieldRefs = useRef<any>({});

  const registerField = useCallback((name: any, v: FieldRegisterModel) => {
    fieldRefs.current[name] = v;
  }, []);

  return (
    <SilkeBox column bg="neutral-5">
      <SilkeBox pad="s" vAlign="center">
        <SilkeBox hPad="s" vPad="s" flex>
          <SilkeText weight="strong">
            {generateTitle(value[selected], schema) || 'Untitled'}
          </SilkeText>
        </SilkeBox>
        <SilkeButton icon="delete" disabled={disabled} kind="ghost" onClick={onDelete} />
        <SilkeButton icon="close" kind="ghost" onClick={onClose} />
      </SilkeBox>
      <SilkeBox hPad="m" gap="m" column vAlign="center">
        {typeof schema === 'string' ? (
          <SilkeTextField
            value={(selected !== undefined && value[selected]) || ''}
            type={(schema as any).of}
            onChange={(val: string) => {
              const update = value || [];
              update[selected] = val;
              onChange(update);
            }}
          />
        ) : (
          <FormObjectProvider
            errors={{}}
            valueRef={valueRef}
            value={value[selected] || {}}
            validate={() => {}}
            onChange={(name, update) => {
              value[selected] = {
                ...value[selected],
                [name]: update,
              };
              onChange(value);
            }}
            register={registerField}
          >
            <SilkeSchemaFields
              schema={[schema]}
              value={(selected && value[selected]) || {}}
              noPad
              disabled={disabled}
              itemIndex={selected}
            />
          </FormObjectProvider>
        )}
      </SilkeBox>
    </SilkeBox>
  );
}
