import {useParams, useSearchParams} from "react-router-dom"
import TrainsTable from "./TrainsTable"
import {useEffect, useState} from "react";
import {Box, Button, FormControl, FormControlLabel, FormGroup, FormLabel} from "@mui/material";
import {DatePicker, DateTimePicker, TimePicker} from "@mui/x-date-pickers";
import dayjs from "dayjs";

function DateTimeSelector({date, time}) {
  return <>
    <Box component="form" display="flex" alignItems="center" sx={{'& .MuiTextField-root': { m: 1, width: '25ch' },}}>
        <FormLabel>
          Modifier la date et l'heure de recherche :
        </FormLabel>
        <DatePicker name="date" label="Date" format="YYYY-MM-DD" defaultValue={dayjs(`${date}`)} />
        <TimePicker name="time" label="Heure" format="HH:mm" defaultValue={dayjs(`${date} ${time}`)} />
        <Button type="submit">Rechercher</Button>
    </Box>
  </>
}

function Station() {
  let {stopId} = useParams()
  let [stop, setStop] = useState({'name': "Chargement…"})
  let [searchParams, _setSearchParams] = useSearchParams()
  const now = new Date()
  let dateNow = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
  let timeNow = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
  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])

  if (time === timeNow) {
    setInterval(() => {
      const now = new Date()
      let dateNow = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
      let timeNow = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
      setDate(dateNow)
      setTime(timeNow)
    }, 60000)
  }

  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;
