import { Component } from 'preact'
import h from '../shared/h.js'
import { isPublish } from '../shared/wcm-mode.js'
import { Annotation } from './annotation.js'

import { ARROW_TAIL_RIGHT } from '../shared/icons.js'
import PLACEHOLDER_IMAGE from './placeholder-image.svg'

const LINK_SRC = 'about:blank'
const PLACEHOLDER_CONTENT = {
  title: 'Lorem ipsum dolor sit',
  date: '2000-01-01T00:00:00.000Z',
  text:
    'Nunc lobortis mattis aliquam faucibus purus in massa tempor nec. ' +
    'Morbi enim nunc faucibus a. ' +
    'Nascetur ridiculus mus mauris vitae ultricies leo. ' +
    'Aliquam ultrices sagittis orci a scelerisque purus semper. ' +
    'Urna condimentum mattis pellentesque id nibh tortor id aliquet lectus.',
  image: {
    src: `data:image/svg+xml;utf-8,${encodeURIComponent(PLACEHOLDER_IMAGE)}`
  },
  links: [
    { name: 'Nunc lobortis', value: LINK_SRC, icon: ARROW_TAIL_RIGHT },
    { name: 'Volutpat ', value: LINK_SRC, icon: ARROW_TAIL_RIGHT },
    { name: 'Purus in massa', value: LINK_SRC, icon: ARROW_TAIL_RIGHT }
  ],
  tags: [
    { name: 'Fermentum', value: '#' },
    { name: 'Turpis egestas', value: '#' },
    { name: 'Dignissim cras tincidunt ', value: '#' }
  ]
}

export class ValidationError extends Error {}

export class ErrorHandler extends Component {
  state = { isValid: true }

  componentDidCatch (error) {
    if (error instanceof ValidationError) {
      this.setState({ isValid: false })
    }
  }

  render () {
    if (this.state.isValid) {
      return this.props.children
    }

    if (isPublish) {
      return null
    }

    const Organism = this.props.children.type
    const organismProps = this.props.children.props

    return h('div', { className: 'relative h-full' },
      h(Annotation, 'Placeholder'),
      h('div', { className: 'h-full opacity-50', 'data-placeholder': '' },
        h(Organism, { ...organismProps, _model: PLACEHOLDER_CONTENT })
      )
    )
  }
}
