import BlockInputs from './BlockInputs'
import { TextInput } from '../../form'
import { TBlockInstance, TBlock } from '../types'
import theme from '../../styles/theme'
import { useState, useEffect, ChangeEvent } from 'react'
import { emptyBlock, countBlocksAndExercises } from '../utils'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChevronRight, faChevronDown } from '@fortawesome/free-solid-svg-icons'
import BlockSelector from './BlockSelector'

const BlockInstanceInputs = ({
  value,
  name,
  onChange,
  className = 'bi-fields',
}: {
  value: TBlockInstance
  name: string
  onChange: GenericEventHandler
  className?: string
}) => {
  const [show, setShow] = useState(true)
  const [source, setSource] = useState<'new' | 'existing'>()
  const [newItem, setNewItem] = useState(emptyBlock())
  const [existingItem, setExistingItem] = useState<undefined | TBlock>()

  function handleSourceChange(event: ChangeEvent<HTMLInputElement>) {
    const { target } = event
    if (target.value === 'new') {
      if (!value.block?.id.startsWith('++')) setExistingItem(value.block)
      setSource('new')
      onChange({ target: { type: 'custom', name: `${name}.block`, value: newItem } })
    } else if (target.value === 'existing') {
      if (value.block?.id.startsWith('++')) setNewItem(value.block)
      setSource('existing')
      onChange({ target: { type: 'custom', name: `${name}.block`, value: existingItem } })
    }
  }

  const [blocks, exercises] = countBlocksAndExercises(value.block)

  return (
    <fieldset className={className}>
      {!value.id.startsWith('++') && (
        <div className='bi-info'>
          <div>Block Instance ID{value.id}</div>
          <div>Created at:</div>
        </div>
      )}
      <TextInput
        name={`${name}.order`}
        label='Order'
        value={value.order}
        type='number'
        onChange={onChange}
        className='bi-order'
      />
      <TextInput
        name={`${name}.rounds`}
        label='Rounds'
        value={value.rounds}
        type='number'
        onChange={onChange}
        className='bi-rounds'
      />
      <TextInput
        name={`${name}.variation`}
        label='Variation'
        value={value.variation}
        onChange={onChange}
        className='bi-variation'
      />
      <div className='bi-block'>
        <FontAwesomeIcon
          icon={show ? faChevronDown : faChevronRight}
          height={16}
          onClick={() => setShow(!show)}
        />
        <input
          type='radio'
          name='source'
          id='source-new'
          value='new'
          checked={source === 'new'}
          onChange={handleSourceChange}
        />
        <label htmlFor='source-new'>New block</label>
        <input
          type='radio'
          name='source'
          id='source-existing'
          value='existing'
          checked={source === 'existing'}
          onChange={handleSourceChange}
        />
        <label htmlFor='source-existing'>Existing block</label>
        {value.block ? (
          <div>
            Block: {value.block.title ?? value.block.description?.substr(0, 50)}, sub blocks:{' '}
            {blocks}, exercises: {exercises}
          </div>
        ) : (
          <div>No block selected</div>
        )}

        {show &&
          (source === 'new' ? (
            <BlockInputs name={`${name}.block`} value={value.block} onChange={onChange} />
          ) : source === 'existing' ? (
            <BlockSelector
              name={`${name}.block`}
              value={value.block}
              label='Existing block'
              onChange={onChange}
            />
          ) : (
            <p>Please select a block</p>
          ))}
      </div>

      <style jsx>{`
        .bi-block > label,
        .bi-block > input[type='radio'] {
          display: inline;
          width: auto;
        }
        @media (min-width: ${theme.midsize}) {
          .${className} {
            display: grid;
            grid-template-areas:
              'info info info info'
              'order  rounds variation variation'
              'block  block  block block'
              'button button button button';
            grid-template-columns: repeat(4, 1fr);
          }

          .${className} :global(.bi-order) {
            grid-area: order;
          }
          .${className} :global(.bi-rounds) {
            grid-area: rounds;
          }
          .${className} :global(.bi-variation) {
            grid-area: variation;
          }
          .${className} :global(.bi-block) {
            grid-area: block;
          }
          .${className} :global(.bi-button) {
            grid-area: button;
          }
        }
      `}</style>
    </fieldset>
  )
}

export default BlockInstanceInputs
