import styled from "@emotion/styled"
import { css } from "@emotion/css"
import { memo, useState } from "react"
import { useTranslation } from "react-i18next"
import Icon from "@aet/icons/macro"
import { FileInput } from "~/vendor/react-files-drag-and-drop"
import { FileView } from "./FileView"
import { Exporter } from "./Exporter"
import { color, token } from "~/options/theme"

export const ImporterTab = memo<{
  className?: string
}>(({ className }) => {
  const { t } = useTranslation()
  const [file, setFile] = useState<File | null>(null)

  return (
    <div className={className}>
      <FormEntry>
        <Exporter />
      </FormEntry>

      <FormEntry>
        <FileInput
          extensions={[".json"]}
          onError={() => {}}
          onUpload={x => setFile(x[0])}
          label={file ? file.name : null}
        >
          {({ dragging, labelId }) =>
            dragging ? (
              <Label htmlFor={labelId} className="dragging">
                <Icon icon="BsHourglassTop" className={iconClass} />
                {t("import.waiting")}
              </Label>
            ) : (
              <Label htmlFor={labelId}>
                <Icon icon="TbDragDrop" className={iconClass} />
                {t("import.dragFileHere")}
              </Label>
            )
          }
        </FileInput>
      </FormEntry>

      {file != null && (
        <FormEntry>
          <FileView file={file} />
        </FormEntry>
      )}
    </div>
  )
})

const FormEntry = styled.div`
  margin-top: 12px;
  margin-bottom: 12px;
`

const Label = styled.label`
  background: ${token.canvas.overlay};
  border: 1px solid ${token.border.muted};
  border-radius: 5px;
  display: block;
  padding: 8px 12px;
  width: 100%;
  text-align: center;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
  &.dragging {
    background-color: ${color("#bbb", "#303746")};
  }
`

const iconClass = css`
  margin-bottom: -3px;
  display: inline-block;
  font-size: 1.2em;
  margin-right: 4px;
`
