import Icon from "@aet/icons/macro"
import { memo, useMemo, useState } from "react"
import { css, cx } from "@emotion/css"
import { useEvent } from "@aet/hooks"
import { Modal } from "~/vendor/react-responsive-modal"
import { ListItem } from "../FileTree/FileItem"

export const AboutModal = memo<{
  as: React.ComponentType<{ onClick?: () => void; children: React.ReactNode }>
}>(({ as: As }) => {
  const [show, setShow] = useState(false)
  const [licenseData, setLicenseData] = useState<Record<string, string | null>>()
  const [selected, setSelected] = useState<string>()

  const onHide = useEvent((e?: React.MouseEvent) => {
    e?.stopPropagation()
    setShow(false)
  })
  const onShow = useEvent(async () => {
    setShow(true)

    if (licenseData == null) {
      const { default: data } = await import("../../../generated/licenses.json", {
        assert: { type: "json" },
      })
      setLicenseData(data)
      setSelected(Object.keys(data)[0])
    }
  })

  const keys = useMemo(() => Object.keys(licenseData ?? {}), [licenseData])

  return (
    <As onClick={onShow}>
      <Icon icon="VscInfo" />
      <Modal open={show} center onClose={onHide}>
        <div
          className={css`
            display: flex;
            > div {
              max-height: 80vh;
              overflow-y: auto;
            }
          `}
        >
          <div
            className={css`
              width: 220px;
              margin-right: 20px;
            `}
          >
            {keys.map(key => (
              <ListItem
                key={key}
                className={cx({
                  active: key === selected,
                })}
                onClick={() => setSelected(key)}
              >
                {key}
              </ListItem>
            ))}
          </div>
          <div
            className={css`
              width: 625px;
            `}
          >
            {selected != null && (
              <pre
                className={css`
                  line-height: 1.45;
                  margin: 0;
                  white-space: pre-wrap;
                `}
              >
                {licenseData?.[selected] ?? " "}
              </pre>
            )}
          </div>
        </div>
      </Modal>
    </As>
  )
})
