import classnames from 'classnames/bind';
import React from 'react';
import { SilkeBox } from '../silke-box';
import { SilkeIcon } from '../silke-icon';
import { SilkeSkeleton } from '../silke-skeleton';
import { useButtonContext } from './context';
import { SilkeButtonProps } from './silke-button';
import styles from './silke-button.scss';

const cl = classnames.bind(styles);

type SilkeFileSelectButtonProps = {
  accept?: string;
  multiple?: boolean;
  onSelect: (files: FileList) => any;
} & Omit<SilkeButtonProps, 'link' | 'onSelect'>;

export function SilkeFileSelectButton({
  accept,
  multiple,
  onSelect,
  label,
  kind,
  size,
  icon,
  focus,
  hover,
  className,
  loading,
  type = 'button',
  selected,
  ...rest
}: SilkeFileSelectButtonProps) {
  const context = useButtonContext();
  const iconOnly = icon && !label;

  size = size || context.size || 'base';
  className = cl('button', className, kind || context.kind || 'primary', size, {
    iconOnly,
    focus,
    hover,
    selected,
  });
  if (loading) rest.disabled = true;
  if (type === 'submit' && context.disableSubmit) rest.disabled = true;

  return (
    <SilkeBox
      {...(rest as any)}
      type={type}
      className={className}
      rounded={size === 's' ? 'tiny' : 'small'}
      gap="s"
      rel="button"
      tag="label"
    >
      <input
        type="file"
        style={{ height: 0, width: 0, position: 'absolute', opacity: 0 }}
        accept={accept}
        autoFocus={rest.autoFocus}
        maxLength={1024}
        multiple={multiple}
        onChange={(e) => e.currentTarget.files && onSelect(e.currentTarget.files)}
      />
      {loading && (
        <SilkeSkeleton
          style={{
            position: 'absolute',
            top: 0,
            right: 0,
            left: 0,
            bottom: 0,
            overflow: 'hidden',
            borderRadius: 'inherit',
          }}
        />
      )}
      {label}
      {icon && (
        <span className={styles.icon}>
          <SilkeIcon icon={icon} />
        </span>
      )}
    </SilkeBox>
  );
}
