import { FC, useEffect, useState } from 'react'
import styles from './SectionShare.module.css'
import { Heading } from '../../shared/Heading'
import { Paragraph } from '../../shared/Paragraph/Paragraph'
import { Button } from '../../shared/Button/Button'
import cx from 'classnames'
import typography from '../../../styles/typography.module.css'
import { download, streamToArrayBuffer } from '../../../src/download'
import { I18n } from '../../shared/I18n/I18n'
import { Input } from '../../shared/Input/Input'
import { Section } from '../../shared/Section/Section'
import { useGroups } from '../../contexts/GroupProvider'

export const SectionShare: FC = () => {
  const { store, load } = useGroups()

  const [location, setLocation] = useState('')
  useEffect(() => {
    setLocation(window.location.href)
  }, [])

  return (
    <Section color={'primary'}>
      <div className={styles.shareGrid}>
        <div>
          <Heading type={'section'}>
            <I18n id={'page.home.share.download.title'} />
          </Heading>
          <Paragraph size={'medium'}>
            <I18n id={'page.home.share.download.description'} />
          </Paragraph>
          <Button
            className={cx(styles.downloadBtn, typography.bodyLarge)}
            onClick={() => {
              download('factorio-microservices.bin', store())
            }}
          >
            <I18n id={'page.home.pref.download'} />
          </Button>
          <label className={styles.uploadInput}>
            <I18n id={'page.home.share.download.upload_text'} />
            <input
              type={'file'}
              multiple={false}
              onChange={async evt => {
                const stream = evt.currentTarget.files?.[0].stream() as
                  | globalThis.ReadableStream<Uint8Array>
                  | undefined
                if (stream) {
                  const array = await streamToArrayBuffer(stream)
                  load(array)
                  evt.currentTarget.value = null as unknown as string
                }
              }}
            />
          </label>
        </div>
        <div>
          <Heading type={'section'}>
            <I18n id={'page.home.share.link.title'} />
          </Heading>
          <Paragraph size={'medium'}>
            <I18n id={'page.home.share.link.description'} />
          </Paragraph>
          <Paragraph size={'medium'}>
            <strong>
              <I18n id={'page.home.share.link.warning'} />
            </strong>
          </Paragraph>
          <Input
            className={styles.shareInput}
            readOnly={true}
            value={location}
            onClick={e => e.currentTarget.select()}
          />
        </div>
      </div>
    </Section>
  )
}
