"use client";
import { sendFormInputs } from "@/actions";
import { Button } from "@/components/ui/button";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { ImSpinner10 } from "react-icons/im";
import CustomInput from "./CoustomInput";
import SelectInputToAdd from "./SelectInputToAdd";
import { toastError, toastSuccess } from "@/services/custom-toast";

function generateUUID() {
  return crypto.randomUUID().substring(0, 9);
}

// ["input", "checkbox", "radio"]
export default function FormBuilder({ productId, initState }) {
  const [formInputs, setFormInputs] = useState(initState);
  const t = useTranslations("form_builder");
  const [isSubmitting, setIsSubmitting] = useState(false);
  //  to add a value into the text input the small text field or check box name and value fields
  const addInputData = (id, data) => {
    setFormInputs((c) =>
      c.map((input) =>
        input.id === id
          ? {
              ...input,
              ...Object.keys(data).reduce((acc, key) => {
                // Only add the field if the value is not undefined
                if (data[key] !== undefined) {
                  acc[key] = data[key];
                }
                return acc;
              }, {}),
            }
          : input
      )
    );
  };
  //  to add a new input field to the form like new small text new check boxes field
  const addInputFormHandler = (inputType) => {
    let newField = {
      inputType,
      fieldName: "",
      order: formInputs.length,
      placeHolder: "",
      // isRequired: 0,
      id: generateUUID(),
    };

    if (inputType === "checkbox" || inputType === "radio") {
      newField.options = [{ price: "", name: "", id: generateUUID() }];
    }

    setFormInputs((c) => {
      if (c.length > 0) {
        return [...c, newField];
      } else {
        return [newField];
      }
    });
  };

  // to add a new options to check box
  const addOptionToInput = (inputId) => {
    setFormInputs((c) =>
      c.map((input) =>
        input.id !== inputId
          ? input
          : { ...input, options: [...input?.options, { name, price }] }
      )
    );
  };
  //  to remove an input field from the form like small text or check boxes field
  const removeInputFormHandler = (index) => {
    setFormInputs((c) => c.filter((input) => index !== input.id));
  };

  //  add data to option field to a check box
  const addDataToCheckBox = (checkboxOptionId, optionId, data) => {
    setFormInputs((c) =>
      c.map((input) =>
        input.id === checkboxOptionId
          ? {
              ...input,
              options: input.options.map((option) =>
                option.id === optionId
                  ? {
                      ...option,
                      ...Object.keys(data).reduce((acc, key) => {
                        if (data[key] !== undefined) {
                          acc[key] = data[key];
                        }
                        return acc;
                      }, {}),
                    }
                  : option
              ),
            }
          : input
      )
    );
  };

  // add a new set of field to checkbox
  const addNewOptionToCheckbox = (checkboxId) => {
    setFormInputs((currentInputs) =>
      currentInputs.map((input) =>
        input.id === checkboxId
          ? {
              ...input,
              options: [
                ...input.options,
                {
                  id: generateUUID(),
                  name: "",
                  price: "",
                },
              ],
            }
          : input
      )
    );
  };
  //   delete set of option in checkbox
  const deleteOptionFromCheckbox = (checkboxId, optionId) => {
    setFormInputs((currentInputs) =>
      currentInputs.map((input) =>
        input.id === checkboxId
          ? {
              ...input,
              options: input.options.filter((option) => option.id !== optionId),
            }
          : input
      )
    );
  };
  // to rearange the input in the form
  const reorderInputs = (currentIndex, direction) => {
    setFormInputs((currentInputs) => {
      // Create a copy of the inputs array to modify
      const updatedInputs = [...currentInputs];

      // Determine the target index based on direction
      const targetIndex =
        direction === "up" ? currentIndex - 1 : currentIndex + 1;

      // Ensure we're within array bounds
      if (targetIndex < 0 || targetIndex >= updatedInputs.length) {
        return currentInputs; // Return unchanged if out of bounds
      }

      // Swap the inputs directly
      [updatedInputs[currentIndex], updatedInputs[targetIndex]] = [
        updatedInputs[targetIndex],
        updatedInputs[currentIndex],
      ];

      // Reassign order properties based on their new positions
      updatedInputs.forEach((input, index) => {
        input.order = index;
      });

      return updatedInputs;
    });
  };
  //  validate the state before send it to the backend
  const validateFormInputs = (formInputs) => {
    for (const input of formInputs) {
      if (!input.fieldName.trim()) {
        return false;
      }

      if (!input.placeHolder.trim()) {
        return false;
      }

      switch (input.inputType) {
        case "checkbox":
        case "radio":
          for (const option of input.options) {
            if (!option.name || option.name.trim() === "") {
              return false;
            }

            if (!option.price || option.price.trim() === "") {
              return false;
            }
          }
          break;
      }
      return true;
    }
  };

  // Usage in submit handler
  const handleSubmit = async (formInputs, productId) => {
    setIsSubmitting(true);
    if (validateFormInputs(formInputs)) {
      const { status, message } = await sendFormInputs(formInputs, productId);
      setIsSubmitting(false);
      if (status == "success") {
        toastSuccess(message);
      } else {
        toastError(message);
      }
    }
  };

  return (
    <div className="flex flex-col gap-4 w-full">
      <SelectInputToAdd
        formInputs={formInputs}
        onAddInputFormHandler={addInputFormHandler}
      />
      <div className=" mt-12 mb-20 rounded-lg w-full py-4  max-w-5xl flex flex-col gap-4">
        {formInputs?.map((oneInput, index) => (
          <CustomInput
            formInputs={formInputs}
            index={index}
            addInputData={addInputData}
            onAddOptionToInput={addOptionToInput}
            id={oneInput.id}
            inputObject={oneInput}
            key={oneInput.id}
            removeInputFormHandler={removeInputFormHandler}
            addDataToCheckBox={addDataToCheckBox}
            addNewOptionToCheckbox={addNewOptionToCheckbox}
            deleteOptionFromCheckbox={deleteOptionFromCheckbox}
            reorderInputs={reorderInputs}
          />
        ))}
        {formInputs?.length > 0 && (
          <div className="w-fit mx-auto">
            <Button
              className={"disabled:cursor-not-allowed"}
              onClick={() => handleSubmit(formInputs, productId)}
              disabled={!validateFormInputs(formInputs) || isSubmitting}
            >
              {isSubmitting ? (
                <p className="flex gap-2 items-center justify-center">
                  <div>{t("confrim_form")}</div>
                  <ImSpinner10 size={24} className="text-white animate-spin" />
                </p>
              ) : validateFormInputs(formInputs) ? (
                t("confrim_form")
              ) : (
                t("need_to_fill_all_fields")
              )}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
