// @flow
import cx from 'classnames'
import { Link } from 'found'
import sortBy from 'lodash/sortBy'
import React from 'react'
import { createFragmentContainer, graphql } from 'react-relay'

import style from './plantList.css'
import type { PlantList_viewer } from './__generated__/PlantList_viewer.graphql.js'

type Props = {
  display: 'list' | 'grid',
  viewer: PlantList_viewer,
}

const PlantList = ({ display, viewer }: Props) => {
  const { plants } = viewer

  if (!plants.edges.length) {
    return <div>No plants</div>
  }

  const displayClass = style[display || 'list']
  const sortedPlants = sortBy(plants.edges, 'node.name').map(({ node }) => {
    const Component = display === 'grid' ? PlantGridItem : PlantListItem
    return <Component key={node.id} plant={node} />
  })

  return (
    <div className={displayClass}>
      <ul className={cx(style.row, 'row')}>
        {sortedPlants}
      </ul>
    </div>
  )
}

const PlantListItem = ({ plant }) => {
  const { defaultPhoto, name, species } = plant
  const speciesName = species
    ? `${species.genus} ${species.epithet}`
    : 'Unknown species'
  const linkTo = `/plant/${plant.id}`

  return (
    <li className={style.listRow}>
      <div className={style.cell}>
        <Link className={style.name} to={linkTo}>
          {name}
        </Link>
      </div>
      <div className={style.cell}>
        <Link className={style.species} to={linkTo}>
          {speciesName}
        </Link>
      </div>
    </li>
  )
}

const PlantGridItem = ({ plant }) => {
  const { defaultPhoto, name, species } = plant

  const renderPhoto = () => {
    if (defaultPhoto) {
      return <img className={style.photo} src={defaultPhoto.url} />
    }
    return <div className={style.placeholder}>No image</div>
  }

  const backgroundImage = defaultPhoto ? `url(${defaultPhoto.url})` : null
  const speciesName = species
    ? `${species.genus} ${species.epithet}`
    : 'Unknown species'

  return (
    <li className="col-xs-6 col-sm-4 col-md-3">
      <Link to={`/plant/${plant.id}`} className={style.gridItem}>
        <div className={style.gridItemContainer}>
          <div className={style.image} style={{ backgroundImage }} />
          <div className={style.info}>
            <span className={style.name}>
              {name}
            </span>
            <div className={style.species}>
              {speciesName}
            </div>
          </div>
        </div>
      </Link>
    </li>
  )
}

export default createFragmentContainer(
  PlantList,
  graphql`
    fragment PlantList_viewer on Profile {
      plants: plantsByProfileId(first: 2147483647)
        @connection(key: "PlantList_plants") {
        edges {
          node {
            id
            defaultPhoto: mediaByDefaultPhotoId {
              url
            }
            name
            species: speciesBySpeciesId {
              family
              genus
              epithet
            }
          }
        }
      }
    }
  `
)
