import { useState } from "react";

import { ApiRoute } from "@/utils/type";
import axios from "@/utils/axios";

import { Endpoint } from "./endpoint";
import { Request } from "./request";
import { Response } from "./response";
import { useRequest } from "./hooks/useRequest";
import { useMount, useUpdateEffect } from "react-use";

export const EditorMain = ({
  collections,
  endpoint,
  onCollections,
  onEndpoint,
}: {
  collections: string[];
  endpoint: ApiRoute;
  onCollections: (collections: string[]) => void;
  onEndpoint: (endpoint: ApiRoute) => void;
}) => {
  const [formattedEndpoint, setFormattedEndpoint] = useState<string>(
    endpoint.path
  );
  const [formattedParameters, setFormattedParameters] = useState(
    endpoint?.parameters ? { ...endpoint.parameters } : undefined
  );
  const { loading, submit, data } = useRequest(
    formattedEndpoint,
    formattedParameters
  );

  useMount(() => {
    if (
      endpoint?.path &&
      endpoint?.method === "GET" &&
      !endpoint?.path?.includes("{") &&
      !endpoint?.path?.includes("}")
    ) {
      submit();
    }
  });

  useUpdateEffect(() => {
    if (endpoint?.path) {
      setFormattedEndpoint(endpoint.path);
    }
  }, [endpoint.path]);

  useUpdateEffect(() => {
    if (endpoint?.parameters) {
      setFormattedParameters(endpoint.parameters);
    }
  }, [endpoint.parameters]);

  return (
    <div className="flex-1 bg-slate-900/50 h-[calc(100%-56px)]">
      <div className="h-full grid grid-cols-2">
        <Request
          parameters={formattedParameters}
          onChange={(k: string, v: string | boolean) => {
            setFormattedParameters({
              ...formattedParameters,
              [k]: v,
            });
          }}
        >
          <Endpoint endpoint={endpoint}>
            <button
              className="bg-indigo-500 hover:bg-indigo-500/80 text-white px-3 py-1 rounded-lg text-sm"
              onClick={submit}
            >
              Send
            </button>
          </Endpoint>
        </Request>
        <Response res={data} loading={loading} />
      </div>
    </div>
  );
};
