"use client";

import { ProductGallery } from "@/features/products/components/product-gallery";

import { productLabel, quantityWithUnit } from "@/lib/product-unit";

import { useState, useMemo } from "react";
import { useRouter } from "next/navigation";
import {
  Package,
  CreditCard,
  Ruler,
  Tag,
  Search,
  ShoppingCart,
  Check,
  Minus,
  Plus,
  Info,
  CheckCircle2,
  ZoomIn,
  X,
  Image as ImageIcon,
  Settings,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useCartContext } from "../components/cart-context";
import { getCurrentUserContext, isAdminUser, isDepartmentUser } from "@/features/auth/user-context";
import type { ProductResponseDTO } from "@/features/products/dtos/product.dto";
import type { ProductVariantResponseDTO } from "@/features/products/dtos/product.dto";

// ============================================
// Types for product options (variant + size combos)
// ============================================

interface ProductOption {
  variantId: string | null;
  variantName: string | null;
  variantImageUrl: string | null;
  size: string | null;
  sizeImageUrl: string | null;
  label: string;
}

function buildProductOptions(product: ProductResponseDTO): ProductOption[] {
  const isBC = Boolean(product.isBusinessCard);
  if (isBC) {
    return [
      { variantId: null, variantName: null, variantImageUrl: null, size: null, sizeImageUrl: null, label: "Default" },
    ];
  }

  const variants =
    product.variants.length > 0
      ? product.variants
      : [{ id: null, name: null, imageUrl: null } as unknown as ProductVariantResponseDTO];
  const sizes =
    product.sizes && product.sizes.length > 0
      ? product.sizes
      : [{ name: null, imageUrl: null } as unknown as import("@/features/products/dtos/product.dto").ProductSizeDTO];

  const options: ProductOption[] = [];
  for (const v of variants) {
    for (const s of sizes) {
      const parts: string[] = [];
      if (v.name) parts.push(v.name);
      if (s?.name) parts.push(s.name);
      options.push({
        variantId: v.id,
        variantName: v.name,
        variantImageUrl: v.imageUrl ?? null,
        size: s?.name ?? null,
        sizeImageUrl: s?.imageUrl ?? null,
        label: parts.length > 0 ? parts.join(" · ") : "Default",
      });
    }
  }
  return options;
}

// ============================================
// Image Preview Modal
// ============================================

function ImageModal({
  url,
  alt,
  onClose,
}: {
  url: string;
  alt: string;
  onClose: () => void;
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />
      <div className="relative z-10 mx-4 max-w-3xl overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl">
        <div className="flex items-center justify-between border-b border-gray-200 px-4 py-3">
          <div className="flex items-center gap-2">
            <ZoomIn className="h-4 w-4 text-gray-500" />
            <span className="text-sm font-medium text-gray-700">{alt}</span>
          </div>
          <button
            onClick={onClose}
            className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
          >
            <X className="h-5 w-5" />
          </button>
        </div>
        <div className="flex items-center justify-center p-4">
          <img
            src={url}
            alt={alt}
            className="max-h-[70vh] max-w-full rounded-lg object-contain"
          />
        </div>
      </div>
    </div>
  );
}

// ============================================
// Product Card Component (Ecommerce Style)
// ============================================

interface ProductCardProps {
  product: ProductResponseDTO;
  onAddToCart: (
    productId: string,
    productName: string,
    imageUrl: string | null,
    isBusinessCard: boolean,
    variantId: string | null,
    variantName: string | null,
    size: string | null,
    quantity: number,
    minQty: number
  ) => void;
  getCartQty: (
    productId: string,
    variantId: string | null,
    size: string | null
  ) => number;
}

