import { useState } from 'react';
import {
  Minus,
  Plus,
  ShoppingBag,
  X,
  CreditCard,
  ChevronLeft,
  ChevronRight,
  Maximize2,
} from 'lucide-react';
import type { CartItem, Product } from '../../lib/types';

type Props = {
  product: Product | null;
  cartItem?: CartItem;
  onClose: () => void;
  onAdd: () => void;
  onIncrease: () => void;
  onDecrease: () => void;
  onCheckout: () => void;
};

export default function ProductDetailModal({
  product,
  cartItem,
  onClose,
  onAdd,
  onIncrease,
  onDecrease,
  onCheckout,
}: Props) {
  const [activeImage, setActiveImage] = useState(0);
  const [isGalleryOpen, setIsGalleryOpen] = useState(false);

  if (!product) return null;

  const images = product.images?.length ? product.images : [product.image];
  const qty = cartItem?.quantity || 0;

  const maxThumbs = 4;
  const visibleThumbs = images.slice(0, maxThumbs);
  const extraCount = images.length - maxThumbs;

  const prevImage = () => {
    setActiveImage((prev) => (prev === 0 ? images.length - 1 : prev - 1));
  };

  const nextImage = () => {
    setActiveImage((prev) =>
      prev === images.length - 1 ? 0 : prev + 1
    );
  };

  return (
    <>
      {/* MAIN MODAL */}
      <div className="fixed inset-0 z-[80] overflow-y-auto bg-black/60 p-2 backdrop-blur-sm sm:p-4">
        <div className="mx-auto w-full max-w-6xl rounded-2xl bg-white p-4 shadow-2xl sm:p-6">

          {/* HEADER */}
          <div className="mb-4 flex items-center justify-between">
            <h2 className="text-lg font-black text-slate-900 sm:text-xl">
              Product Details
            </h2>

            <button
              onClick={onClose}
              className="rounded-full bg-slate-100 p-2 hover:bg-slate-200"
            >
              <X className="h-5 w-5" />
            </button>
          </div>

          {/* GRID */}
          <div className="grid gap-6 lg:grid-cols-2">

            {/* LEFT SIDE */}
            <div className="flex flex-col gap-3">

              {/* MAIN IMAGE */}
              <button
                onClick={() => setIsGalleryOpen(true)}
                className="group relative overflow-hidden rounded-xl bg-slate-100"
              >
                <img
                  src={images[activeImage]}
                  alt={product.name}
                  className="h-[260px] w-full object-contain sm:h-[360px] md:h-[420px]"
                />

                <div className="absolute right-3 top-3 rounded-full bg-black/60 p-2 text-white opacity-0 transition group-hover:opacity-100">
                  <Maximize2 className="h-5 w-5" />
                </div>
              </button>

              {/* THUMBNAILS UNDER */}
              <div className="flex gap-3 overflow-x-auto pb-1">
                {visibleThumbs.map((img, index) => {
                  const isLastOverlay =
                    index === maxThumbs - 1 && extraCount > 0;

                  return (
                    <button
                      key={index}
                      onClick={() => {
                        setActiveImage(index);
                        if (isLastOverlay) setIsGalleryOpen(true);
                      }}
                      className={`relative h-20 w-20 shrink-0 overflow-hidden rounded-xl border-2 sm:h-24 sm:w-24 ${
                        activeImage === index
                          ? 'border-orange-500'
                          : 'border-transparent'
                      }`}
                    >
                      <img
                        src={img}
                        className="h-full w-full object-cover"
                      />

                      {isLastOverlay && (
                        <div className="absolute inset-0 flex items-center justify-center bg-black/65 text-xl font-black text-white">
                          +{extraCount}
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* RIGHT SIDE */}
            <div className="flex flex-col justify-between">

              <div>
                <h3 className="text-xl font-black text-slate-900 sm:text-2xl">
                  {product.name}
                </h3>

                {/* PRICE */}
                <div className="mt-4 flex items-center gap-3">
                  <span className="text-2xl font-black text-orange-500 sm:text-3xl">
                    ${product.price.toFixed(2)}
                  </span>

                  {product.originalPrice && (
                    <span className="text-sm text-slate-400 line-through sm:text-lg">
                      ${product.originalPrice.toFixed(2)}
                    </span>
                  )}
                </div>

                {/* INFO */}
                <div className="mt-5 space-y-2 text-sm text-slate-900">
                  <p><b>Category:</b> {product.category || '-'}</p>
                  <p><b>Stock:</b> {product.stock ?? 0}</p>

                  {product.badge && (
                    <span className="mt-2 inline-block rounded-full bg-blue-50 px-3 py-1 text-xs font-bold text-blue-700">
                      {product.badge}
                    </span>
                  )}
                </div>

                {/* DESCRIPTION */}
                <div className="mt-6">
                  <h4 className="font-bold text-slate-900">Description</h4>
                  <p className="mt-2 whitespace-pre-line text-sm text-slate-600">
                    {product.description || 'No description available.'}
                  </p>
                </div>
              </div>

              {/* ACTIONS */}
              <div className="mt-6 bg-white pt-4">

                {qty > 0 ? (
                  <div className="mb-3 flex items-center gap-2">
                    <button
                      onClick={onDecrease}
                      className="h-11 w-11 rounded-xl border bg-white"
                    >
                      <Minus />
                    </button>

                    <div className="flex h-11 flex-1 items-center justify-center rounded-xl border font-bold">
                      {qty}
                    </div>

                    <button
                      onClick={onIncrease}
                      className="h-11 w-11 rounded-xl border bg-white"
                    >
                      <Plus />
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={onAdd}
                    className="mb-3 w-full h-11 rounded-xl bg-slate-900 text-white font-bold"
                  >
                    <ShoppingBag className="inline mr-2" />
                    Add to Cart
                  </button>
                )}

                <button
                  onClick={() => {
                    if (qty === 0) onAdd();
                    onCheckout();
                    onClose();
                  }}
                  className="w-full h-11 rounded-xl bg-orange-500 text-white font-bold"
                >
                  <CreditCard className="inline mr-2" />
                  Checkout Now
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* FULLSCREEN GALLERY */}
      {isGalleryOpen && (
        <div className="fixed inset-0 z-[100] bg-black/90 text-white">

          <div className="absolute left-4 top-4 text-sm font-bold">
            {activeImage + 1} / {images.length}
          </div>

          <button
            onClick={() => setIsGalleryOpen(false)}
            className="absolute right-4 top-4 p-3 bg-white/10 rounded-full"
          >
            <X />
          </button>

          <button
            onClick={prevImage}
            className="absolute left-4 top-1/2 -translate-y-1/2 p-3 bg-white/10 rounded-full"
          >
            <ChevronLeft />
          </button>

          <button
            onClick={nextImage}
            className="absolute right-4 top-1/2 -translate-y-1/2 p-3 bg-white/10 rounded-full"
          >
            <ChevronRight />
          </button>

          <div className="flex h-full items-center justify-center px-10 pb-24 pt-14">
            <img
              src={images[activeImage]}
              className="max-h-full max-w-full object-contain"
            />
          </div>

          {/* BOTTOM THUMB */}
          <div className="absolute bottom-4 left-0 right-0 flex justify-center">
            <div className="flex gap-2 overflow-x-auto bg-black/40 p-2 rounded-xl">
              {images.map((img, index) => (
                <button
                  key={index}
                  onClick={() => setActiveImage(index)}
                  className={`h-16 w-16 rounded-lg overflow-hidden border-2 ${
                    activeImage === index
                      ? 'border-orange-500'
                      : 'border-transparent'
                  }`}
                >
                  <img
                    src={img}
                    className="h-full w-full object-cover"
                  />
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
}