import { useState } from 'preact/hooks'
import { Box } from '../atoms/box.js'
import { Button } from '../atoms/button.js'
import { Heading } from '../atoms/heading.js'
import { Input } from '../atoms/input.js'
import { RichText } from '../atoms/rich-text.js'
import { Asset } from '../molecules/asset.js'
import disableTransparency from '../shared/disable-transparency.js'
import h from '../shared/h.js'
import { NAVIGATION_SEARCH } from '../shared/icons.js'
import t from '../shared/t.js'
import { ValidationError } from '../routing/error-handler.js'

export function ExternalSearch ({ _model, _color, ...props }) {
  const { image, links, title, text } = _model
  if (!text || !title || links.length === 0) {
    throw new ValidationError()
  }

  const [value, setValue] = useState('')
  const firstLink = links[0]
  const hasAsset = image.src

  const inputProps = {
    type: 'search',
    placeholder: firstLink.name,
    title: t('Enter your search term'),
    onInput: event => setValue(event.target.value),
    value
  }

  const buttonProps = {
    _textless: true,
    _model: {
      name: t('Submit'),
      icon: NAVIGATION_SEARCH
    },
    type: 'submit',
    onClick: event => {
      event.preventDefault()
      const url = firstLink.value + encodeURIComponent(value)
      globalThis.location.href = url
    }
  }

  const form = h('form', {
    action: firstLink.value,
    className: `lg:rounded-xl bg-bga text-txa ${disableTransparency(_color)}`,
    children: h(Box,
      h(Heading, { _level: 3 }, title),
      h(RichText, text),
      h('div', { className: 'flex space-x-5' },
        h('div', { className: 'grow' },
          h(Input, inputProps)
        ),
        h('div', { className: 'shrink' },
          h(Button, buttonProps)
        )
      )
    )
  })

  if (!hasAsset) {
    return h('div', { ...props, className: 'rounded-2xl overflow-hidden w-full' }, form)
  }

  return h('div', { ...props, className: 'relative overflow-hidden rounded-2xl' },
    h(Asset, { _model, role: 'presentation' }),
    h('div', { className: 'lg:absolute lg:top-6 lg:start-0 lg:end-0 lg:grid lg:grid-cols-12 gap-x-5' },
      h('div', { className: 'lg:col-start-2 lg:col-span-10' }, form)
    )
  )
}
