import { XIcon } from "@/assets/svgs";
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={` flex w-fit flex-wrap items-center gap-2 p-1 text-sm text-primaryBlue`}
      >
        {items.map((obj, index) => (
          <div
            key={index}
            className={`${
              obj.valueType === "Object"
                ? " rounded-lg border border-[#525252] bg-[#f4f4f4]"
                : ""
            }`}
          >
            <div className="flex h-8 items-center justify-between gap-3 rounded-lg bg-[#f4f4f4] px-3 py-1 text-[#525252]">
              {obj.valueType !== "Object" && obj.parent && (
                <span className="mr-3">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="18"
                    height="18"
                    viewBox="0 0 18 18"
                    fill="none"
                  >
                    <path
                      d="M2.8125 3.5625V9.75C2.8125 10.5784 3.48407 11.25 4.3125 11.25H14.625M12.375 8.25L15.1098 10.9848C15.2563 11.1313 15.2563 11.3687 15.1098 11.5152L12.375 14.25"
                      stroke="#A8A8A8"
                      strokeWidth="1.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </span>
              )}
              <div className="flex items-center gap-3">
                <span>
                  {obj.key}
                  {obj?.value && obj.valueType !== "Object" && `:${obj.value}`}
                </span>
                <span className="text-xs uppercase">({obj.valueType})</span>
              </div>

              <span
                onClick={() => handleRemoveEntry(obj.id)}
                className="cursor-pointer rounded-full p-1 hover:bg-[#e4e4e4]"
              >
                <XIcon />
              </span>
            </div>

            <div
              className={`${
                obj.valueType === "Object"
                  ? "ml-2 flex items-center gap-2"
                  : "hidden"
              }`}
            >
              {obj.valueType === "Object"
                ? renderResponse(generatedObject, obj.id)
                : null}
            </div>
          </div>
        ))}
      </div>
    );

    return response;
  };

  return (
    <div className="space-y-4 p-4">
      <input
        type="text"
        value={key}
        onChange={(e) => setKey(e.target.value)}
        placeholder="Key"
        className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
      />

      <select
        value={valueType}
        onChange={(e) => setValueType(e.target.value)}
        className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
      >
        <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-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
      >
        <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-primaryBlue px-4 py-2 text-white"
      >
        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;
