import { useParams, useLocation } from "react-router-dom";
import { useEffect, useState } from "react";

import { ResultsApi, Search } from "@/types/types";
import Loading from "@/components/Loading";
import NoResults from "@/components/NoResults";
import SearchResults from "@/components/SearchResults";

import classes from "./resultspage.module.css";

type Results = ResultsApi | undefined;

const ResultsPage = () => {
  const APIADDRESS = import.meta.env.VITE_APIADDRESS;
  const APIKEY = import.meta.env.VITE_APIKEY;

  //Data for API Call and Result
  const { search, page } = useParams();
  const [results, setResults] = useState<Results>();
  const location = useLocation();

  //Handlers for Movie Modal Opening and Closing
  const [open, setOpen] = useState<boolean>(false);
  const [id, setId] = useState<string | undefined>("");
  const [movieSelected, setMovieSelected] = useState<Search | undefined>();

  const handleOpen = (ID: string | undefined, movie: Search) => {
    setOpen(true);
    setId(ID);
    setMovieSelected(movie);
  };
  const handleClose = () => setOpen(false);

  async function handleGetResults() {
    let endpoint: string = "";

    if (page === "0" || page === undefined) {
      //default is 1 anyway but just in case someone wants to change parameters
      endpoint = `${APIADDRESS}?s=${search}&apikey=${APIKEY}`;
    } else {
      endpoint = `${APIADDRESS}?s=${search}&page=${page}&apikey=${APIKEY}`;
    }

    const reply = await fetch(`${endpoint}`);
    const data = await reply.json();
    setResults(data);
  }

  useEffect(() => {
    handleGetResults();
  }, [location]);

  return (
    <div className={classes.container}>
      {results === undefined ? (
        <Loading />
      ) : results.Response === "False" ? (
        <NoResults searchQuery={search} />
      ) : (
        <SearchResults
          searchQuery={search}
          results={results}
          page={page}
          open={open}
          openHandler={handleOpen}
          closeHandler={handleClose}
          id={id}
          movieSelected={movieSelected}
        />
      )}
    </div>
  );
};

export default ResultsPage;
