import React, { useCallback, useState } from "react";
import { LazyLoad } from "@/components/LazyLoad";
import { MkdButton } from "@/components/MkdButton";
import { MkdControlledInput } from "@/components/MkdControlledInput";
import { CustomSelect } from "@/components/CustomSelect";
import {
  DataTypes,
  InputType,
  validationRules,
} from "@/utils/options/DataTypes";
import { MultiSelect } from "@/components/MultiSelect";
import { TrashIcon } from "@/assets/svgs";

const defaultData = {
  name: "",
  dataType: "",
};

const formatNumber = (number) => {
  const stringNumber = String(number);
  if (stringNumber.length > 1) {
    return `${number}`;
  }
  return `0${number}`;
};
const ApiResponseModelEntries = ({ entries, setEntries }) => {
  const [data, setData] = useState(defaultData);

  const [error, setError] = useState({
    name: { message: "" },
    dataType: { message: "" },
  });

  const handleAddEntry = () => {
    if ([data?.name, data?.dataType].includes("")) {
      if (!data?.name) {
        setError((prev) => ({
          ...prev,
          name: { message: "Name Cannot Be Empty" },
        }));
      }
      if (!data?.dataType) {
        setError((prev) => ({
          ...prev,
          dataType: { message: "Please Select a Data Type" },
        }));
      }

      return;
    }

    const tempData = {
      name: data?.name,
      dataType: data?.dataType,
    };

    setEntries((prev) => [...prev, tempData]);
    setData(() => defaultData);
    setShow(false);
  };

  const handlePropertyChange = useCallback(
    (field, value, position) => {
      const tempEntries = entries;
      tempEntries.splice(position, 1, {
        ...tempEntries[position],
        [field]: value,
      });
      setEntries(() => [...tempEntries]);
    },
    [entries]
  );

  const deleteEntry = useCallback(
    (position) => {
      const tempEntries = entries;
      tempEntries.splice(position, 1);
      setEntries(() => [...tempEntries]);
    },
    [entries]
  );

  const addProperty = useCallback(() => {
    const tempEntries = entries;
    tempEntries.push({ name: "", dataType: "" });
    setEntries(() => [...tempEntries]);
  }, [entries]);

  return (
    <>
      <div className=" ">
        <div className="mt-4 space-y-4">
          <h2 className="text-lg font-bold">API RESPONSE MODEL</h2>

          {entries && entries.length
            ? entries.map((entry, entryPosition) => (
                <div
                  key={entryPosition}
                  className="flex flex-col items-start gap-2 rounded-md border-2 border-primary-light p-2 shadow-md shadow-primaryBlue "
                >
                  <div className={`flex w-full items-center justify-between `}>
                    <code className="text-lg font-bold">
                      Property {formatNumber(entryPosition + 1)}
                    </code>
                    <button
                      onClick={() => deleteEntry(entryPosition)}
                      className={`w-fit self-end`}
                    >
                      <TrashIcon
                        className={`h-[1.5rem] w-[1rem] cursor-pointer text-red-500`}
                        fill="red"
                      />
                    </button>
                  </div>

                  <div className={`w-full flex-col items-end gap-2`}>
                    <div className={`relative grow `}>
                      <LazyLoad>
                        <MkdControlledInput
                          className={`relative mb-3`}
                          label={"Property Name"}
                          onChange={(e) =>
                            handlePropertyChange(
                              "name",
                              e.target.value,
                              entryPosition
                            )
                          }
                          value={entry?.name}
                          placeholder={`Property Name`}
                        />
                      </LazyLoad>
                    </div>

                    <div className={`relative grow `}>
                      <LazyLoad>
                        <CustomSelect
                          label={`Data Type`}
                          showBorder
                          initialValue={entry?.dataType}
                          options={DataTypes}
                          onSelectedChange={(value) =>
                            handlePropertyChange(
                              "dataType",
                              value,
                              entryPosition
                            )
                          }
                        />
                      </LazyLoad>
                    </div>
                  </div>
                </div>
              ))
            : null}
        </div>

        <div className="mt-5">
          <MkdButton className={`mb-2`} onClick={() => addProperty()}>
            Add Property
          </MkdButton>
          <button hidden onClick={handleAddEntry}>
            save
          </button>
        </div>
      </div>
    </>
  );
};

export default ApiResponseModelEntries;
