"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { FaWhatsapp, FaEye, FaCamera } from "react-icons/fa"; // Imported FaCamera
import Header from "@/app/_components/Header";  // Importing Header
import Footer from "@/app/_components/Footer";  // Importing Footer
import Newsletter from "@/app/_components/Newsletter";  // Importing Newsletter

const cameraData = [
  {
    id: 43,
    promo: "Diskon hingga 20%",
    promoDesc: "Hemat sampai 20% untuk paket acara multi-hari",
    slug: "sony-nx100",
    title: "Sony NX100",
    description: "Kamera dengan kualitas gambar superior dan compact design, ideal untuk event kecil.",
    spec: "Sensor 1 inch | 12x Optical Zoom | WIFI | Stabilizer | HDMI Output",
    reviews: 268,
    rating: 5.0,
    featured: true,
    popular: true,
    priority: 10,
    imgs: { thumbnails: ["/images/sony-nx-100.webp"], previews: ["/images/sony-nx-100.webp"] },
    inStock: true,
    discount: "20%",
    buttonUrl: "https://wa.me/6289528597335?text=Halo%20STJ,%20saya%20ingin%20sewa%20Sony%20NX100",
  },
  {
    id: 50,
    promo: "Gratis Kabel HDMI",
    promoDesc: "Free HDMI 5m + adaptor sesuai kebutuhan",
    slug: "sony-nx200",
    title: "Sony NX200",
    description: "Kamera dengan teknologi canggih dan kemudahan pengoperasian untuk video live streaming.",
    spec: "Sensor 1 inch | 15x Optical Zoom | Dual HDMI Out | GYRO Stabilizer | Long Battery Life",
    reviews: 341,
    rating: 5.0,
    featured: true,
    popular: true,
    priority: 9,
    imgs: { thumbnails: ["/images/sony-nx-200.webp"], previews: ["/images/sony-nx-200.webp"] },
    inStock: true,
    discount: "15%",
    buttonUrl: "https://wa.me/6289528597335?text=Halo%20STJ,%20saya%20ingin%20sewa%20Sony%20NX200",
  },
  {
    id: 55,
    promo: "Diskon Corporate",
    promoDesc: "Harga khusus untuk perusahaan & event organizer",
    slug: "canon-xa75",
    title: "Canon XA75",
    description: "Kamera video HD dengan performa tinggi, ideal untuk produksi profesional dan event besar.",
    spec: "Sensor 1/2.3 inch | Dual Pixel Autofocus | 15x Optical Zoom | 4K Recording | Professional Audio",
    reviews: 412,
    rating: 4.8,
    featured: true,
    popular: true,
    priority: 8,
    imgs: { thumbnails: ["/images/canon-a75.webp"], previews: ["/images/canon-a75.webp"] },
    inStock: true,
    discount: "18%",
    buttonUrl: "https://wa.me/6289528597335?text=Halo%20STJ,%20saya%20ingin%20sewa%20Canon%20XA75",
  },
  {
    id: 60,
    promo: "Termasuk Aksesoris",
    promoDesc: "Gratis aksesoris profesional seperti tripod dan stabilizer",
    slug: "canon-xf605",
    title: "Canon XF605",
    description: "Kamera profesional dengan fitur broadcasting, ideal untuk konferensi dan produksi film.",
    spec: "1-inch CMOS Sensor | 15x Optical Zoom | 4K UHD Recording | 12G SDI | Built-in ND Filters",
    reviews: 189,
    rating: 4.7,
    featured: true,
    popular: false,
    priority: 7,
    imgs: { thumbnails: ["/images/canon-605.webp"], previews: ["/images/canon-605.webp"] },
    inStock: true,
    discount: "15%",
    buttonUrl: "https://wa.me/6289528597335?text=Halo%20STJ,%20saya%20ingin%20sewa%20Canon%20XF605",
  },
  // More camera products can be added here
];

function StarRating({ value = 0 }) {
  const full = Math.floor(value);
  return (
    <div className="flex items-center gap-1">
      {Array.from({ length: 5 }).map((_, i) => (
        <svg
          key={i}
          width="16"
          height="16"
          viewBox="0 0 24 24"
          className={`${i < full ? "fill-amber-400 text-amber-400" : "fill-none text-gray-300"} stroke-current`}
        >
          <path
            strokeWidth="1.5"
            d="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.62L12 2 9.19 8.62 2 9.24l5.46 4.73L5.82 21z"
          />
        </svg>
      ))}
      <span className="text-xs text-gray-500 ml-1">{value.toFixed(1)}</span>
    </div>
  );
}

