import React, { useCallback, useMemo, useState } from "react";
import useSWR from "swr";
import axios from "axios";
import type { AxiosResponse } from "axios";
import type { SWRResponse } from "swr/dist/types";
import { ifElse } from "ramda";
import { getRequestPrefix } from "./config";
import { concatRequestParams } from "./helpers";
import { notification } from "@atomintl/aui-next";
import { AES } from "../utils";
import { getItem } from "../utils/useCookie";

const getToken = () => {
  return getItem("token") || "";
};

const token = `Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJBVE9NSU5UTCIsInVpZCI6OTcyMDE5NzksImlhdCI6MTY2Nzk4MjM4NywiZXhwIjoxNjY4MDY4Nzg3fQ.kmFPJ5K6dp3xmwWyIy-V03iy4i-q4Cw_UOMEzpdsn548wgPiMB4khGTuhgiXuTpzNAoRa7S4cKjs07BslRmotLYImhhkgccdCy4zernknTfaVNr8kF2PpmcQU3wf3wMs3GybC8BjF1ngC_u28nZwWbLvsvushl9AInDZF56gwn3nEq5cPkfvkHn8OcapLAmkWr-23QovQqFhcp3mINoocoFoMZal2oG58LFIWRZz0wHq4OtL8FEK3JyFWILyovqzbfo4iPwZkRFRSx1DZYa8UsmF5E7gVPdhHuiyef3U_7YI0C2sfjazvYT98k94e13C_au8XNVKIgCtsxXapJIjRQ`;

export const AxiosInst = () =>
  axios.create({
    timeout: 20000,
    headers: {
      authorization: token,
      // authorization: `Bearer ${AES.instance.aesDecrypt(getToken())}`,
      "accept-language": `zh-TW`,
      source: `web`
    }
  });

export interface SWRConfigProps {}
export function useQuery(url: string, params?: any, swrConfig?: SWRConfigProps) {
  const { data: responseData, error } = useSWR<SWRResponse | AxiosResponse>(
    `${getRequestPrefix(url)}${url}${concatRequestParams(params)}`,
    AxiosInst().get,
    {
      focusThrottleInterval: 3600 * 1000,
      refreshInterval: 3600 * 1000,
      errorRetryInterval: 60 * 1000,
      errorRetryCount: 3,
      shouldRetryOnError: false,
      revalidateOnFocus: false,
      ...swrConfig
    }
  );

  return useMemo(() => {
    const loading = !responseData;
    const data = ifElse(
      () => responseData?.data?.code === "1",
      () => responseData?.data?.data,
      () => {
        responseData?.data?.message &&
          notification.warning({
            message: responseData?.data?.message,
            placement: "topRight"
          });
        return [];
      }
    )();

    return [data, loading, error];
  }, [responseData, error]);
}

export const usePost = (url: string, payload?: any) => {
  const [data, setData] = useState<React.SetStateAction<any>>({ data: null, error: null, isLoading: false });

  const callApi: CallableFunction = useCallback(() => {
    setData((prevState: any) => ({ ...prevState, isLoading: true }));
    AxiosInst()
      .post(`${getRequestPrefix(url)}${url}`, payload)
      .then(responseData => {
        if (responseData.data?.code === "1") {
          setData({ data: responseData.data, isLoading: false, error: null });
        } else {
          responseData.data?.message &&
            notification.warning({
              message: responseData.data?.message,
              placement: "topRight"
            });
        }
      })
      .catch(error => {
        setData({ data: null, isLoading: false, error });
      });
  }, [url, payload]);

  return [data, callApi];

  // const { data: responseData, error } = useSWR<SWRResponse | AxiosResponse>(
  //   `${getRequestPrefix(url)}${url}`,
  //   AxiosInst().post
  // );
  //
  // return useMemo(() => {
  //   const loading = !!responseData;
  //   const data = ifElse(
  //     () => responseData?.data?.code === "1",
  //     () => responseData?.data?.data,
  //     () => null
  //   )();
  //
  //   return [data, loading, error];
  // }, [responseData, error]);
};

export const useMutation = () => {};
