import React from 'react'
import get from 'lodash/fp/get'
import { Element, styled } from '@siteone/system-core'
import { Loading } from '@siteone/pagebuilder-components'
import { Button } from '@siteone/pagebuilder-ui'
import Files from './Files'

const LoadInProgress = styled(Element)`
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2;
`

const LoadInProgressModal = styled(Element)`
  border: 1px solid #ccc;
  width: 518px;
  
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);
  border-radius: 7px;
  background-color: #fff;
`

const Header = styled(Element)`
  padding: 22px;
  border-bottom: 1px solid #d3edff;
  background-color: #eaf7ff;
  h2 {
    color: #2b5672;
    margin-bottom: 10px;
  }
  strong {
    font-weight: bold;
  }
  p {
    color: #7a92a5;
  }
`

const Body = styled(Element)`
  max-height: 250px;
  width: 100%;
  overflow: auto;
`

const Bottom = styled(Element)`
  padding: 20px;
  border-top: 1px solid #ccc;
  color: #b6c1cd;
`

const getStatus = get('status')

const getCountUploadedFiles = (items, filesStatus) => items.reduce(
  (count, file) => (getStatus(filesStatus[file.name]) === 'ok' ? ++count : count),
  0
)

const fileListToArray = fileList => {
  let items = []
  // FileList to array
  for (var i = 0; i < fileList.length; i++) {
    items.push(fileList.item(i))
  }
  return items
}

/**
 * @param {FileList} files list of files (https://developer.mozilla.org/en-US/docs/Web/API/FileList)
 * @param {object} filesStatus {status: error | ok, uri: string}
 * @param {function} onConfirm close dialog
 * @param {boolean} done is upload done
 */
const UploadDialog = ({ files, filesStatus = {}, onConfirm, done }) => {
  // move file list to array list
  let items = fileListToArray(files)

  // count of successfully upload files
  const countUploadedFiles = getCountUploadedFiles(items, filesStatus)

  return (
    <LoadInProgress>
      <LoadInProgressModal>
        <Header>
          <h2>
            <strong>Nahráno</strong> {countUploadedFiles} / {items.length}{' '} souborů
          </h2>
          <p>Toto okno můžete zavřít i během nahrávání souborů</p>
        </Header>

        <Body>
          <Files items={items} filesStatus={filesStatus} />
        </Body>

        <Bottom display='flex' justifyContent='space-between' alignItems='center'>
          <div>
            {!!done && (
            <h3>Nahrávání {countUploadedFiles !== items.length ? 'ne' : ''}proběhlo úspěšně</h3>
          )}
          </div>
          <div>
            <Button label='Hotovo' variant='success' onClick={() => done && onConfirm()} />
          </div>
        </Bottom>

      </LoadInProgressModal>
    </LoadInProgress>
  )
}

export default UploadDialog
