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

import { getDisplayFilename } from 'shared-utils/fileupload'

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

interface IRenameFileProps {
  initialValue: string
  disabled: boolean
  onSave: (newName: string) => void
  onCancel: () => void
}

const RenameFile = ({ initialValue, disabled, onSave, onCancel }: IRenameFileProps) => {
  const inputRef = useRef<HTMLInputElement>(null)
  const inputId = useId()

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

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

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

const resolveCurrentName = (context: TQueueOperationContext) =>
  context.getAttribute<string>('targetFilename') || getDisplayFilename(context.file, '')

export const renameFileOperation: TQueueItemOperation = {
  id: 'rename',
  title: 'Rediger',
  ariaLabel: 'Rediger filnavn',
  renderInlineUI: (context) => (
    <RenameFile
      initialValue={resolveCurrentName(context)}
      disabled={context.disabled}
      onSave={(newName: string) => {
        const trimmed = newName.trim()
        if (trimmed) context.setAttribute('targetFilename', trimmed)
        context.close()
      }}
      onCancel={context.close}
    />
  ),
  renderHidden: (context) => <RenameHiddenInput key={`rename${context.file.fileId}`} targetFilename={resolveCurrentName(context)} />,
}
