import React, { useEffect, useState } from "react";
import { LazyLoad } from "@/components/LazyLoad";

import { CustomSelect } from "@/components/CustomSelect";
import { ResponseEntries } from "@/components/ResponseEntries";
import { ApiResponseModelEntries } from "@/components/ApiResponseModelEntries";

const statusCodes = {
  200: "OK",
  201: "Created",
  204: "No Content",
};

const SuccessResponseConfig = ({
  workflow,
  variables,
  onSetData,
  open,
}) => {
  const [responseHeaders, setResponseHeaders] = useState([
    { key: "", value: "" },
  ]);
  const [responseBody, setResponseBody] = useState([]);
  const [selectedStatusCode, setSelectedStatusCode] = useState("200 - OK");
  const [responseModel, setResponseModel] = useState([]);

  useEffect(() => {
    onSetData("response_headers", responseHeaders);
  }, [responseHeaders]);

  useEffect(() => {
    onSetData("response", responseBody);
  }, [responseBody, responseBody?.length]);

  useEffect(() => {
    onSetData("response_model", responseModel);
  }, [responseModel, responseModel?.length]);

  useEffect(() => {
    onSetData("status_code", selectedStatusCode);
  }, [selectedStatusCode]);

  useEffect(() => {
    if (workflow?.response_headers && workflow?.response_headers.length) {
      setResponseHeaders(workflow?.response_headers);
    }
    if (workflow?.response && workflow?.response.length) {
      setResponseBody(workflow?.response);
    }
    if (workflow?.response_model && workflow?.response_model.length) {
      setResponseModel(workflow?.response_model);
    }
    if (workflow?.status_code) {
      setSelectedStatusCode(workflow?.status_code);
    }
  }, [workflow?.response_headers, workflow?.response, workflow?.response_model, workflow?.status_code]);




  return (
    <div className="scrollbar-hide ">
      <div className="my-4">
        <label className="mb-2 block text-sm font-bold text-gray-700">
          API Status Code
        </label>
        <CustomSelect
          className="w-full border p-2"
          initialValue={selectedStatusCode}
          onSelectedChange={(value) => setSelectedStatusCode(value)}
          options={Object.keys(statusCodes).map(
            (key) => `${key} - ${statusCodes[key]}`
          )}
          showBorder
        />
      </div>
      <div>
        <label className="block text-sm font-bold text-gray-700">
          Response Body
        </label>
        <LazyLoad>
          <ResponseEntries
            entries={responseBody}
            setEntries={setResponseBody}
            variables={variables}
            open={open}
          />
           <ApiResponseModelEntries
            entries={responseModel}
            setEntries={setResponseModel}
          />
        </LazyLoad>
      </div>
    </div>
  );
};

export default SuccessResponseConfig;
