import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Modal } from "antd";
import { IoMdHeartEmpty, IoMdHeart } from "react-icons/io";
import { FaShoppingCart } from "react-icons/fa";
import { DecreaseIcon, IncreaseIcon } from "../../../components/Icons";
import {
  useAddFavoriteMutation,
  useRemoveFavoriteMutation,
  useGetFavoritesQuery,
} from "../../../app/api/favoritesApi";
import {
  useAddToCartMutation,
  useUpdateCartItemMutation,
  useRemoveFromCartMutation,
} from "../../../app/api/cartApi";
import { useCart } from "../../../app/api/useCart";
import styles from "./Mobilephonecard.module.scss";

/**
 * Parses product.description HTML into spec pairs.
 * Format inside HTML: "Label1: Value1; Label2: Value2; ..."
 */
const parseSpecs = (htmlString) => {
  if (!htmlString) return [];
  const div = document.createElement("div");
  div.innerHTML = htmlString;

  let processedHtml = htmlString
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<\/div>/gi, "\n")
    .replace(/<\/strong>/gi, ": ");

  div.innerHTML = processedHtml;
  const text = (div.textContent || div.innerText || "").trim();

  return text
    .split(/[;\n]+/)
    .map((chunk) => chunk.trim())
    .filter(Boolean)
    .map((chunk) => {
      const separatorIdx = chunk.search(/[:|]/);
      if (separatorIdx === -1) return null;

      return {
        label: chunk.slice(0, separatorIdx).trim(),
        value: chunk.slice(separatorIdx + 1).trim(),
      };
    })
    .filter((item) => item !== null && item.value !== "");
};

