import React, { useEffect, useState } from "react";
import "./Routes.css";
import SectionHeader from "../../layouts/SectionHeader";
import CButton from "../../components/CButton";
import { useTranslation } from "react-i18next";
import GoogleMapReact from "google-map-react";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../stores/store";
import { getRouteHistory } from "../../stores/slices/dataSlice";
import CMarker from "../../components/CMarker";
import { GOOGLE_MAPS_API_KEY } from "../../constants/constants";

const Routes: React.FC = () => {
  const [fromDate, setFromDate] = useState("");
  const [fromTime, setFromTime] = useState("");
  const [toDate, setToDate] = useState("");
  const [toTime, setToTime] = useState("");
  const [mapCenter, setMapCenter] = useState({
    lat: 37.33,
    lng: -122,
  });

  const { selectedDevice } = useAppSelector((state: RootState) => state.device);
  const { routeHistory, isRouteHistoryLoading } = useAppSelector(
    (state: RootState) => state.data
  );
  const dispatch = useAppDispatch();
  const { t } = useTranslation();

  useEffect(() => {
    if (selectedDevice) {
      const now = new Date();
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 1);

      setFromDate(yesterday.toISOString().slice(0, 10));
      setFromTime("00:00");
      setToDate(now.toISOString().slice(0, 10));
      setToTime("23:59");

      dispatch(
        getRouteHistory({
          deviceId: selectedDevice.id,
          dateFrom: yesterday,
          dateTo: now,
          recStart: 0,
          recLimit: 1000,
        })
      );
    }
  }, [dispatch, selectedDevice]);

  useEffect(() => {
    if (routeHistory.length > 0) {
      const lat = Number(routeHistory[0]?.location.lat);
      const lng = Number(routeHistory[0]?.location.lon);
      if (!isNaN(lat) && !isNaN(lng)) {
        setMapCenter({ lat, lng });
      }
    } else {
      setMapCenter({ lat: 37.33, lng: -122 });
    }
  }, [routeHistory]);

  const handleSearch = () => {
    if (!selectedDevice) return;

    const dateFrom = new Date(`${fromDate}T${fromTime}`);
    const dateTo = new Date(`${toDate}T${toTime}`);

    dispatch(
      getRouteHistory({
        deviceId: selectedDevice.id,
        dateFrom,
        dateTo,
        recStart: 0,
        recLimit: 1000,
      })
    );
  };

  return (
    <div className="routes wrapper">
      <SectionHeader to="/home" />

      <div className="routes__content">
        <div style={{ height: "67vh", width: "100%" }}>
          <GoogleMapReact
            bootstrapURLKeys={{
              key: GOOGLE_MAPS_API_KEY,
            }}
            center={mapCenter}
            defaultZoom={12}
            options={{ disableDefaultUI: true }}
          >
            {routeHistory.length > 0 && (
              <CMarker
                lat={Number(routeHistory[0]?.location.lat)}
                lng={Number(routeHistory[0]?.location.lon)}
              />
            )}
          </GoogleMapReact>
        </div>

        <div className="routes__filter">
          <p className="routes__filter__title">{t("common.selectTime")}</p>

          <div className="routes__filter__dates">
            <div className="routes__filter__date">
              <label htmlFor="from">{t("common.from")}</label>
              <div>
                <input
                  type="date"
                  id="from"
                  value={fromDate}
                  onChange={(e) => setFromDate(e.target.value)}
                />
                <input
                  type="time"
                  id="from-time"
                  value={fromTime}
                  onChange={(e) => setFromTime(e.target.value)}
                />
              </div>
            </div>

            <div className="routes__filter__date">
              <label htmlFor="to">{t("common.to")}</label>
              <div>
                <input
                  type="date"
                  id="to"
                  value={toDate}
                  onChange={(e) => setToDate(e.target.value)}
                />
                <input
                  type="time"
                  id="to-time"
                  value={toTime}
                  onChange={(e) => setToTime(e.target.value)}
                />
              </div>
            </div>
          </div>

          <CButton
            title={t("button.search")}
            onClick={handleSearch}
            isLoading={isRouteHistoryLoading}
          />
        </div>
      </div>
    </div>
  );
};

export default Routes;
