import './sncf.scss'
import {useParams, useSearchParams} from "react-router-dom"
import TrainsTable from "./TrainsTable"
import {useEffect, useState} from "react";

function DateTimeSelector({date, time}) {
  return <>
    <form>
      <div className="form-group row">
        <div className="col-sm-2">
          Modifier la date et l'heure de recherche
        </div>
        <label htmlFor="date" className="col-sm-1 col-form-label">Date</label>
        <div className="col-sm-1">
          <input type="date" name="date" className="form-control" id="date" defaultValue={date} />
        </div>
        <label htmlFor="time" className="col-sm-1 col-form-label">Heure</label>
        <div className="col-sm-1">
          <input type="time" name="time" className="form-control" id="time" defaultValue={time} />
        </div>
        <div className="col-sm-1">
          <button type="submit" className="btn btn-primary">Rechercher</button>
        </div>
      </div>
    </form>
  </>
}

function Station() {
  let {stopId} = useParams()
  let [stop, setStop] = useState({'name': "Chargement…"})
  let [searchParams, setSearchParams] = useSearchParams()
  const now = new Date()
  let dateNow = now.toISOString().split('T')[0]
  let timeNow = now.toTimeString().split(' ')[0].substring(0, 5)
  let [date, setDate] = useState(searchParams.get('date') || dateNow)
  let [time, setTime] = useState(searchParams.get('time') || timeNow)

  useEffect(() => {
    fetch(`http://localhost:8000/api/gtfs/stop/${stopId}/`)
      .then(response => response.json())
      .then(data => {
        setStop(data)
      })
  }, [stopId])

  return (
    <div className="Station">
      <header className="App-header">
        <h1>Horaires en gare de {stop.name}</h1>
      </header>

      <main>
        <DateTimeSelector date={date} time={time} />
        <TrainsTable stop={stop} date={date} time={time} tableType="departures" />
        <TrainsTable stop={stop} date={date} time={time} tableType="arrivals" />
      </main>
    </div>
  )
}

export default Station;
