import './SelectTimeZoneDefault.scss'
import { Select, Option } from 'components/Select'
import React, { useState } from 'react'
import momentTZ from 'moment-timezone'
import { TIME_ZONE_DATA } from 'redux/Common/types'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'

interface Props {
  className?: string
  selectClassName?: string
  defaultValue?: string
  onChange?: (value: string) => void
}

const SelectTimeZoneDefault: React.FC<Props> = ({
  className,
  selectClassName,
  defaultValue,
  onChange
}) => {
  const { t } = useTranslation()
  const [selectedTimeZone, setTimeZone] = useState(momentTZ.tz.guess())

  useEffect(() => {
    if (!defaultValue) return
    momentTZ.tz.setDefault(defaultValue)
    setTimeZone(defaultValue)
  }, [defaultValue])

  const onChangeTimezone = (value: string) => {
    momentTZ.tz.setDefault(value)
    setTimeZone(value)
    onChange && onChange(value)
  }

  return (
    <React.Fragment>
      <div className={classNames('timezone-wrapper', className)}>
        <Select
          value={selectedTimeZone}
          className={classNames('timezone-wrapper__select', selectClassName)}
          onSelect={onChangeTimezone}
        >
          {TIME_ZONE_DATA.map(timezoneGroup =>
            timezoneGroup.data.map(timezone => (
              <Option key={timezone.sectionId} value={timezone.tz}>
                {`${timezone.sectionId === 1 ? timezone.tx : t(timezone.tx)} 
                (${momentTZ().tz(timezone.tz).format('HH:mm')})`}
              </Option>
            ))
          )}
        </Select>
      </div>
    </React.Fragment>
  )
}

export default SelectTimeZoneDefault
