"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import api from "@/lib/api";
import { getGuestToken } from "@/lib/guestToken";
import toast from "react-hot-toast";

import {
  Heart,
  Eye,
  Star,
  ShoppingCart,
  Plus,
  Minus,
  Trash2,
} from "lucide-react";

interface VariationAttributeValue {
  id?: number;
  attribute?: {
    id?: number;
    name?: string;
    slug?: string;
  };
  value?: {
    id?: number;
    value?: string;
    color_code?: string | null;
    image?: string | null;
  };
}

interface ProductVariation {
  id: number;
  sku?: string | null;
  price?: string | number | null;
  sale_price?: string | number | null;
  stock_quantity?: number;
  image?: string | null;
  status?: boolean;
  attribute_values?: VariationAttributeValue[];
  variation_attribute_values?: VariationAttributeValue[];
}

interface Product {
  id: number;
  name: string;
  slug: string;
  price: string | number;
  sale_price?: string | number | null;
  image?: string | null;
  stock_quantity?: number;
  stock_status?: string;
  is_featured?: boolean;
  product_type?: "simple" | "variable" | string;

  category?: {
    name: string;
    slug: string;
  } | null;

  unit_type?: string;
  unit_value?: string;

  variations?: ProductVariation[];
  product_variations?: ProductVariation[];
}

