// React
import React, { useEffect } from 'react'
import { Link, useLocation, useParams } from 'react-router-dom'

// Redux
import { useSelector, useDispatch } from 'react-redux'
import { actionCreators as weatherForecastsActionCreators, WeatherForecast, WeatherForecastsState } from '../store/reducers/WeatherForecasts'

interface IReduxState {
  weatherForecasts: WeatherForecastsState
}

type IParams = {
  startDateIndex: string
}

const FetchData = () => {
  const location = useLocation()
  const params = useParams<IParams>()

  const dispatch = useDispatch()
  const { startDateIndex,  forecasts, isLoading } = useSelector((state: IReduxState) => state.weatherForecasts)

  const ensureDataFetched = () => {
    dispatch(weatherForecastsActionCreators.requestWeatherForecasts(
      parseInt(params.startDateIndex ? params.startDateIndex : '0', 10)
    ))
  }

  // This method is called when the route parameters change
  useEffect(() => {
    ensureDataFetched()
  }, [location.pathname])

  const renderForecastsTable = () => {
    return <table className='table table-striped' aria-labelledby="tabelLabel">
      <thead>
        <tr>
          <th>Date</th>
          <th>Temp. (C)</th>
          <th>Temp. (F)</th>
          <th>Summary</th>
        </tr>
      </thead>
      <tbody>
        {forecasts.map((forecast: WeatherForecast) =>
          <tr key={forecast.date}>
            <td>{forecast.date}</td>
            <td>{forecast.temperatureC}</td>
            <td>{forecast.temperatureF}</td>
            <td>{forecast.summary}</td>
          </tr>
        )}
      </tbody>
    </table>
  }

  const renderPagination = () => {
    const prevStartDateIndex = (startDateIndex || 0) - 5
    const nextStartDateIndex = (startDateIndex || 0) + 5

    return <div className="d-flex justify-content-between">
      <Link className='btn btn-outline-secondary btn-sm' to={`/fetch-data/${prevStartDateIndex}`}>Previous</Link>
      {isLoading && <span>Loading...</span>}
      <Link className='btn btn-outline-secondary btn-sm' to={`/fetch-data/${nextStartDateIndex}`}>Next</Link>
    </div>
  }

  return <>
    <h1 id="tabelLabel">Weather forecast</h1>
    <p>This component demonstrates fetching data from the server and working with URL parameters.</p>
    { renderForecastsTable() }
    { renderPagination() }
  </>
}

export {
  FetchData
}