import { useContext, useId, useRef } from 'react'

import { PktButton } from '../../button/Button'
import { TFileAttributes, FileItem, PktFileUploadContext, TQueueItemOperation } from '../types'

const RENAME_SYMBOL = Symbol('renameFile')

const RenameFile = (props: { value: string | undefined; onSave: (newName: string) => void; onCancel: () => void }) => {
  const inputRef = useRef<HTMLInputElement>(null)
  const inputId = useId()

  const save = () => {
    props.onSave(inputRef.current?.value ?? '')
  }

  return (
    <>
      <label htmlFor={inputId} className="pkt-sr-only">
        Endre filnavn
      </label>
      <input
        id={inputId}
        ref={inputRef}
        type="text"
        autoFocus
        defaultValue={props.value}
        className="pkt-fileupload__queue-display__item__rename-input"
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            e.preventDefault()
            e.stopPropagation()
            save()
          }
          if (e.key === 'Escape') {
            e.preventDefault()
            e.stopPropagation()
            props.onCancel()
          }
        }}
      />
      <PktButton skin="secondary" size="small" onClick={() => props.onSave(inputRef.current!.value)}>
        Lagre
      </PktButton>
      <PktButton skin="tertiary" size="small" onClick={props.onCancel}>
        Avbryt
      </PktButton>
    </>
  )
}

const RenameHiddenInput = (props: { targetFilename: string }) => {
  const context = useContext(PktFileUploadContext)
  return <input type="hidden" name={`${context.name}-targetFilename`} value={props.targetFilename} />
}

export const renameFileOperation = (attributes: TFileAttributes): TQueueItemOperation => {
  const targetFilenameAttribute = attributes<string>('targetFilename')
  return {
    title: 'Rediger',
    ariaLabel: 'Rediger filnavn',
    renderInlineUI: (fileItem: FileItem, closeOperationUi: () => void) => (
      <RenameFile
        value={targetFilenameAttribute.get(fileItem.fileId) || undefined}
        onSave={(newName: string) => {
          targetFilenameAttribute.set(fileItem.fileId, newName)
          closeOperationUi()
        }}
        onCancel={closeOperationUi}
      />
    ),
    renderHidden: (fileItem: FileItem) => (
      <RenameHiddenInput
        key={`rename${fileItem.fileId}`}
        targetFilename={targetFilenameAttribute.get(fileItem.fileId) || fileItem.file.name}
      />
    ),
    symbol: RENAME_SYMBOL,
  }
}
