import React, { useState, useEffect } from "react";
import { DataTypes } from "@/utils/options/DataTypes";
import { getDefaultResponseValueByType } from "@/utils/options/DataTypes";
import { generateUUID } from "@/utils/utils";

const EndpointResponse = ({ endpoint, onResponseChange }) => {
  const [key, setKey] = useState("");
  const [parent, setParent] = useState("");
  const [valueType, setValueType] = useState("");
  const [error, setError] = useState("");
  const [generatedObject, setGeneratedObject] = useState([]);

  const getDefaultResponse = () => {
    return [
      {
        id: generateUUID(),
        key: "error",
        value: false,
        valueType: "Boolean",
        parent: null,
      },
      {
        id: generateUUID(),
        key: "message",
        value: "Operation successful",
        valueType: "String",
        parent: null,
      },
    ];
  };
  const handleAddEntry = () => {
    if (!key || !valueType) {
      setError("Please fill in all fields.");
      return;
    }
    const entry = {
      id: generateUUID(),
      key,
      value: getDefaultResponseValueByType(valueType),
      valueType,
      parent,
    };

    setGeneratedObject((prevObject) => [...prevObject, entry]);
    setKey("");
    setParent("");
    setValueType("");
    setError("");
    onResponseChange([...generatedObject, entry]);
  };

  const handleRemoveEntry = (id) => {
    let updatedObject = [];
    setGeneratedObject((prevObject) => {
      updatedObject = prevObject.filter((obj) => obj.id != id);
      return updatedObject;
    });
    onResponseChange(updatedObject);
  };

  useEffect(() => {
    setGeneratedObject(
      typeof endpoint.response === "string"
        ? getDefaultResponse()
        : endpoint.response
    );
  }, []);

  const renderResponse = (generatedObject, parent = "") => {
    let items = generatedObject.filter((go) => go.parent == parent);

    let response = (
      <div className={` ${parent != "" ? "pl-4" : ""} `}>
        {items.map((obj, index) => (
          <div key={index}>
            <span>{obj.key}</span>:
            <span>
              {obj.valueType == "Object"
                ? renderResponse(generatedObject, obj.id)
                : obj.value}
            </span>{" "}
            <span className="text-xs uppercase">({obj.valueType})</span>
            <button
              onClick={() => handleRemoveEntry(obj.id)}
              className="ml-2 text-red-500"
            >
              Remove
            </button>
          </div>
        ))}
      </div>
    );

    return response;
  };

  return (
    <div className="space-y-4 bg-blue-50 p-4">
      <input
        type="text"
        value={key}
        onChange={(e) => setKey(e.target.value)}
        placeholder="Key"
        className="w-full rounded border border-blue-500 p-2"
      />

      <select
        value={valueType}
        onChange={(e) => setValueType(e.target.value)}
        className="w-full rounded border border-blue-500 p-2"
      >
        <option value="">Value Type</option>
        {DataTypes.map((type, index) => {
          return (
            <option key={index} value={type}>
              {type}
            </option>
          );
        })}
      </select>
      <select
        value={parent}
        onChange={(e) => setParent(e.target.value)}
        className="w-full rounded border border-blue-500 p-2"
      >
        <option value={null}> Select Parent </option>
        {generatedObject
          .filter((obj) => obj.valueType.toLowerCase() == "object")
          .map((obj, index) => {
            return (
              <option key={index} value={obj.id}>
                {obj.key}
              </option>
            );
          })}
      </select>
      {error && <div className="text-red-500">{error}</div>}
      <button
        onClick={handleAddEntry}
        className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
      >
        Add Entry
      </button>
      <div className="mt-8">
        <h2 className="hidden text-lg font-bold">Generated Object</h2>
        <div>{renderResponse(generatedObject)}</div>
      </div>
    </div>
  );
};

export default EndpointResponse;
