import './SelectTimeZone.scss'
import React, { useCallback, useEffect, useState } from 'react'
import Dropdown from 'antd/lib/dropdown'
import cityTimezones, { CityData } from 'city-timezones'
import Menu from 'antd/lib/menu'
import Input from 'antd/lib/input'
import { ReactComponent as SearchIcon } from 'icons/search.svg'
import { ReactComponent as VectorDownIcon } from 'icons/vector-down.svg'
import { ReactComponent as VectorUpIcon } from 'icons/vector-up.svg'
import momentTZ from 'moment-timezone'

interface Props {
  disableChangeMommentTZ?: boolean
  defaultCity?: string
  defaultTimeZone?: string
  onChange?: (city: CityData) => void
}

const getCityData = (city: string) =>
  cityTimezones
    .findFromCityStateProvince(city)
    .filter(i => !!i.timezone)
    .sort((a, b) => (a.pop > b.pop ? -1 : 1))
    .slice(0, 20)

const SelectTimeZone: React.FC<Props> = ({
  disableChangeMommentTZ = false,
  defaultCity,
  defaultTimeZone,
  onChange
}) => {
  const [isOpenDropDown, setIsOpenDropDown] = React.useState(false)
  const [selectedCity, setSelectedCity] = useState<any>(null)
  const [selectedTimeZone, setTimeZone] = useState(momentTZ.tz.guess())
  const [searchCityOptions, setSearchCityOption] = useState(
    getCityData('America')
  )

  useEffect(() => {
    if (!defaultCity) return
    setSelectedCity(defaultCity)
  }, [defaultCity])

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

  const handleChangeTimezone = useCallback(
    (city: CityData) => {
      !disableChangeMommentTZ && momentTZ.tz.setDefault(city.timezone)
      setTimeZone(city.timezone)
      setSelectedCity(city.city)
      setIsOpenDropDown(false)
      onChange && onChange(city)
    },
    [disableChangeMommentTZ]
  )

  const updateSearchOptions = useCallback(
    value => setSearchCityOption(getCityData(value)),
    []
  )

  const menu = () => (
    <div className="menu-timezone">
      <div className="menu-timezone__search">
        <Input
          style={{ width: '100%', fontWeight: 600, position: 'sticky' }}
          placeholder="Search by City"
          prefix={<SearchIcon />}
          className="p__y--10"
          onChange={event => {
            const text = event?.currentTarget?.value
            if (text !== '') {
              updateSearchOptions(event?.currentTarget?.value)
            } else {
              updateSearchOptions('america')
            }
          }}
        />
      </div>
      <Menu className="menu-timezone__parent">
        {searchCityOptions.map(city => (
          <Menu.Item
            className="menu-timezone__item"
            key={`${city?.lat}${city?.lng}`}
          >
            <div
              onClick={() => handleChangeTimezone(city)}
              className="selection d--flex justify__content--between"
            >
              <span className="timezone-name">
                {`${city?.city}`} - {`${city?.iso3}`}
              </span>
              <span>{`(${momentTZ()
                .tz(city?.timezone)
                .format('HH:mm')})`}</span>
            </div>
          </Menu.Item>
        ))}
      </Menu>
    </div>
  )

  return (
    <React.Fragment>
      <div className="dropdown-timezone">
        <Dropdown
          overlayClassName="dropdown-timezone__overlay"
          placement="bottomCenter"
          overlay={menu}
          trigger={['click']}
          onVisibleChange={setIsOpenDropDown}
          visible={isOpenDropDown}
        >
          <div className="title">
            <span className="title-dropdown" onClick={e => e.preventDefault()}>
              {`${selectedCity || selectedTimeZone} (${momentTZ()
                .tz(selectedTimeZone)
                .format('HH:mm')})`}
            </span>
            {isOpenDropDown ? (
              <VectorDownIcon className="m__l--8 m__b--2 m__r--16" />
            ) : (
              <VectorUpIcon className="m__l--8 m__b--2 m__r--16" />
            )}
          </div>
        </Dropdown>
      </div>
    </React.Fragment>
  )
}

export default SelectTimeZone