export default function NewArrival() {
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [quantity, setQuantity] = useState(1);

  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && setSelectedProduct(null);
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const openModal = (p) => {
    setSelectedProduct(p);
    setQuantity(1);
  };
  const closeModal = () => setSelectedProduct(null);

  return (
    <section className="py-12 bg-gradient-to-b from-white to-gray-50">
      <div className="max-w-[1170px] mx-auto px-4 sm:px-8 xl:px-0">
        {/* Header */}
        <Header />

        {/* Breadcrumb */}
        <div className="text-sm bg-gray-200 border-b py-3 mt-[120px]">
          <div className="max-w-[1200px] mx-auto px-6 flex items-center space-x-3 text-gray-600">
            <Link href="/" className="hover:text-blue-600">Beranda</Link>
            <span>/</span>
            <h1 className="text-blue-600 font-semibold">Produk Sewa Kamera</h1>
          </div>
        </div>

        <div className="mb-8 flex items-start justify-between gap-6">
          <div className="max-w-2xl">
            <span className="flex items-center gap-2 text-blue-600 font-medium mb-1">
              {/* Camera icon from React Icons */}
              <FaCamera className="h-5 w-5" />
              Kamera
            </span>
          </div>
        </div>

        {/* Product Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-6">
          {cameraData.map((product) => {
            const waLink = product.buttonUrl;
            const specChips = product.spec.split("|").slice(0, 3).map((s) => s.trim());
            return (
              <article
                key={product.id}
                className="group relative rounded-2xl p-[1px] bg-gradient-to-br from-gray-200 via-gray-100 to-white hover:from-blue-200 hover:via-white hover:to-gray-50 transition"
              >
                <div className="relative h-full rounded-2xl bg-white shadow-sm hover:shadow-md transition overflow-hidden">
                  {product.discount && (
                    <span className="absolute right-3 top-3 z-10 rounded-full bg-amber-500 px-3 py-1 text-xs font-bold text-white shadow">
                      −{product.discount}
                    </span>
                  )}

                  <div className="relative aspect-[4/3] bg-gray-100">
                    <Image
                      src={product.imgs.thumbnails[0]}
                      alt={product.title}
                      fill
                      sizes="(min-width:1280px) 280px, (min-width:1024px) 25vw, (min-width:768px) 33vw, 50vw"
                      className="object-contain p-5 transition-transform duration-300 group-hover:scale-105"
                      priority={product.priority >= 9}
                    />
                    <div className="pointer-events-none absolute inset-0 flex items-center justify-center gap-3 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
                      <button
                        onClick={() => openModal(product)}
                        className="pointer-events-auto inline-flex items-center justify-center rounded-full bg-white/90 p-3 shadow hover:bg-white transition"
                        aria-label={`Lihat detail ${product.title}`}
                        title="Lihat detail"
                      >
                        <FaEye size={16} />
                      </button>
                      <a
                        href={waLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="pointer-events-auto inline-flex items-center justify-center rounded-full bg-white/90 p-3 shadow hover:bg-white transition"
                        aria-label="Sewa via WhatsApp"
                        title="Sewa via WhatsApp"
                      >
                        <FaWhatsapp size={16} />
                      </a>
                    </div>
                  </div>

                  <div className="p-4">
                    <div className="flex items-center">
                      <StarRating value={product.rating} />
                    </div>

                    <h3 className="mt-2 line-clamp-2 text-sm font-semibold text-gray-900">{product.title}</h3>
                    <p className="mt-1 line-clamp-2 text-xs text-gray-600">{product.description}</p>

                    <div className="mt-3 flex flex-wrap gap-2">
                      {specChips.map((chip, i) => (
                        <span key={i} className="rounded-full bg-gray-100 px-2.5 py-1 text-[11px] font-medium text-gray-700">
                          {chip}
                        </span>
                      ))}
                    </div>

                    <div className="flex items-center gap-2">
                      <Link href={`/sewa-kamera`}>
                        <button className="rounded-full border border-gray-300 bg-white px-3 py-1.5 text-xs font-semibold text-gray-800 hover:shadow">
                          Sewa
                        </button>
                      </Link>
                      <a
                        href={waLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="rounded-full bg-[#0ea5e9] px-3 py-1.5 text-xs font-semibold text-white hover:bg-[#0284c7]"
                      >
                        WhatsApp
                      </a>
                    </div>
                  </div>
                </div>
              </article>
            );
          })}
        </div>
      </div>

      {/* Modal */}
      {selectedProduct && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm cursor-pointer"
          onClick={closeModal}
          role="dialog"
          aria-modal="true"
        >
          <div
            className="w-full h-full md:h-auto md:max-w-5xl md:rounded-2xl bg-white shadow-xl relative flex flex-col cursor-auto"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="flex items-center justify-between p-3 border-b bg-white sticky top-0 z-10">
              <h3 className="text-sm md:text-lg font-bold text-gray-900 truncate">
                {selectedProduct.title}
              </h3>
              <button
                onClick={closeModal}
                className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-orange-500 text-white hover:bg-orange-600 cursor-pointer"
                aria-label="Tutup"
                title="Tutup"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                  <path
                    d="M6 6L18 18M6 18L18 6"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>
            </div>

            {/* Konten scrollable */}
            <div className="flex-1 overflow-y-auto p-3 space-y-4">
              {/* Gambar */}
              <div className="relative aspect-[4/3] max-h-56 mx-auto bg-gray-50 rounded-lg cursor-pointer">
                <Image
                  src={selectedProduct.imgs.previews[0]}
                  alt={selectedProduct.title}
                  fill
                  className="object-contain"
                  priority
                  sizes="(max-width: 768px) 90vw, 50vw"
                />
              </div>

              {/* Diskon */}
              {selectedProduct.discount && (
                <span className="inline-block rounded-full bg-amber-500 px-3 py-1 text-xs font-bold text-white cursor-pointer">
                  Disc {selectedProduct.discount}
                </span>
              )}

              {/* Rating & stok */}
              <div className="flex items-center gap-3 cursor-pointer">
                <StarRating value={selectedProduct.rating} />
              </div>

              {/* Deskripsi */}
              <p className="text-sm text-gray-700 cursor-pointer">{selectedProduct.description}</p>

              {/* Spesifikasi */}
              <div className="cursor-pointer">
                <h4 className="text-xs font-bold text-gray-700">Spesifikasi & Include</h4>
                <ul className="mt-1 list-disc pl-5 text-xs text-gray-600 space-y-1">
                  {selectedProduct.spec.split("|").map((s, i) => (
                    <li key={i}>{s.trim()}</li>
                  ))}
                </ul>
              </div>
            </div>

            {/* CTA bawah */}
            <div className="sticky bottom-0 left-0 right-0 bg-white border-t p-3 flex flex-wrap items-center justify-between gap-3">
              <div className="cursor-pointer">
                <span className="text-[10px] font-bold text-gray-600">Harga Sewa</span>
                <div className="text-base font-extrabold text-blue-600">Hubungi Kami</div>
              </div>

              {/* Qty */}
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                  className="h-7 w-7 rounded-full bg-gray-200 text-gray-800 hover:bg-gray-300 text-xs cursor-pointer"
                >
                  −
                </button>
                <span className="w-6 text-center text-sm">{quantity}</span>
                <button
                  onClick={() => setQuantity((q) => q + 1)}
                  className="h-7 w-7 rounded-full bg-gray-200 text-gray-800 hover:bg-gray-300 text-xs cursor-pointer"
                >
                  +
                </button>
              </div>

              {/* WA */}
              <a
                href={`https://wa.me/6289528597335?text=${encodeURIComponent(
                  `Halo STJ, Saya ingin sewa ${selectedProduct.title} sebanyak ${quantity} unit.`
                )}`}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1 rounded-full bg-[#22c55e] px-4 py-1.5 text-xs font-semibold text-white hover:bg-[#16a34a] cursor-pointer"
              >
                <FaWhatsapp size={14} />
                WhatsApp
              </a>
            </div>
          </div>
        </div>
      )}

      <Newsletter />
      <Footer />
    </section>
  );
}
