import gql from "gql-tag";
import { useParams } from "react-router-dom";
import type { Request } from "../types";
import { useQuery } from "urql";
import { JsonViewer } from "@textea/json-viewer";

const requestQuery = gql`
  query RequestQuery($id: ID) {
    requests(where: { id: $id }) {
      success
      message
      requests {
        id
        callType
        url
        method
        body
        headers
        timestamp
        response {
          id
          statusCode
          body
          headers
          timestamp
        }
      }
    }
  }
`;

export function Request() {
  const params = useParams();

  const [result] = useQuery({
    query: requestQuery,
    variables: { id: params.requestId },
  });

  const request =
    (result?.data?.requests?.requests || [])[0] || ({} as Request);

  return (
    <div>
      <div className="border-b border-gql-vis-grey-2 p-5">
        <h2 className="text-2xl text-center font-bold text-gql-vis-darkblue">
          {request?.id}
        </h2>
      </div>

      <div className="d-flex">
        <div className="border-gql-vis-grey-2 p-5">
          <h3 className="text-2xl font-bold text-gql-vis-darkblue">Request</h3>
          <JsonViewer
            theme={"auto"}
            value={{ ...request, response: undefined }}
            indentWidth={2}
          />
        </div>
        <div className="border-gql-vis-grey-2 p-5">
          <h3 className="text-2xl font-bold text-gql-vis-darkblue">Response</h3>
          <JsonViewer
            theme={"auto"}
            value={request?.response || {}}
            indentWidth={2}
          />
        </div>
      </div>
    </div>
  );
}
