import styled from "@emotion/styled"
import type { ItemSection } from "opvault.js"
import { useCallback, useState } from "react"
import { useTranslate } from "../../i18n"
import { useItemFieldContextMenu } from "../ItemFieldContextMenu"
import { Container } from "./Container"
import { useCopy } from "./hooks"

const OTPItemContainer = styled(Container)`
  margin: 5px 0;
`

const OTPItem = ({ children }: { children: string }) => {
  const { onRightClick } = useItemFieldContextMenu()
  const onCopy = useCopy(children)

  return (
    <OTPItemContainer onContextMenu={onRightClick} onClick={onCopy} style={{}}>
      {children}
    </OTPItemContainer>
  )
}

const ItemCount = styled(Container)`
  opacity: 0.5;
  user-select: none;
`

export const OTP: React.FC<{
  field: Pick<ItemSection.Concealed, "v">
}> = ({ field }) => {
  const t = useTranslate()
  const [show, setShow] = useState(false)

  const { onRightClick, ContextMenuContainer, Item } = useItemFieldContextMenu()
  const onToggle = useCallback(() => setShow(x => !x), [])
  const fields = field.v.split(" ")

  return (
    <>
      {show ? (
        <div
          onContextMenu={onRightClick}
          onDoubleClick={() => setShow(x => !x)}
          style={{
            fontFamily: "var(--monospace)",
            paddingTop: 5,
          }}
        >
          {fields.map((item, i) => (
            <OTPItem key={i}>{item}</OTPItem>
          ))}
        </div>
      ) : (
        <ItemCount onContextMenu={onRightClick} onClick={onToggle}>
          {fields.length} {fields.length === 1 ? t.noun.item : t.noun.items}
        </ItemCount>
      )}
      <ContextMenuContainer>
        <Item onClick={onToggle}>{show ? t.action.hide : t.action.show}</Item>
      </ContextMenuContainer>
    </>
  )
}