const MobilePhoneCard = ({
  product,
  showAddToCart = true,
  showFavoriteButton = true,
}) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [stockErrorModalVisible, setStockErrorModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // ── Favorites ──────────────────────────────────────────────────────────────
  const [addFavorite] = useAddFavoriteMutation();
  const [removeFavorite] = useRemoveFavoriteMutation();
  const { data: favoriteProducts = [] } = useGetFavoritesQuery();
  const [localIsFavorite, setLocalIsFavorite] = useState(false);

  useEffect(() => {
    if (Array.isArray(favoriteProducts)) {
      setLocalIsFavorite(
        favoriteProducts.some((fav) => fav.product?.id === product.id)
      );
    }
  }, [favoriteProducts, product.id]);

  // ── Cart ───────────────────────────────────────────────────────────────────
  const { getCartItem } = useCart();
  const [addToCart] = useAddToCartMutation();
  const [updateCartItem] = useUpdateCartItemMutation();
  const [removeFromCart] = useRemoveFromCartMutation();

  const cartItem = getCartItem(product.id);
  const [localQuantity, setLocalQuantity] = useState(0);
  const [pendingQuantity, setPendingQuantity] = useState(0);

  useEffect(() => {
    const qty = parseInt(
      cartItem?.quantity || cartItem?.product_quantity || 0,
      10
    );
    setLocalQuantity(qty);
    setPendingQuantity(qty);
  }, [cartItem]);

  // Debounced sync to server
  useEffect(() => {
    const serverQty = parseInt(
      cartItem?.quantity || cartItem?.product_quantity || 0,
      10
    );
    if (pendingQuantity === serverQty || pendingQuantity <= 0) return;

    const timer = setTimeout(async () => {
      try {
        setIsLoading(true);
        await updateCartItem({
          productId: product.id,
          quantity: pendingQuantity,
        }).unwrap();
      } catch {
        setLocalQuantity(serverQty);
        setPendingQuantity(serverQty);
      } finally {
        setIsLoading(false);
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [pendingQuantity, cartItem, product.id, updateCartItem]);

  // ── Handlers ───────────────────────────────────────────────────────────────
  const handleCardClick = () => navigate(`/product/${product.id}`);

  const handleAddToCart = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (product.stock <= 0) {
      setStockErrorModalVisible(true);
      return;
    }
    setLocalQuantity((p) => p + 1);
    setPendingQuantity((p) => p + 1);
    try {
      await addToCart({ productId: product.id, quantity: 1 }).unwrap();
    } catch {
      setLocalQuantity((p) => p - 1);
      setPendingQuantity((p) => p - 1);
    }
  };

  const handleIncrease = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (isLoading) return;
    if (localQuantity >= product.stock) {
      setStockErrorModalVisible(true);
      return;
    }
    setLocalQuantity((p) => p + 1);
    setPendingQuantity((p) => p + 1);
  };

  const handleDecrease = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (isLoading) return;
    if (pendingQuantity <= 1) {
      setLocalQuantity(0);
      setPendingQuantity(0);
      setIsLoading(true);
      removeFromCart({ productId: product.id })
        .unwrap()
        .catch(() => {
          setLocalQuantity(1);
          setPendingQuantity(1);
        })
        .finally(() => setIsLoading(false));
    } else {
      setLocalQuantity((p) => p - 1);
      setPendingQuantity((p) => p - 1);
    }
  };

  const handleToggleFavorite = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (isLoading) return;
    setIsLoading(true);
    setLocalIsFavorite((prev) => !prev);
    try {
      if (localIsFavorite) await removeFavorite(product.id).unwrap();
      else await addFavorite(product.id).unwrap();
    } catch {
      setLocalIsFavorite((prev) => !prev);
    } finally {
      setIsLoading(false);
    }
  };

  // ── Derived ────────────────────────────────────────────────────────────────
  const specs = parseSpecs(product.description);
  const thumbnail =
    product.media?.[0]?.images_400x400 || product.media?.[0]?.thumbnail;
  const hasDiscount =
    product.old_price_amount &&
    parseFloat(product.old_price_amount) > parseFloat(product.price_amount);

  return (
    <>
      <div className={styles.card} onClick={handleCardClick}>
        {/* Image */}
        <div className={styles.imageCol}>
          {product.stock === 0 && (
            <span className={styles.outOfStockBadge}>
              {t("common.out_of_stock")}
            </span>
          )}
          {thumbnail ? (
            <img src={thumbnail} alt={product.name} className={styles.image} />
          ) : (
            <div className={styles.imagePlaceholder}>📱</div>
          )}
        </div>

        {/* Info */}
        <div className={styles.infoCol}>
          <div className={styles.titleRow}>
            <span className={styles.name}>{product.name}</span>
            {product.brand?.name && (
              <span className={styles.brand}>{product.brand.name}</span>
            )}
          </div>

          {/* Dense spec paragraph — mirrors reference image */}
          {specs.length > 0 && (
            <p className={styles.specLine}>
              {specs.map((s, i) => (
                <span key={i}>
                  <span className={styles.specLabel}>{s.label}: </span>
                  <span className={styles.specValue}>{s.value}</span>
                  {i < specs.length - 1 && "; "}
                </span>
              ))}
            </p>
          )}

          {/* Footer */}
          <div className={styles.footer} onClick={(e) => e.stopPropagation()}>
            <div className={styles.priceBlock}>
              <span className={styles.price}>{product.price_amount} m.</span>
              {hasDiscount && (
                <span className={styles.oldPrice}>
                  {product.old_price_amount} m.
                </span>
              )}
            </div>

            <div className={styles.actions}>
              {showFavoriteButton && (
                <button
                  className={`${styles.iconBtn} ${
                    localIsFavorite ? styles.favActive : ""
                  }`}
                  onClick={handleToggleFavorite}
                  disabled={isLoading}
                >
                  {localIsFavorite ? <IoMdHeart /> : <IoMdHeartEmpty />}
                </button>
              )}

              {showAddToCart &&
                (localQuantity > 0 ? (
                  <div className={styles.quantityControls}>
                    <button
                      className={styles.qtyBtn}
                      onClick={handleDecrease}
                      disabled={isLoading}
                    >
                      <DecreaseIcon />
                    </button>
                    <span className={styles.qtyValue}>{localQuantity}</span>
                    <button
                      className={styles.qtyBtn}
                      onClick={handleIncrease}
                      disabled={isLoading}
                    >
                      <IncreaseIcon />
                    </button>
                  </div>
                ) : (
                  <button
                    className={styles.cartBtn}
                    onClick={handleAddToCart}
                    disabled={isLoading || product.stock === 0}
                  >
                    <FaShoppingCart />
                    <span>Sebede goş</span>
                  </button>
                ))}
            </div>
          </div>
        </div>
      </div>

      <Modal
        title={t("common.warning")}
        open={stockErrorModalVisible}
        onOk={() => setStockErrorModalVisible(false)}
        onCancel={() => setStockErrorModalVisible(false)}
        footer={[
          <button
            key="ok"
            onClick={() => setStockErrorModalVisible(false)}
            className={styles.modalButton}
          >
            {t("common.ok")}
          </button>,
        ]}
      >
        <p>
          {t("common.not_enough_stock", {
            available: product.stock,
            requested: localQuantity + 1,
          })}
        </p>
      </Modal>
    </>
  );
};

export const MOBILE_PHONE_CATEGORY_ID = 531;
export default MobilePhoneCard;
