import { PrivateKey } from '@ethersphere/bee-js'
import { ReactElement, useState } from 'react'
import CheckDoubleLineIcon from 'remixicon-react/CheckDoubleLineIcon'
import ClipboardIcon from 'remixicon-react/FileCopyLineIcon'

import { uuidV4 } from '../../../../utils'
import { TOOLTIPS } from '../../constants/tooltips'
import { getSigner, setSignerPk } from '../../utils/common'
import { Button } from '../Button/Button'
import { Tooltip } from '../Tooltip/Tooltip'

import './PrivateKeyModal.scss'

type Props = { onSaved: () => void }

const generateNewPrivateKey = (): string => {
  const id = uuidV4()
  const signer = getSigner(id)

  return signer.toHex()
}

export function PrivateKeyModal({ onSaved }: Props): ReactElement {
  const [value, setValue] = useState(generateNewPrivateKey())
  const [confirmValue, setConfirmValue] = useState('')
  const [showError, setShowError] = useState(false)
  const [copied, setCopied] = useState(false)

  const handleCopyPrivateKey = async () => {
    try {
      await navigator.clipboard.writeText(value)
      setCopied(true)
    } catch {
      // eslint-disable-next-line no-console
      console.debug('Failed to copy private key to clipboard')
    }
  }

  const handleGenerateNew = () => {
    setValue(generateNewPrivateKey())
    setConfirmValue('')
    setCopied(false)
    setShowError(false)
  }

  const handleBlur = () => {
    if (!value.trim()) {
      return
    }

    try {
      new PrivateKey(value)
      setShowError(false)
    } catch {
      setShowError(true)
      setCopied(false)
    }
  }

  const handleSave = () => {
    try {
      new PrivateKey(value)
      setSignerPk(value)
      onSaved()
    } catch {
      setShowError(true)
    }
  }

  return (
    <div className="fm-initialization-modal-container">
      <div className="fm-modal-window">
        <div className="fm-modal-window-header">
          <div>Create Private Key</div>
          <Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_HEADER} />
        </div>

        <div className="fm-modal-window-scrollable">
          <div>This key grants access to this File Manager instance. Save it before continuing..</div>
          <div className="fm-modal-info-warning flex-column">
            <span className="fm-modal-info-warning-text-header">CRITICAL: Key Cannot Be Recovered</span>
            <span>
              Swarm does not store this key and <strong>cannot</strong> retrieve it. Loss of the key will result in
              permanent loss of access to this File Manager instance.
            </span>
          </div>
          <div className="fm-modal-window-body">
            <div className="fm-modal-window-input-container">
              <label htmlFor="fm-private-key" className="fm-emphasized-text fm-private-key-label">
                <span>1. New Private key</span>
                <button
                  onClick={handleGenerateNew}
                  type="button"
                  className="fm-generate-btn"
                  onMouseEnter={e => (e.currentTarget.style.background = '#e5e7eb')}
                  onMouseLeave={e => (e.currentTarget.style.background = '#f3f4f6')}
                >
                  Generate New
                </button>
              </label>

              <div className="fm-private-key-input-row">
                <input
                  id="fm-private-key"
                  type="text"
                  className={`fm-input${showError ? ' has-error' : ''} fm-private-key-input`}
                  autoComplete="off"
                  value={value}
                  onChange={e => {
                    setValue(e.target.value)
                    setCopied(false)
                    setShowError(false)
                  }}
                  onBlur={handleBlur}
                  spellCheck={false}
                />
                {
                  <button
                    className="fm-copy-btn"
                    onClick={handleCopyPrivateKey}
                    aria-label="Copy private key"
                    type="button"
                    title={copied ? 'Copied!' : 'Copy'}
                  >
                    {copied ? <CheckDoubleLineIcon size="16px" /> : <ClipboardIcon size="16px" />}
                  </button>
                }
                <Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_GENERATED_KEY} />
              </div>
              <div className="fm-input-hint-error">{showError ? 'Invalid private key.' : ''}</div>
            </div>

            <div className="fm-modal-window-input-container">
              <label htmlFor="fm-private-key-confirm" className="fm-emphasized-text fm-confirm-key-label">
                Confirm Private Key
              </label>
              <div className="fm-private-key-input-row">
                <input
                  id="fm-private-key-confirm"
                  type="text"
                  className="fm-input fm-confirm-key-input"
                  placeholder="Paste or type your private key again"
                  autoComplete="off"
                  value={confirmValue}
                  onChange={e => setConfirmValue(e.target.value)}
                  spellCheck={false}
                />
                <Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_CONFIRM_KEY} />
              </div>
              <div className="fm-input-hint fm-confirm-key-hint">
                {confirmValue && value === confirmValue
                  ? '✓ Private keys match!'
                  : 'Save the private key securely, then paste or type it again to confirm.'}
              </div>
            </div>
          </div>

          <div className="fm-modal-window-body">
            <div className="flex-row">
              <div>
                <b>Key Storage:</b>
              </div>
              <Tooltip label={TOOLTIPS.PRIVATE_KEY_MODAL_KEY_INFO} />
            </div>
            The key is saved only in this browser&apos;s local storage. If browser data is cleared, a different browser
            is used, or the OS is updated, this local copy might be deleted. The key will be required to access this
            File Manager instance after that.
          </div>
        </div>

        <div className="fm-modal-window-footer">
          <Button
            label="Save"
            variant="primary"
            onClick={handleSave}
            disabled={!value || !confirmValue || value !== confirmValue || showError}
          />
        </div>
      </div>
    </div>
  )
}

export default PrivateKeyModal
