import React, { FC, FormEvent, useState } from 'react';
import { Button, ErrorMessage, FormDropdown } from '@nova-hf/ui';
import { useDropzone } from 'react-dropzone';

import { useTranslation } from 'utils/i18n';
import { useUploadWalletCardsListMutation, useWalletCardsRegisteredQuery } from 'typings/graphql';
import LoadingPlaceholder from 'components/loading-placeholder/LoadingPlaceholder';

import s from './UploadList.module.scss';

interface IUploadListrops {
  onComplete(): void;
}

export const UploadList: FC<IUploadListrops> = ({ onComplete }) => {
  const { t } = useTranslation('cards');
  const [cardId, setCardId] = useState<string | undefined>(undefined);
  const { acceptedFiles, getRootProps, getInputProps } = useDropzone({
    accept: 'text/csv',
    onDragEnter: () => {
      setErrorMessage(undefined);
    },
  });
  const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
  const { data, loading: registeredLoading } = useWalletCardsRegisteredQuery();
  const [walletCardsUploadList, { loading }] = useUploadWalletCardsListMutation();

  const handleDropdownChange = (value: string) => {
    setCardId(value);
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    if (!cardId) {
      return;
    }

    try {
      const res = await walletCardsUploadList({
        variables: {
          input: { cardId, users: acceptedFiles[0] },
        },
      });

      if (res.data?.uploadWalletCardsList.uploadList?.success) {
        onComplete();
      }
    } catch (error) {
      if (error instanceof Error) {
        setErrorMessage(error.message);
      }
    }
  };

  return (
    <div className={s.uploadList}>
      {registeredLoading ? (
        <div className={s.uploadList__loading}>
          <LoadingPlaceholder size={32} width={200} />
          <LoadingPlaceholder width={150} />
          <LoadingPlaceholder width={250} />
        </div>
      ) : (
        <form onSubmit={handleSubmit}>
          <h2 className={s.uploadList__heading}>{t('subNavigation.uploadList')}</h2>

          {Boolean(errorMessage) && <ErrorMessage>{errorMessage}</ErrorMessage>}

          <FormDropdown onSelect={handleDropdownChange} label={t('shared.selectCard')}>
            {(data?.walletCardsRegistered.registered ?? []).map(({ cardId, name }) => (
              <option key={cardId} value={cardId}>
                {name}
              </option>
            ))}
          </FormDropdown>

          <label className={s.uploadList__label}>{t('shared.list')}</label>

          {acceptedFiles.length ? (
            <div className={s.uploadList__files}>
              {acceptedFiles.map((file: any) => (
                <p key={file.path}>
                  {file.path} - {file.size} bytes
                </p>
              ))}
            </div>
          ) : (
            <div {...getRootProps({ className: s.uploadList__dropzone })}>
              <input {...getInputProps()} />
              <p>{t('upload.copy')}</p>
            </div>
          )}

          <Button big loading={loading} type="submit" fill arrowRight>
            {t('shared.submit')}
          </Button>
        </form>
      )}
    </div>
  );
};
