"use client";

import {
  FC,
  createContext,
  useContext,
  useReducer,
  useState,
  PropsWithChildren,
} from "react";
import { colors, typography } from "leafcutter-ui/styles/theme";

const basePath = process.env.GITLAB_CI
  ? "/link/link-stack/apps/leafcutter"
  : "";
const imageURL = (image: any) =>
  typeof image === "string" ? `${basePath}${image}` : `${basePath}${image.src}`;

const AppContext = createContext({
  colors,
  typography,
  imageURL,
  query: null as any,
  updateQuery: null as any,
  updateQueryType: null as any,
  replaceQuery: null as any,
  clearQuery: null as any,
  foundCount: 0,
  setFoundCount: null as any,
});

export const LeafcutterProvider: FC<PropsWithChildren> = ({ children }) => {
  const initialState = {
    incidentType: {
      display: "Incident Type",
      queryType: "include",
      values: [],
    },
    relativeDate: {
      display: "Relative Date",
      queryType: null,
      values: [],
    },
    startDate: {
      display: "Start Date",
      queryType: null,
      values: [],
    },
    endDate: {
      display: "End Date",
      queryType: null,
      values: [],
    },
    targetedGroup: {
      display: "Targeted Group",
      queryType: "include",
      values: [],
    },
    platform: {
      display: "Platform",
      queryType: "include",
      values: [],
    },
    device: {
      display: "Device",
      queryType: "include",
      values: [],
    },
    service: {
      display: "Service",
      queryType: "include",
      values: [],
    },
    maker: {
      display: "Maker",
      queryType: "include",
      values: [],
    },
    country: {
      display: "Country",
      queryType: "include",
      values: [],
    },
    subregion: {
      display: "Subregion",
      queryType: "include",
      values: [],
    },
    continent: {
      display: "Continent",
      queryType: "include",
      values: [],
    },
  };
  const reducer = (state: any, action: any) => {
    const key = action.payload?.[0];
    if (!key) {
      throw new Error("Unknown key");
    }
    const newState = { ...state };
    switch (action.type) {
      case "UPDATE":
        newState[key].values = action.payload[key].values;
        return newState;
      case "UPDATE_TYPE":
        newState[key].queryType = action.payload[key].queryType;
        return newState;
      case "REPLACE":
        return Object.keys(action.payload).reduce((acc: any, cur: string) => {
          if (["startDate", "endDate"].includes(cur)) {
            const rawDate = action.payload[cur].values[0];
            const date = new Date(rawDate);
            acc[cur] = {
              ...action.payload[cur],
              values: rawDate && date ? [date] : [],
            };
          } else {
            acc[cur] = action.payload[cur];
          }

          return acc;
        }, {});
      case "CLEAR":
        return initialState;
      default:
        throw new Error("Unknown action type");
    }
  };

  const [query, dispatch] = useReducer(reducer, initialState);
  const updateQuery = (payload: any) => dispatch({ type: "UPDATE", payload });
  const updateQueryType = (payload: any) =>
    dispatch({ type: "UPDATE_TYPE", payload });
  const replaceQuery = (payload: any) => dispatch({ type: "REPLACE", payload });
  const clearQuery = () => dispatch({ type: "CLEAR" });
  const [foundCount, setFoundCount] = useState(0);

  return (
    <AppContext.Provider
      // eslint-disable-next-line react/jsx-no-constructed-context-values
      value={{
        colors,
        typography,
        imageURL,
        query,
        updateQuery,
        updateQueryType,
        replaceQuery,
        clearQuery,
        foundCount,
        setFoundCount,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export function useLeafcutterContext() {
  return useContext(AppContext);
}
