import React, { useState, useEffect } from "react";
import EndPointLogic from "./EndpointLogic";
import { DataTypes } from "@/utils/options/DataTypes";
import EndpointResponse from "./EndpointResponse";
import Toggle from "react-toggle";

const RightPanel = ({
  selectedEndpoint,
  selectedField,
  onFieldChange,
  actions,
  roles,
}) => {
  const [fieldValue, setFieldValue] = useState(null);
  const [numInputs, setNumInputs] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [selectedAction, setSelectedAction] = useState(null);
  const [actionInputValues, setActionInputValues] = useState([]);

  useEffect(() => {
    if (selectedEndpoint) {
      setFieldValue(selectedEndpoint[selectedField]);
    }
  }, [selectedField]);

  const handleInputChange = (event) => {
    const newValue = event.target.value;
    setFieldValue(newValue);
    onFieldChange(selectedField, newValue);
  };

  const handleCodeEditorInputChange = (value) => {
    setFieldValue(value);
    onFieldChange(selectedField, value);
  };

  const handleRouteProtectedInputChange = (event) => {
    onFieldChange("protected", event.target.checked);
  };

  const handleAddAuthorizedRole = (event) => {
    let roles =
      Array.isArray(selectedEndpoint.authorizedRoles) &&
        selectedEndpoint.authorizedRoles.includes(event.target.value)
        ? selectedEndpoint.authorizedRoles
        : [...(selectedEndpoint.authorizedRoles ?? []), event.target.value];
    onFieldChange("authorizedRoles", roles);
    event.target.value = "";
  };

  const handleRemoveAuthorizedRole = (role) => {
    let roles = selectedEndpoint.authorizedRoles.filter((r) => r != role);
    onFieldChange("authorizedRoles", roles);
  };

  const handleAddInput = () => {
    // Add a new input object to the inputs array
    onFieldChange(`inputs`, [
      ...selectedEndpoint.inputs,
      {
        name: "",
        type: "query",
        rules: "",
      },
    ]);
  };

  const handleResponseChange = (value) => {
    onFieldChange(`response`, value);
  };
  const handleRemoveInput = (inputIndex) => {
    // Add a new input object to the inputs array
    let remainingInputs = selectedEndpoint.inputs.filter(
      (input, index) => inputIndex !== index
    );
    onFieldChange(`inputs`, [...remainingInputs]);
  };

  const onInputsChange = (inputIndex, field, value) => {
    selectedEndpoint.inputs = selectedEndpoint.inputs.map((input, index) => {
      if (index === inputIndex) {
        input[field] = value;
        return input;
      }
      return input;
    });
    onFieldChange(`inputs`, [...selectedEndpoint.inputs]);
  };

  const handleActionInputChange = (inputIndex, value) => {
    setActionInputValues((prev) => {
      prev[inputIndex] = value;
      return prev;
    });
  };

  const handleActionInputSave = () => {
    setFieldValue(
      (prev) =>
        ` ${typeof prev !== "undefined" ? prev : ""
        }  \n ${selectedAction.template(...actionInputValues)} `
    );
    onFieldChange(selectedField, fieldValue);
    setSelectedCategory(null);
    setSelectedAction(null);
  };

  return (
    <div className="grow space-y-3 overflow-y-auto">
      <div className="relative mb-3 flex min-h-[41px] items-center border-b  border-gray-300 bg-white px-8 py-2">
        <div>Configuration</div>
        <div className="ml-auto w-[8%] pl-3">
          {/* <button className="peer p-1 rounded-md border border-[#E0E0E0]">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path fill-rule="evenodd" clip-rule="evenodd" d="M7.9999 2.3999C8.44173 2.3999 8.7999 2.75807 8.7999 3.1999V7.1999H12.7999C13.2417 7.1999 13.5999 7.55807 13.5999 7.9999C13.5999 8.44173 13.2417 8.7999 12.7999 8.7999H8.7999V12.7999C8.7999 13.2417 8.44173 13.5999 7.9999 13.5999C7.55807 13.5999 7.1999 13.2417 7.1999 12.7999V8.7999H3.1999C2.75807 8.7999 2.3999 8.44173 2.3999 7.9999C2.3999 7.55807 2.75807 7.1999 3.1999 7.1999H7.1999V3.1999C7.1999 2.75807 7.55807 2.3999 7.9999 2.3999Z" fill="#8D8D8D" />
            </svg>
          </button>
          <div className="absolute hidden flex-col items-start justify-between gap-2 z-20  rounded-lg border border-[#a8a8a8] bg-white p-2 text-sm text-[#525252] shadow-md hover:flex focus:flex peer-focus:flex peer-focus-visible:flex whitespace-nowrap">
            <button
              className="flex items-center justify-start cursor-pointer text-left rounded-md px-4 py-3 hover:bg-[#F4F4F4] hover:text[#262626] w-full"
              onClick={onEndpointAdd}
            >
              <div className="flex items-center gap-2">
                <PlusIcon className="mr-1 h-5 w-5 " />
                Add Endpoint
              </div>
            </button>
            <button
              className="flex items-center justify-start cursor-pointer text-left rounded-md px-4 py-3 hover:bg-[#F4F4F4] hover:text[#262626] w-full"
              onClick={e => setShowAddLambdaModal(true)}
            >
              <div className="flex items-center gap-2">
                <PlusIcon className="mr-1 h-5 w-5 " />
                Add Lambda
              </div>
            </button>
          </div> */}
        </div>
      </div>

      <div className="mx-3 mb-4 rounded-md border border-[#E0E0E0] bg-white px-5 py-3">
        {selectedEndpoint && (
          <div className='p-4 space-y-3'>
            <p className="font-medium mb-2">{selectedField && selectedField.toUpperCase()}</p>
            {(selectedField === 'name' || selectedField === 'route') && (
              <input
                type="text"
                value={fieldValue}
                onChange={handleInputChange}
                className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
              />
            )}

            {selectedField === "route" && (
              <>
                <Toggle
                  className="mr-3 h-5 w-9 text-primaryBlue"
                  // defaultChecked={props[key]}
                  checked={selectedEndpoint.protected}
                  onChange={handleRouteProtectedInputChange}
                  icons={false}
                />
                <label htmlFor="" className="ml-5 font-medium capitalize">
                  Protected
                </label>

                <br />
                {selectedEndpoint.protected && <div>
                  <div className='flex items-center my-2'>
                    {selectedEndpoint.authorizedRoles?.map((role, index) => (
                      <span key={index} className='flex items-center gap-1 mr-2 uppercase text-sm font-medium'>
                        <span className='mr-1' >{role}</span>
                        <span onClick={() => handleRemoveAuthorizedRole(role)} className='font-bold cursor-pointer'>
                          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                            <path d="M15 5L5 15M5 5L15 15" stroke="#A8A8A8" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                        </span>
                      </span>
                    ))}
                  </div>
                  <select
                    className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
                    onChange={(e) => handleAddAuthorizedRole(e)}
                  >
                    <option value="">Select Authorized Roles</option>
                    {roles.map((role, index) => (
                      <option key={index}>{role}</option>
                    ))}
                  </select>
                </div>
                }
              </>
            )}

            {selectedField === "method" && (
              <select
                value={fieldValue}
                onChange={handleInputChange}
                className="mb-2 w-full rounded border border-gray-400 px-2 py-1"
              >
                <option value="GET">GET</option>
                <option value="POST">POST</option>
                <option value="PUT">PUT</option>
                <option value="PATCH">PATCH</option>
                <option value="DELETE">DELETE</option>
              </select>
            )}

            {selectedField === "response" && (
              <EndpointResponse
                onResponseChange={(value) => handleResponseChange(value)}
                fieldValue={fieldValue}
                endpoint={selectedEndpoint}
              />
            )}

            {selectedField === "logic" && (
              <EndPointLogic
                selectedEndpoint={selectedEndpoint}
                selectedCategory={selectedCategory}
                setSelectedCategory={setSelectedCategory}
                selectedAction={selectedAction}
                setSelectedAction={setSelectedAction}
                handleInputChange={handleInputChange}
                handleActionInputChange={handleActionInputChange}
                handleActionInputSave={handleActionInputSave}
                actions={actions}
                fieldValue={fieldValue}
                setFieldValue={setFieldValue}
                onFieldChange={onFieldChange}
                handleCodeEditorInputChange={handleCodeEditorInputChange}
              />
            )}

            {selectedField === "functionStack" && (
              <textarea
                cols={30}
                rows={10}
                value={fieldValue}
                onChange={handleInputChange}
                className="mb-2 w-full rounded border border-gray-400 px-2 py-1"
              />
            )}

            {selectedField === "inputs" && (
              <div className="overflow-y-auto">
                {selectedEndpoint.inputs.map((input, index) => (
                  <div key={index} className="mb-2 space-y-3">
                    <div className="flex justify-between">
                      <label className="font-medium">Input {index + 1}</label>
                      <button onClick={() => handleRemoveInput(index)}>
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none">
                          <path fillRule="evenodd" clipRule="evenodd" d="M6.3199 4.16666C6.90053 2.7025 8.32902 1.66666 10.0007 1.66666C11.6725 1.66666 13.1009 2.7025 13.6816 4.16666H17.7083C18.0535 4.16666 18.3333 4.44649 18.3333 4.79166C18.3333 5.13684 18.0535 5.41666 17.7083 5.41666H16.6276L15.8823 16.9689C15.8328 17.7363 15.196 18.3333 14.427 18.3333H5.57293C4.80396 18.3333 4.16713 17.7363 4.11762 16.9689L3.37232 5.41666H2.29163C1.94645 5.41666 1.66663 5.13684 1.66663 4.79166C1.66663 4.44649 1.94645 4.16666 2.29163 4.16666H6.3199ZM7.71797 4.16666C8.19942 3.41479 9.04236 2.91666 10.0007 2.91666C10.9591 2.91666 11.8021 3.41479 12.2835 4.16666H7.71797ZM8.74996 8.95833C8.74996 8.61315 8.47014 8.33333 8.12496 8.33333C7.77978 8.33333 7.49996 8.61315 7.49996 8.95833V13.5417C7.49996 13.8868 7.77978 14.1667 8.12496 14.1667C8.47014 14.1667 8.74996 13.8868 8.74996 13.5417V8.95833ZM11.875 8.33333C12.2201 8.33333 12.5 8.61315 12.5 8.95833V13.5417C12.5 13.8868 12.2201 14.1667 11.875 14.1667C11.5298 14.1667 11.25 13.8868 11.25 13.5417V8.95833C11.25 8.61315 11.5298 8.33333 11.875 8.33333Z" fill="#A8A8A8" />
                        </svg>
                      </button>
                    </div>
                    <div className="mt-4 flex flex-col space-y-3">
                      <label className="font-medium">Input name</label>
                      <input
                        type="text"
                        value={input.name}
                        onChange={(event) =>
                          onInputsChange(index, `name`, event.target.value)
                        }
                        placeholder="name"
                        className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
                      />

                      <label className="font-medium">Input type</label>
                      <select
                        value={input.type}
                        onChange={(event) =>
                          onInputsChange(index, `type`, event.target.value)
                        }
                        className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
                      >
                        <option value="query">Query</option>
                        <option value="body">Body</option>
                        <option value="path">Path/Param</option>
                        <option value="multipart">
                          Multipart (File Upload)
                        </option>
                      </select>

                      <label className="font-medium">Data type</label>
                      <select
                        value={input.dataType}
                        onChange={(event) =>
                          onInputsChange(index, `dataType`, event.target.value)
                        }
                        className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
                      >
                        {DataTypes.map((type, index) => {
                          return (
                            <option key={index} value={type}>
                              {type}
                            </option>
                          );
                        })}
                      </select>

                      <label className="font-medium">Validation Rules</label>
                      <input
                        type="text"
                        value={input.rules}
                        onChange={(event) =>
                          onInputsChange(index, `rules`, event.target.value)
                        }
                        placeholder="Validations rules ==> required|string"
                        className="w-full rounded-md border border-[#C6C6C6] bg-white px-3 py-2 shadow-sm"
                      />
                    </div>
                  </div>
                ))}
                <button
                  type="button"
                  onClick={handleAddInput}
                  className="mb-2 rounded border border-gray-400 px-2 py-1"
                >
                  Add Input
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default RightPanel;
