import axios from "axios";
import { useEffect, useState } from "react";

const endpoints: Record<string, string> = {
  stats: "/api/stats",
  training: "/api/training"
};

export default function useFilterRecordsByUser<T extends any[]>(
  id?: string,
  shouldNotQuery?: boolean,
  recordType: string = 'stats'
) {
  type ElementType = T extends (infer U)[] ? U : never;

  const [data, setData] = useState<T>([] as unknown as T);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const endpointURL = endpoints[recordType] || endpoints.stats;
  // CAUTION: This makes the assumption that the record enpoint has a /user/${id} endpoint
  const endpoint = !id ? endpointURL: `${endpointURL}/user/${id}`;

  const getData = () => {
    if (shouldNotQuery) return;

    setIsLoading(true);
    setIsError(false);

    axios
      .get<T>(endpoint)
      .then((response) => {
        // CAUTION: This makes the assumption ElementType has a "user" field that contains the user id
        setData(response.data.filter((x: ElementType) => (id ? (x as any).user === id : true)) as T);
      })
      .catch(() => setIsError(true))
      .finally(() => setIsLoading(false));
  };

  useEffect(() => {
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id, shouldNotQuery, recordType, endpoint]);

  return { 
    data, 
    reload: getData, 
    isLoading, 
    isError
  };
}