export default function ProductCard({
  product,
}: {
  product: Product;
}) {
  const variations =
    product.variations || product.product_variations || [];

  const [selectedVariation, setSelectedVariation] =
    useState<ProductVariation | null>(
      variations[0] || null
    );

  const [cartQuantity, setCartQuantity] = useState(0);

  const [cartItemId, setCartItemId] =
    useState<number | null>(null);

  const [loading, setLoading] = useState(false);

  const activePriceSource =
    selectedVariation || product;

  const regularPrice = Number(
    activePriceSource.price ||
      product.price ||
      0
  );

  const salePrice = Number(
    activePriceSource.sale_price || 0
  );

  const hasSale =
    salePrice > 0 &&
    salePrice < regularPrice;

  const finalPrice = hasSale
    ? salePrice
    : regularPrice;

  const discountPercent = hasSale
    ? Math.round(
        ((regularPrice - salePrice) /
          regularPrice) *
          100
      )
    : 0;

  const displayImage =
    selectedVariation?.image ||
    product.image ||
    "https://via.placeholder.com/500x500?text=Product";

  const stockQuantity =
    selectedVariation?.stock_quantity ??
    product.stock_quantity ??
    0;

  const isOutOfStock =
    product.stock_status ===
      "out_of_stock" ||
    stockQuantity === 0;

  const variationLabel = (
    variation: ProductVariation
  ) => {
    const values =
      variation.attribute_values ||
      variation.variation_attribute_values ||
      [];

    const label = values
      .map((item) => item.value?.value)
      .filter(Boolean)
      .join(" / ");

    return (
      label ||
      variation.sku ||
      `Variant ${variation.id}`
    );
  };

  const selectedVariationLabel = useMemo(() => {
    if (!selectedVariation) return null;

    return variationLabel(selectedVariation);
  }, [selectedVariation]);

  const fireCartUpdate = () => {
    window.dispatchEvent(
      new Event("cart-updated")
    );
  };

  const addToWishlist = async () => {
    try {
      await api.post("/wishlist/toggle", {
        product_id: product.id,
        guest_token: getGuestToken(),
      });

      toast.success("Wishlist updated");
    } catch (error) {
      console.error(error);

      toast.error(
        "Wishlist update failed"
      );
    }
  };

  const addToCart = async () => {
    if (isOutOfStock) {
      toast.error(
        "Product is out of stock"
      );

      return;
    }

    if (
      variations.length > 0 &&
      !selectedVariation
    ) {
      toast.error(
        "Please select a variant"
      );

      return;
    }

    try {
      setLoading(true);

      const response = await api.post(
        "/cart/add",
        {
          product_id: product.id,

          variation_id:
            selectedVariation?.id || null,

          quantity: 1,

          guest_token: getGuestToken(),
        }
      );

      setCartQuantity(1);

      setCartItemId(
        response.data.cart_item_id
      );

      fireCartUpdate();

      toast.success("Added to cart");
    } catch (error) {
      console.error(error);

      toast.error(
        "Failed to add cart"
      );
    } finally {
      setLoading(false);
    }
  };

  const updateCartQuantity = async (
    nextQuantity: number
  ) => {
    if (nextQuantity < 1) return;

    try {
      setLoading(true);

      await api.post("/cart/update", {
        cart_item_id: cartItemId,

        quantity: nextQuantity,

        guest_token: getGuestToken(),
      });

      setCartQuantity(nextQuantity);

      fireCartUpdate();
    } catch (error) {
      console.error(error);

      toast.error(
        "Cart update failed"
      );
    } finally {
      setLoading(false);
    }
  };

  const removeFromCart = async () => {
    try {
      setLoading(true);

      await api.post("/cart/remove", {
        cart_item_id: cartItemId,

        guest_token: getGuestToken(),
      });

      setCartQuantity(0);

      setCartItemId(null);

      fireCartUpdate();

      toast.success(
        "Removed from cart"
      );
    } catch (error) {
      console.error(error);

      toast.error("Remove failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="group relative overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm transition-all duration-300 hover:shadow-lg">
      <div className="relative aspect-square overflow-hidden bg-gray-50">
        <Link
          href={`/products/${product.slug}`}
          prefetch={false}
        >
          <img
            src={displayImage}
            alt={product.name}
            className="h-full w-full object-contain p-4 transition-transform duration-300 group-hover:scale-105"
          />
        </Link>

        {hasSale && (
          <div className="absolute left-3 top-3 rounded-sm bg-red-600 px-2 py-1 text-xs font-bold text-white">
            -{discountPercent}%
          </div>
        )}

        {product.is_featured && (
          <div className="absolute right-3 top-3 rounded-sm bg-orange-500 px-2 py-1 text-xs font-bold text-white">
            Featured
          </div>
        )}

        <div className="absolute bottom-3 right-3 flex flex-col gap-2 opacity-100 transition md:opacity-0 md:group-hover:opacity-100">
          <button
            type="button"
            onClick={addToWishlist}
            className="flex h-9 w-9 cursor-pointer items-center justify-center rounded-full bg-white text-gray-700 shadow hover:text-red-500"
          >
            <Heart size={17} />
          </button>

          <Link
            href={`/products/${product.slug}`}
            prefetch={false}
            className="flex h-9 w-9 cursor-pointer items-center justify-center rounded-full bg-white text-gray-700 shadow hover:text-blue-600"
          >
            <Eye size={17} />
          </Link>
        </div>
      </div>

      <div className="p-4">
        {product.category?.name && (
          <p className="mb-1 line-clamp-1 text-xs text-gray-500">
            {product.category.name}
          </p>
        )}

        <Link
          href={`/products/${product.slug}`}
          prefetch={false}
        >
          <h3 className="min-h-[42px] line-clamp-2 text-sm font-medium leading-5 text-gray-900 hover:text-green-600">
            {product.name}
          </h3>
        </Link>

        <div className="mt-2 flex items-center gap-1">
          <div className="flex text-orange-400">
            {[...Array(5)].map(
              (_, index) => (
                <Star
                  key={index}
                  size={13}
                  fill="currentColor"
                />
              )
            )}
          </div>

          <span className="text-xs text-gray-500">
            (5.0)
          </span>
        </div>

        <div className="mt-3 flex items-end gap-2">
          <span className="text-xl font-bold text-gray-900">
            ৳{finalPrice.toFixed(0)}
          </span>

          {hasSale && (
            <span className="text-sm text-gray-400 line-through">
              ৳
              {regularPrice.toFixed(0)}
            </span>
          )}
        </div>

        {(product.unit_value ||
          product.unit_type) && (
          <p className="mt-1 text-xs text-gray-500">
            {product.unit_value}{" "}
            {product.unit_type}
          </p>
        )}

        {variations.length > 0 && (
          <div className="mt-3">
            <p className="mb-2 text-xs font-semibold text-gray-700">
              Variant:{" "}
              <span className="font-normal text-gray-500">
                {
                  selectedVariationLabel
                }
              </span>
            </p>

            <div className="flex flex-wrap gap-2">
              {variations.map(
                (variation) => {
                  const active =
                    selectedVariation?.id ===
                    variation.id;

                  return (
                    <button
                      key={variation.id}
                      type="button"
                      onClick={() => {
                        setSelectedVariation(
                          variation
                        );

                        setCartQuantity(0);

                        setCartItemId(
                          null
                        );
                      }}
                      className={`cursor-pointer rounded-md border px-2.5 py-1.5 text-xs font-medium transition ${
                        active
                          ? "border-green-500 bg-green-50 text-green-700"
                          : "border-gray-300 bg-white text-gray-700 hover:border-green-400"
                      }`}
                    >
                      {variationLabel(
                        variation
                      )}
                    </button>
                  );
                }
              )}
            </div>
          </div>
        )}

        <div className="mt-4">
          {cartQuantity === 0 ? (
            <button
              type="button"
              onClick={addToCart}
              disabled={
                loading ||
                isOutOfStock
              }
              className="flex h-11 w-full cursor-pointer items-center justify-center gap-2 rounded-full bg-green-600 px-4 text-sm font-bold text-white transition hover:bg-green-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-500"
            >
              <ShoppingCart size={18} />

              {isOutOfStock
                ? "Out of Stock"
                : "Add to Cart"}
            </button>
          ) : (
            <div className="flex h-11 w-full items-center overflow-hidden rounded-full border border-green-500 bg-white">
              <button
                type="button"
                onClick={() =>
                  cartQuantity === 1
                    ? removeFromCart()
                    : updateCartQuantity(
                        cartQuantity - 1
                      )
                }
                disabled={loading}
                className="flex h-full w-12 cursor-pointer items-center justify-center text-green-600 hover:bg-green-50 disabled:opacity-50"
              >
                {cartQuantity === 1 ? (
                  <Trash2 size={18} />
                ) : (
                  <Minus size={18} />
                )}
              </button>

              <div className="flex flex-1 items-center justify-center gap-2 bg-green-50 text-sm font-bold text-green-700">
                <ShoppingCart size={17} />

                <span>
                  {cartQuantity}
                </span>
              </div>

              <button
                type="button"
                onClick={() =>
                  updateCartQuantity(
                    cartQuantity + 1
                  )
                }
                disabled={loading}
                className="flex h-full w-12 cursor-pointer items-center justify-center text-green-600 hover:bg-green-50 disabled:opacity-50"
              >
                <Plus size={18} />
              </button>
            </div>
          )}
        </div>

        <p className="mt-3 text-xs text-gray-500">
          {isOutOfStock
            ? "Currently unavailable"
            : `Stock: ${stockQuantity}`}
        </p>
      </div>
    </div>
  );
}