import React, {memo} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useController} from 'react-hook-form';
import {Typography, FileCard} from '@components';
import {getFieldName} from '@shared/dynamicForms/utils';
import {useTheme} from '@shared/theme';
import {sizeToBytes} from '@shared/utils';
import {ComponentType} from '@shared/dynamicForms/interfaces';

import {styles} from './styles';
import {FormInputComponentProps} from './interfaces';
import {InputComponent} from './components/InputComponent';

function FormInputComponent({
  section,
  component,
  showRequireAsterisk,
  isFrozen,
}: FormInputComponentProps) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const name = getFieldName(section, component.nameId);
  const {fieldState} = useController({name});
  const isError = !!fieldState.error?.message;
  const textColor = isError
    ? theme.text.feedback.error
    : theme.text.neutral.default;

  const isAutocomplete = component.type === ComponentType.Autocomplete;
  const isInfo = component.type === ComponentType.Info;

  return (
    <View
      style={[
        styles.commonContainer,
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <Typography weight="semiBold" color={textColor}>
        {component.content.title}
        {showRequireAsterisk && !isAutocomplete && !isInfo
          ? component.content.required
            ? '*'
            : ` (${t('general.optional').toLowerCase()})`
          : null}
      </Typography>
      {!!component.attachments?.length && (
        <View style={styles.attachments}>
          {component.attachments?.map(attachment => (
            <FileCard
              id={attachment.id.toString()}
              key={attachment.key}
              name={attachment.name}
              path={attachment.url}
              url={attachment.url}
              size={sizeToBytes(attachment.size || '')}
              downloadWithAuthHeader
              showCheckIcon={false}
              showFileTypeIcon
            />
          ))}
        </View>
      )}
      <InputComponent name={name} component={component} isFrozen={isFrozen} />
    </View>
  );
}

export const FormInput = memo(FormInputComponent);