function ProductCard({
  product,
  onAddToCart,
  getCartQty,
}: ProductCardProps) {
  const router = useRouter();
  const [quantities, setQuantities] = useState<Record<string, number>>({});
  const [addedKeys, setAddedKeys] = useState<Set<string>>(new Set());
  const [imageModal, setImageModal] = useState<{ url: string; alt: string } | null>(null);

  const isBC = Boolean(product.isBusinessCard);
  const options = buildProductOptions(product);
  const minQty = product.minimumQuantity;
  const allowOversell = true;

  const handleQtyChange = (key: string, value: number) => {
    // Snap to multiples of minimumQuantity, minimum is minQty
    const snapped = Math.max(minQty, Math.round(value / minQty) * minQty);
    setQuantities((prev) => ({ ...prev, [key]: snapped }));
  };

  const handleIncrement = (key: string) => {
    const current = quantities[key] ?? minQty;
    setQuantities((prev) => ({ ...prev, [key]: current + minQty }));
  };

  const handleDecrement = (key: string) => {
    const current = quantities[key] ?? minQty;
    setQuantities((prev) => ({ ...prev, [key]: Math.max(minQty, current - minQty) }));
  };

  const handleAdd = (option: ProductOption) => {
    const key = `${option.variantId ?? "null"}-${option.size ?? "null"}`;
    const qty = quantities[key] ?? product.minimumQuantity;

    const available = product.stockOptions?.find((stock) => stock.variantId === option.variantId && stock.size === option.size)?.quantity ?? 0;
    if (!allowOversell && qty + getCartQty(product.id, option.variantId, option.size) > available) return;

    onAddToCart(
      product.id,
      product.name,
      option.variantImageUrl ?? option.sizeImageUrl ?? product.imageUrl,
      isBC,
      option.variantId,
      option.variantName,
      option.size,
      qty,
      product.minimumQuantity
    );

    // Flash added state
    setAddedKeys((prev) => new Set(prev).add(key));
    setTimeout(() => {
      setAddedKeys((prev) => {
        const next = new Set(prev);
        next.delete(key);
        return next;
      });
    }, 1500);
  };

  return (
    <div className="group flex flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm transition-all hover:border-navy-200 hover:shadow-md">
      {/* Product Image & Badges */}
      <div className="relative h-28 shrink-0 overflow-hidden border-b border-gray-100 bg-gray-50">
        {product.imageUrl ? (
          <button type="button" aria-label={`Zoom ${product.name}`} onClick={() => setImageModal({ url: product.imageUrl!, alt: product.name })} className="group/image relative h-full w-full cursor-zoom-in focus-visible:outline-2 focus-visible:outline-blue-500">
            <img src={product.imageUrl} alt={product.name} className="h-full w-full object-contain p-2 transition-transform duration-200 group-hover/image:scale-105" />
            <span className="absolute bottom-2 right-2 rounded-md border border-gray-200 bg-white/95 p-1 text-gray-600"><ZoomIn className="h-3.5 w-3.5" /></span>
          </button>
        ) : (
          <div
            className={`flex h-full w-full items-center justify-center ${
              isBC ? "bg-[#1a6b5a]/5" : "bg-purple-50"
            }`}
          >
            {isBC ? (
              <CreditCard className="h-12 w-12 text-[#1a6b5a]/40" />
            ) : (
              <Package className="h-12 w-12 text-purple-300" />
            )}
          </div>
        )}

        {/* Badges */}
        <div className="absolute left-2 top-2 flex flex-wrap gap-1">
          {isBC && (
            <span className="inline-flex items-center gap-0.5 rounded-md bg-[#1a6b5a] px-2 py-0.5 text-[10px] font-semibold text-white">
              <CreditCard className="h-2.5 w-2.5" />
              Business Card
            </span>
          )}
          {product.variants.length > 0 && (
            <span className="inline-flex items-center gap-0.5 rounded-md bg-amber-500 px-2 py-0.5 text-[10px] font-semibold text-white">
              <Tag className="h-2.5 w-2.5" />
              {product.variants.length} variant{product.variants.length !== 1 ? "s" : ""}
            </span>
          )}
          {product.sizes && product.sizes.length > 0 && (
            <span className="inline-flex items-center gap-0.5 rounded-md bg-blue-500 px-2 py-0.5 text-[10px] font-semibold text-white">
              <Ruler className="h-2.5 w-2.5" />
              {product.sizes.length} size{product.sizes.length !== 1 ? "s" : ""}
            </span>
          )}
        </div>
      </div>

      {/* Product Info */}
      <div className="flex flex-1 flex-col p-4">
        <h3 className="text-sm font-semibold text-gray-900">{productLabel(product.name, product.defaultUnit)}</h3>
          {product.description && <p className="mt-1 line-clamp-2 text-xs text-gray-500">{product.description}</p>}
          {(product.images?.length ?? 0) > 0 && <ProductGallery product={product} />}
        <p className="mt-1 text-xs text-gray-500">
          Min. quantity: <span className="font-semibold">{quantityWithUnit(product.minimumQuantity, product.defaultUnit)}</span>
        </p>

        {/* Configure Business Card Link — for BC products, show link instead of option table */}
        {isBC && (
          <div className="mt-3 flex-1">
            <div className="rounded-lg border border-[#1a6b5a]/20 bg-[#1a6b5a]/5 p-3">
              <p className="text-[11px] text-gray-600 mb-2">
                Configure your business card designs from the dedicated page, then add to cart.
              </p>
              <button
                type="button"
                onClick={() => router.push(`/business-card?productId=${encodeURIComponent(product.id)}`)}
                className="inline-flex items-center gap-1.5 rounded-md bg-[#1a6b5a] px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-[#155c4d]"
              >
                <Settings className="h-3 w-3" />
                Configure Business Card
              </button>
            </div>
          </div>
        )}

        {/* Variants/Sizes Table — only for non-BC products */}
        {!isBC && (
        <div className="mt-3 flex-1">
          <div className="overflow-hidden rounded-lg border border-gray-100">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-100 bg-gray-50">
                  <th className="px-2 py-1.5 text-left text-[10px] font-medium uppercase tracking-wider text-gray-400">
                    Option
                  </th>
                  <th className="px-2 py-1.5 text-center text-[10px] font-medium uppercase tracking-wider text-gray-400">
                    Qty
                  </th>
                  <th className="px-2 py-1.5 text-center text-[10px] font-medium uppercase tracking-wider text-gray-400">
                    Cart
                  </th>
                  <th className="px-1 py-1.5"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {options.map((option) => {
                  const key = `${option.variantId ?? "null"}-${option.size ?? "null"}`;
                  const cartQty = getCartQty(
                    product.id,
                    option.variantId,
                    option.size
                  );
                  const isInCart = cartQty > 0;
                  const qty = quantities[key] ?? product.minimumQuantity;
                  const available = product.stockOptions?.find((stock) => stock.variantId === option.variantId && stock.size === option.size)?.quantity ?? 0;
                  const canAdd = allowOversell || qty + cartQty <= available;
                  const justAdded = addedKeys.has(key);

                  // Determine which image to show (variant image takes priority, then size image)
                  const thumbUrl = option.variantImageUrl ?? option.sizeImageUrl;
                  const thumbAlt = option.variantName ?? option.size ?? "Default";

                  return (
                    <tr
                      key={key}
                      className={`transition-colors ${
                        isInCart
                          ? "bg-navy-50/50"
                          : "bg-white hover:bg-gray-50/50"
                      }`}
                    >
                      <td className="px-2 py-1.5">
                        <div className="flex items-center gap-1.5">
                          {thumbUrl ? (
                            <button
                              type="button"
                              onClick={() => setImageModal({ url: thumbUrl, alt: thumbAlt })}
                              className="shrink-0"
                            >
                              <img
                                src={thumbUrl}
                                alt={thumbAlt}
                                className="h-5 w-5 rounded-sm object-cover ring-1 ring-gray-200 hover:ring-navy-300 transition-all"
                              />
                            </button>
                          ) : (
                            <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-sm bg-gray-100">
                              <ImageIcon className="h-3 w-3 text-gray-300" />
                            </div>
                          )}
                          <span className="text-[11px] font-medium text-gray-700">
                            {allowOversell && !option.variantName && !option.size ? null : option.label}
                            {!allowOversell && (
                              <span className="block text-[10px] text-gray-500">
                                {available > 0 ? `${available} available` : "Out of stock"}
                              </span>
                            )}
                          </span>
                        </div>
                      </td>
                      <td className="px-2 py-1.5">
                        <div className="flex items-center justify-center">
                          <div className="flex items-center">
                            <button
                              onClick={() => handleDecrement(key)}
                              className="flex h-5 w-5 items-center justify-center rounded-l border border-gray-200 text-gray-400 hover:bg-gray-50"
                            >
                              <Minus className="h-2.5 w-2.5" />
                            </button>
                            <input
                              type="number"
                              value={qty}
                              min={minQty}
                              step={minQty}
                              onChange={(e) => {
                                const val = parseInt(e.target.value);
                                if (!isNaN(val) && val >= minQty) {
                                  handleQtyChange(key, val);
                                }
                              }}
                              className="h-5 w-12 border-y border-gray-200 bg-white text-center text-[10px] font-medium text-gray-900 focus:outline-none"
                            />
                            <button
                              onClick={() => handleIncrement(key)}
                              className="flex h-5 w-5 items-center justify-center rounded-r border border-gray-200 text-gray-400 hover:bg-gray-50"
                            >
                              <Plus className="h-2.5 w-2.5" />
                            </button>
                          </div>
                        </div>
                      </td>
                      <td className="px-2 py-1.5 text-center">
                        {isInCart ? (
                          <span className="inline-flex items-center gap-0.5 rounded-full bg-navy-100 px-1.5 py-0.5 text-[10px] font-semibold text-navy-700">
                            <CheckCircle2 className="h-2.5 w-2.5" />
                            {cartQty.toLocaleString()}
                          </span>
                        ) : (
                          <span className="text-[10px] text-gray-300">—</span>
                        )}
                      </td>
                      <td className="px-1 py-1.5">
                        <button
                          onClick={() => handleAdd(option)}
                          disabled={!canAdd}
                          className={`flex h-5 w-5 items-center justify-center rounded transition-colors ${
                            justAdded
                              ? "bg-emerald-500 text-white"
                              : isInCart
                                ? "bg-navy-100 text-navy-600 hover:bg-navy-200"
                                : "bg-gray-100 text-gray-500 hover:bg-navy-100 hover:text-navy-600"
                          }`}
                          title={!canAdd ? "Insufficient stock for this quantity" : isInCart ? "Add more" : "Add to cart"}
                        >
                          {justAdded ? (
                            <Check className="h-2.5 w-2.5" />
                          ) : (
                            <ShoppingCart className="h-2.5 w-2.5" />
                          )}
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
        )}
      </div>

      {/* Image Preview Modal */}
      {imageModal && (
        <ImageModal
          url={imageModal.url}
          alt={imageModal.alt}
          onClose={() => setImageModal(null)}
        />
      )}
    </div>
  );
}

// ============================================
// Product Grid Component
// ============================================

interface ProductGridProps {
  products: ProductResponseDTO[];
  isLoading?: boolean;
}

export function ProductGrid({ products, isLoading = false }: ProductGridProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const { addToCart, getItemForProduct } = useCartContext();
  const userContext = getCurrentUserContext();
  const userIsAdmin = isAdminUser();
  const userIsDepartmentUser = isDepartmentUser();
  const userCompanyId = userContext.companyId;
  const userDepartmentIds = userContext.departmentIds;

  const filtered = useMemo(() => {
    const activeProducts = products.filter((p) => p.status === "active");

    const companyFiltered = activeProducts.filter((p) => {
      if (userIsAdmin) return true; // Admin sees everything
      if (!userCompanyId) return true; // No company assigned = sees everything
      if (!p.companyId) return !p.departmentId; // Only a fully unassigned product is global
      if (p.companyId !== userCompanyId) return false;
      if (!userIsDepartmentUser || !p.departmentId) return true;
      return userDepartmentIds.includes(p.departmentId);
    });

    return companyFiltered.filter(
      (p) =>
        p.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [products, searchQuery, userCompanyId, userDepartmentIds, userIsAdmin, userIsDepartmentUser]);

  const handleAddToCart = (
    productId: string,
    productName: string,
    imageUrl: string | null,
    isBusinessCard: boolean,
    variantId: string | null,
    variantName: string | null,
    size: string | null,
    quantity: number,
    minQty: number
  ) => {
    addToCart({
      productId,
      productName,
      defaultUnit: products.find((product) => product.id === productId)?.defaultUnit ?? null,
      productImageUrl: imageUrl,
      isBusinessCard,
      productVariantId: variantId,
      variantName,
      size,
      quantity,
      minimumQuantity: minQty,
    });
  };

  const getCartQty = (
    productId: string,
    variantId: string | null,
    size: string | null
  ): number => {
    const item = getItemForProduct(productId, variantId, size);
    return item?.quantity ?? 0;
  };

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {Array.from({ length: 6 }).map((_, i) => (
          <div
            key={i}
            className="overflow-hidden rounded-xl border border-gray-200 bg-white"
          >
            <div className="h-28 animate-pulse bg-gray-100" />
            <div className="p-4 space-y-2">
              <div className="h-4 w-3/4 animate-pulse rounded bg-gray-100" />
              <div className="h-3 w-1/2 animate-pulse rounded bg-gray-100" />
              <div className="h-20 w-full animate-pulse rounded bg-gray-100" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Search Bar */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
        <input
          type="text"
          placeholder="Search products..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="block w-full rounded-lg border border-gray-200 bg-white py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-navy-500 focus:outline-none focus:ring-1 focus:ring-navy-500"
        />
      </div>

      {/* Product Count */}
      <p className="text-xs text-gray-400">
        {filtered.length} product{filtered.length !== 1 ? "s" : ""} available
      </p>

      {/* Product Grid */}
      {filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-gray-400">
          <Package className="mb-3 h-10 w-10" />
          <p className="text-sm font-medium">No products found</p>
          <p className="text-xs">Try adjusting your search</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filtered.map((product) => (
            <ProductCard
              key={product.id}
              product={product}
              onAddToCart={handleAddToCart}
              getCartQty={getCartQty}
            />
          ))}
        </div>
      )}
    </div>
  );
}
