import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { getProduct } from '../utils/api';

const ProductDetailPage = () => {
  const { id } = useParams();
  const [product, setProduct] = useState(null);
  const [loading, setLoading] = useState(true);
  const [selectedImage, setSelectedImage] = useState(0);
  const [quantity, setQuantity] = useState(1);

  useEffect(() => {
    loadProduct();
  }, [id]);

  const loadProduct = async () => {
    try {
      const response = await getProduct(id);
      setProduct(response.data);
    } catch (error) {
      console.error('Error loading product:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatPrice = (price) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      minimumFractionDigits: 0
    }).format(price);
  };

  const handleWhatsAppCheckout = () => {
    const phone = '6281554333316';
    const message = `Halo, saya tertarik dengan produk berikut:

📦 *${product.name}*
💰 Harga: ${formatPrice(product.price)}
🔢 Jumlah: ${quantity}
💵 Total: ${formatPrice(product.price * quantity)}

Mohon info ketersediaan stok dan cara pembayaran. Terima kasih!`;

    const encodedMessage = encodeURIComponent(message);
    window.open(`https://wa.me/${phone}?text=${encodedMessage}`, '_blank');
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-xl text-gray-600">Loading...</div>
      </div>
    );
  }

  if (!product) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-red-600 mb-4">Produk tidak ditemukan</p>
          <Link to="/shop" className="text-blue-600 hover:text-blue-700">
            ← Kembali ke Shop
          </Link>
        </div>
      </div>
    );
  }

  const hasDiscount = product.original_price > product.price;
  const discount = hasDiscount
    ? Math.round(((product.original_price - product.price) / product.original_price) * 100)
    : 0;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-5 py-4 flex justify-between items-center">
          <Link to="/" className="flex items-center gap-3">
            <img src="/assets/img/logo1.png" alt="Logo" className="h-12" />
            <div>
              <div className="text-xl font-bold text-gray-900">
                <strong className="text-blue-600">RH</strong> Elektronik
              </div>
            </div>
          </Link>

          <Link to="/shop" className="text-gray-700 font-semibold hover:text-blue-600">
            ← Kembali ke Shop
          </Link>
        </div>
      </header>

      {/* Product Detail */}
      <div className="max-w-7xl mx-auto px-5 py-12">
        <div className="grid md:grid-cols-2 gap-12">
          {/* Images */}
          <div>
            {/* Main Image */}
            <div className="bg-white rounded-2xl overflow-hidden shadow-lg mb-4">
              {product.images && product.images.length > 0 ? (
                <img
                  src={product.images[selectedImage]}
                  alt={product.name}
                  className="w-full h-96 object-cover"
                />
              ) : (
                <div className="w-full h-96 flex items-center justify-center bg-gray-100 text-gray-400 text-9xl">
                  📦
                </div>
              )}
            </div>

            {/* Thumbnails */}
            {product.images && product.images.length > 1 && (
              <div className="flex gap-3">
                {product.images.map((image, index) => (
                  <button
                    key={index}
                    onClick={() => setSelectedImage(index)}
                    className={`flex-1 rounded-xl overflow-hidden border-4 transition ${
                      selectedImage === index
                        ? 'border-blue-600'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <img src={image} alt={`${product.name} ${index + 1}`} className="w-full h-24 object-cover" />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Product Info */}
          <div>
            <div className="bg-white rounded-2xl shadow-lg p-8">
              {/* Category & Brand */}
              <div className="flex gap-3 mb-4">
                <span className="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm font-semibold">
                  {product.category}
                </span>
                {product.brand && (
                  <span className="bg-gray-100 text-gray-700 px-3 py-1 rounded-full text-sm font-semibold">
                    {product.brand}
                  </span>
                )}
              </div>

              {/* Title */}
              <h1 className="text-3xl font-extrabold text-gray-900 mb-4">{product.name}</h1>

              {/* Price */}
              <div className="mb-6 pb-6 border-b">
                {hasDiscount && (
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-xl text-gray-400 line-through">{formatPrice(product.original_price)}</span>
                    <span className="bg-red-500 text-white px-3 py-1 rounded-full font-bold text-sm">
                      HEMAT {discount}%
                    </span>
                  </div>
                )}
                <div className="text-4xl font-extrabold text-blue-600">{formatPrice(product.price)}</div>
              </div>

              {/* Stock */}
              <div className="mb-6">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-gray-700 font-semibold">Ketersediaan:</span>
                  {product.is_available ? (
                    <span className="text-green-600 font-bold">✅ Tersedia ({product.stock} stok)</span>
                  ) : (
                    <span className="text-red-600 font-bold">❌ Stok Habis</span>
                  )}
                </div>
              </div>

              {/* Quantity */}
              <div className="mb-6">
                <label className="block text-gray-700 font-semibold mb-2">Jumlah:</label>
                <div className="flex items-center gap-3">
                  <button
                    onClick={() => setQuantity(Math.max(1, quantity - 1))}
                    className="w-12 h-12 bg-gray-200 rounded-lg font-bold text-xl hover:bg-gray-300 transition"
                  >
                    -
                  </button>
                  <input
                    type="number"
                    value={quantity}
                    onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
                    className="w-20 h-12 text-center border-2 border-gray-300 rounded-lg font-bold text-xl"
                  />
                  <button
                    onClick={() => setQuantity(Math.min(product.stock, quantity + 1))}
                    className="w-12 h-12 bg-gray-200 rounded-lg font-bold text-xl hover:bg-gray-300 transition"
                  >
                    +
                  </button>
                </div>
              </div>

              {/* Total */}
              <div className="mb-6 bg-gray-50 p-4 rounded-xl">
                <div className="flex items-center justify-between">
                  <span className="text-gray-700 font-semibold text-lg">Total Harga:</span>
                  <span className="text-3xl font-extrabold text-blue-600">
                    {formatPrice(product.price * quantity)}
                  </span>
                </div>
              </div>

              {/* Checkout Button */}
              <button
                onClick={handleWhatsAppCheckout}
                disabled={!product.is_available}
                className="w-full bg-green-500 text-white py-4 rounded-xl font-bold text-lg hover:bg-green-600 transition disabled:opacity-50 disabled:cursor-not-allowed shadow-lg flex items-center justify-center gap-3"
              >
                <span className="text-2xl">📱</span>
                Beli via WhatsApp
              </button>
              <p className="text-center text-sm text-gray-500 mt-3">
                Klik untuk chat langsung dengan kami di WhatsApp
              </p>
            </div>

            {/* Description */}
            <div className="bg-white rounded-2xl shadow-lg p-8 mt-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-4">📝 Deskripsi Produk</h2>
              <div className="text-gray-700 whitespace-pre-line leading-relaxed">
                {product.description}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className="bg-gray-900 text-gray-400 text-center py-10 mt-20">
        <p>© 2026 CV RH Elektronik - Authorized Service Center</p>
      </footer>
    </div>
  );
};

export default ProductDetailPage;
