import React, { FC, useEffect, useState } from 'react'
import {
  EnvironmentalData,
  PickupPoint as PickupPointData,
} from '../model/models'
import PickupPoint from '../components/PickupPoint'
import { __ } from '@wordpress/i18n'

export declare interface PickupPointProps {
  pickupPoints: Array<PickupPointData>
  serviceDescription: string
  environmentalData?: EnvironmentalData
  onSelect: (id: string) => void
  selectedPickupPoint?: string
  displayDistance?: boolean
}

const PickupPoints: FC<PickupPointProps> = ({
  pickupPoints,
  serviceDescription,
  environmentalData,
  selectedPickupPoint,
  onSelect,
  displayDistance,
}) => {
  const [availablePickupPoints, setAvailablePickupPoints] =
    useState<Array<PickupPointData>>()
  const [showMore, setShowMore] = useState<boolean>(false)

  useEffect(() => {
    if (pickupPoints && !showMore) {
      setAvailablePickupPoints(pickupPoints.slice(0, 5))
    } else if (showMore) {
      setAvailablePickupPoints(pickupPoints)
    }
  }, [pickupPoints, showMore])

  return (
    <div>
      {availablePickupPoints &&
        availablePickupPoints.map(pickupPoint => (
          <PickupPoint
            key={pickupPoint.id}
            pickupPoint={pickupPoint}
            checked={selectedPickupPoint === pickupPoint.id}
            onSelect={onSelect}
            displayDistance={displayDistance}
          />
        ))}
      {pickupPoints.length > 5 && !showMore && (
        <button onClick={() => setShowMore(true)} className="button__plain mll plxxs">
          {__('Show more', 'posten-bring-checkout')}
        </button>
      )}
      <p className="mtm service_description">{serviceDescription}</p>
      {environmentalData?.fossilFree && (
        <div className="environmental mtm">
          <img src={environmentalData.tagUrl} alt="" />
        </div>
      )}
    </div>
  )
}

export default PickupPoints
