/* eslint-disable no-unused-vars */
import { ExclamationCircleIcon } from "@heroicons/react/24/solid";
import { useCallback, useEffect, useMemo } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import Button from "../../../../../components/Button";
import LoadingSpinner from "../../../../../components/LoadingSpinner";
import { useAddBadgeMutation, useUpdateBadgeMutation } from "../../../../../features/badges/badgesApi";
import isProActive from "../../../../../utils/isProActive";
import { BADGE_CONTENT_PLACEHOLDERS } from "../../../../../utils/utils";

const FooterActions = () => {
  const navigate = useNavigate();
  const badge = useSelector((state) => state.badges);

  const [addBadge, { data, isLoading, isSuccess }] = useAddBadgeMutation();
  const [updateBadge, { isLoading: isUpdating, isSuccess: isUpdated }] = useUpdateBadgeMutation();

  const isPro = isProActive();
  const isAnimationUsed = Boolean(badge?.badge_settings?.class?.trim());
  const isPlaceHolderUsed = BADGE_CONTENT_PLACEHOLDERS.some((placeholder) =>
    badge?.badge_settings?.text?.includes(placeholder),
  );
  const isCustomHtml = badge?.badge_type === "custom_html";
  const isFiltered = typeof badge?.filter === "number";

  // ✅ Common validation
  const validate = useCallback(() => {
    if (!badge?.badge_name?.trim()) {
      toast.error("Badge name is required");
      return false;
    }
    if (!isPro && isAnimationUsed) {
      toast.info("Upgrade to pro for animations");
      return false;
    }
    if (!isPro && isCustomHtml) {
      toast.info("upgrade to pro for custom Html/CSS");
      return false;
    }
    if (!isPro && isFiltered) {
      toast.info("Upgrade to pro for advance filter");
      return false;
    }
    return true;
  }, [badge, isPro, isAnimationUsed, isCustomHtml, isFiltered]);

  const handleSave = async () => {
    if (!validate()) return;
    await addBadge(badge).unwrap();
  };

  const handleUpdate = async () => {
    if (!validate()) return;
    await updateBadge({ id: badge.id, body: badge }).unwrap();
  };

  const handleCopyCurrentStyle = () => {
    const badgeSettingCopy = { ...badge.badge_settings };
    const { marginTop, marginRight, marginBottom, marginLeft, zIndex, ...rest } = badgeSettingCopy;
    navigator.clipboard.writeText(JSON.stringify(rest));
  };

  useEffect(() => {
    if (isSuccess) {
      toast.success("Badge created successfully");
      navigate(`?id=${data.id}`, { state: { badge: data } });
    }
  }, [isSuccess, data, navigate]);

  useEffect(() => {
    if (isUpdated) toast.success("Badge updated successfully");
  }, [isUpdated]);

  const usedProFeatures = useMemo(() => {
    const features = [];

    if (isAnimationUsed) features.push("Animation");
    if (isPlaceHolderUsed) features.push("Dynamic Placeholders");
    if (isCustomHtml) features.push("Custom HTML");
    if (isFiltered) features.push("Advance Filter");

    return features;
  }, [isAnimationUsed, isPlaceHolderUsed, isCustomHtml, isFiltered]);

  // ✅ Memoize disabled state
  const isDisabled = useMemo(
    () => !isPro && (isAnimationUsed || isCustomHtml || isFiltered || isPlaceHolderUsed),
    [isPro, usedProFeatures],
  );

  // ✅ Save/Update button
  const ActionButton = ({ isEdit }) => {
    const loading = isEdit ? isUpdating : isLoading;
    const action = isEdit ? handleUpdate : handleSave;
    const label = isEdit ? "Update Badge" : "Save Badge";

    return (
      <Button
        disabled={loading || isDisabled}
        onClick={action}
        className="disabled:wmx-cursor-not-allowed wmx-flex-shrink-0 disabled:wmx-opacity-60"
      >
        {loading ? (
          <span className="wmx-flex wmx-items-center wmx-gap-2">
            {isEdit ? "Updating..." : "Saving..."} <LoadingSpinner />
          </span>
        ) : (
          label
        )}
      </Button>
    );
  };

  return (
    <>
      <div
        style={{ boxShadow: "0px -6px 10px 1px rgba(0,0,0,0.08)" }}
        className="wmx-fixed wmx-z-10 wmx-flex wmx-justify-end wmx-items-center wmx-pe-10 wmx-bottom-0 wmx-left-[179px] wmx-right-0 wmx-border wmx-p-2.5 wmx-bg-white"
      >
        <div className="wmx-flex wmx-justify-end wmx-gap-4 wmx-w-80">
          {/* <Button className='wmx-flex-shrink-0' type='secondary' onClick={handleCopyCurrentStyle}>
            Copy Style
          </Button> */}
          <Button type="secondary" onClick={() => navigate("/")}>
            Cancel
          </Button>
          <ActionButton isEdit={!!badge?.id} />
        </div>
      </div>
      {isDisabled && (
        <div className="wmx-flex wmx-fixed wmx-top-10 wmx-left-1/2 -wmx-translate-x-1/2 wmx-z-[9999999] wmx-items-start wmx-gap-2 wmx-bg-yellow-100 wmx-border wmx-border-yellow-400 wmx-text-yellow-900 wmx-rounded-md wmx-px-2 wmx-py-2">
          <ExclamationCircleIcon className="wmx-w-5 wmx-h-5 wmx-shrink-0" />
          <p className="wmx-text-sm wmx-leading-snug">
            You&apos;re using Pro features: <strong>{usedProFeatures.join(", ")}</strong>. Remove them to save, or
            unlock everything by upgrading to the{" "}
            <a
              href="https://innocodia.com/plugins/woocommerce-product-badges-pro/"
              target="_blank"
              className="wmx-text-yellow-900 hover:wmx-text-yellow-950 wmx-transition-colors wmx-duration-300 !wmx-outline-none focus:wmx-text-yellow-900 !wmx-shadow-none wmx-font-semibold wmx-underline"
              rel="noreferrer"
            >
              Pro Version
            </a>
            .
          </p>
        </div>
      )}
    </>
  );
};

export default FooterActions;
