"use client";
import fetchData from "@/api/fetch-data";
import postData from "@/api/post-data";
import AlertWarning from "@/app/ui/shared/AlertWarning";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { FaSpinner } from "react-icons/fa";

export default function TranslationFeatures({ productId }) {
  const t = useTranslations("vendor");
  const [translatedFeatures, setTranslatedFeatures] = useState([]);
  const [originalFeatures, setOriginalFeatures] = useState([]);
  const [nonTranslatedFeatures, setNonTranslatedFeatures] = useState([]);
  const [editedTranslations, setEditedTranslations] = useState({});
  const [loadingButtons, setLoadingButtons] = useState({});

  // function to get translation features
  async function getTranslatedFeatures() {
    const response = await fetchData({
      endPoint: `/user/products/translate-feature/${productId}`,
    });
    if (
      !response?.error &&
      response?.status === "success" &&
      response?.data?.features?.length > 0
    ) {
      setTranslatedFeatures(response?.data?.features);
      setOriginalFeatures(response?.data?.features[0]?.original_options);
      setNonTranslatedFeatures(
        response?.data?.features[0]?.options_translation
      );
    }
  }
  // useEffect to call get translation features
  useEffect(() => {
    getTranslatedFeatures();
  }, []);
  // Handle change in translation
  const handleTranslationChange = (e, optionId) => {
    setEditedTranslations((prev) => ({
      ...prev,
      [optionId]: e.target.value,
    }));
  };

  // function to add translation
  async function addTranslation(id, type, value) {
    setLoadingButtons((prev) => ({ ...prev, [id]: true })); // Set loading for the specific button
    const data = new FormData();
    data.append("option_data_id", id);
    data.append("option_data_type", type);
    data.append("translate", value);
    const response = await postData({
      endPoint: "/user/products/save/translate-feature",
      body: data,
    });
    if (!response.error && response.status === "success") {
      toastSuccess(t("success"));
    } else {
      toastError(t("error"));
    }
    setLoadingButtons((prev) => ({ ...prev, [id]: false })); // Reset loading for the specific button
  }
  // check if there are translated features
  if (translatedFeatures?.length === 0) {
    return <AlertWarning text={t("no-translated-features")} />;
  }
  return (
    <div className="space-y-4">
      {originalFeatures?.map((original, index) => {
        const translation = nonTranslatedFeatures?.find(
          (option) => option.source_id === original.option_data_id
        );
        const currentTranslation =
          editedTranslations[original.option_data_id] ||
          translation?.name ||
          "";
        return (
          <div key={index} className="flex flex-col space-y-2">
            <div className="flex items-end gap-x-4">
              {/* Input for original option */}
              <div className="w-full">
                <Label
                  className="text-btnColor  font-semibold"
                  htmlFor="feature"
                >
                  {t("fearture")}
                </Label>
                <Input
                  id="feature"
                  type="text"
                  value={original?.name || ""}
                  readOnly
                  className="w-full mt-2 p-2 md:h-10"
                />
              </div>
              {/* Input for translated option */}
              <div className="w-full">
                <Label
                  className="text-btnColor  font-semibold"
                  htmlFor="translation"
                >
                  {t("translation")}
                </Label>
                <Input
                  id="translation"
                  type="text"
                  value={currentTranslation}
                  onChange={(e) =>
                    handleTranslationChange(e, original.option_data_id)
                  }
                  className="mt-2 w-full p-2 md:h-10"
                />
              </div>
              <button
                className="group btn btn-btnColor w-80 flex items-center justify-center p-2 text-sm"
                onClick={() =>
                  addTranslation(
                    original.option_data_id,
                    translatedFeatures[0].type,
                    currentTranslation
                  )
                }
                disabled={loadingButtons[original.option_data_id]} // Disable button during loading
              >
                {loadingButtons[original.option_data_id] ? (
                  <FaSpinner
                    size={20}
                    className="text-white animate-spin group-hover:text-btnColor "
                  />
                ) : (
                  <>{t("translate-features-btn")}</>
                )}
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}
