import React, {useCallback} from 'react';
import {StyleProp, View, ViewStyle} from 'react-native';
import {CardContainer} from '@components/_HuGo/CardContainer';
import {FileActions, FileCard} from '@components/_HuGo/FileCard';
import {
  InputAccessibilities,
  InputCommonProps,
  InputCore,
  useInputController,
  UseInputControllerProps,
} from '@components/_HuGo/Inputs';
import {HuGoFile} from '@components/_HuGo/interfaces';

import {Layout, LayoutProps} from './components/Layout';
import {styles} from './styles';
import {UploaderInputs} from './components/Layout/interfaces';

type UploaderProps = InputCommonProps &
  InputAccessibilities &
  FileActions &
  LayoutProps & {
    files: HuGoFile[];
    variant?: 'input' | 'button';
    inputStyle?: StyleProp<ViewStyle>;
    inputs?: UploaderInputs[];
    maxAttachments?: number;
  };

export function Uploader({
  buttonTitle,
  canDownloadFile,
  description,
  disabled,
  files,
  helper,
  isError,
  inputStyle,
  label,
  multiFiles,
  onDeleteFile,
  onRetryUpload,
  onStopUpload,
  onPickFiles,
  showCheckIcon,
  title,
  validTypes,
  variant = 'input',
  layoutVariant = 'column',
  inputs,
  maxAttachments,
}: UploaderProps) {
  const isInputVariant = variant === 'input';
  const canUploadFiles = !!multiFiles || !files.length;
  const commonButtonProps = {
    buttonTitle,
    description,
    multiFiles,
    onPickFiles,
    title,
    validTypes,
    layoutVariant,
    inputs,
    maxAttachments,
  };

  const renderFile = useCallback(
    (file: HuGoFile) => (
      <FileCard
        {...file}
        canDownloadFile={canDownloadFile}
        key={file.id}
        onDeleteFile={onDeleteFile}
        onRetryUpload={onRetryUpload}
        onStopUpload={onStopUpload}
        showCheckIcon={showCheckIcon}
      />
    ),
    [canDownloadFile, onDeleteFile, onRetryUpload, onStopUpload, showCheckIcon],
  );

  return isInputVariant ? (
    <InputCore
      label={label}
      helper={helper}
      isError={isError}
      disabled={disabled}
      style={styles.gap}>
      {canUploadFiles && (
        <CardContainer style={[styles.container, inputStyle]}>
          <Layout {...commonButtonProps} isCenter showButton={!disabled} />
        </CardContainer>
      )}
      {files.map(renderFile)}
    </InputCore>
  ) : (
    <View style={styles.gap}>
      <Layout {...commonButtonProps} showButton={canUploadFiles && !disabled} />
      {files.map(renderFile)}
    </View>
  );
}

type UploaderControllerProps = Omit<UploaderProps, 'variant'> &
  UseInputControllerProps;

export function UploaderController({
  name,
  showSuccess,
  ...props
}: UploaderControllerProps) {
  const inputController = useInputController({name, showSuccess});

  return <Uploader {...props} {...inputController} variant="input" />;
}

export {
  UploaderValidTypes,
  DEFAULT_INPUTS,
  UploaderInputs,
} from './components/Layout/interfaces';
export {isDocumentsOnly} from './components/Layout/utils';
