"use client";

import { useState } from "react";
import api from "@/lib/api";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { getGuestToken } from "@/lib/guestToken";
import toast from "react-hot-toast";

import {
  ShoppingCart,
  Heart,
  Star,
  Truck,
  ShieldCheck,
  RotateCcw,
  Minus,
  Plus,
  CheckCircle,
} from "lucide-react";

interface ProductImage {
  id: number;
  image: string;
  alt_text?: string;
}

interface Product {
  id: number;
  name: string;
  slug: string;
  sku?: string;
  price: string;
  sale_price?: string | null;
  short_description?: string;
  description?: string;
  stock_quantity: number;
  stock_status: string;
  unit_type?: string;
  unit_value?: string;
  brand?: { name: string; slug: string } | null;
  category?: { name: string; slug: string } | null;
  images: ProductImage[];
}

export default function SingleProductClient({ product }: { product: Product }) {
  const [activeImage, setActiveImage] = useState(
    product.images?.[0]?.image || ""
  );
  const [quantity, setQuantity] = useState(1);

  const finalPrice = Number(product.sale_price || product.price || 0);
  const regularPrice = Number(product.price || 0);

  const discount =
    product.sale_price && regularPrice > finalPrice
      ? Math.round(((regularPrice - finalPrice) / regularPrice) * 100)
      : 0;

  const addToWishlist = async () => {
    await api.post("/wishlist/toggle", {
      product_id: product.id,
      guest_token: getGuestToken(),
    });

    toast.success("Wishlist updated");
  };

  const addToCart = async () => {
    await api.post("/cart/add", {
      product_id: product.id,
      quantity,
      guest_token: getGuestToken(),
    });

    window.dispatchEvent(new Event("cart-updated"));
    toast.success("Added to cart");
  };

  return (
    <>
      <Navbar />

      <main className="bg-[#f7fff8] min-h-screen">
        <section className="max-w-7xl mx-auto px-4 py-10">
          <div className="mb-6 text-sm text-slate-500 font-semibold">
            Home / Products /{" "}
            <span className="text-green-600">{product.name}</span>
          </div>

          <div className="grid lg:grid-cols-2 gap-10 bg-white rounded-[2rem] p-5 md:p-8 border border-green-100 shadow-sm">
            <div>
              <div className="relative bg-slate-50 rounded-[2rem] overflow-hidden border border-slate-100">
                {discount > 0 && (
                  <span className="absolute top-5 left-5 z-10 bg-red-500 text-white text-xs font-black px-4 py-2 rounded-full">
                    {discount}% OFF
                  </span>
                )}

                <img
                  src={activeImage || "https://via.placeholder.com/700"}
                  alt={product.name}
                  className="w-full h-[420px] md:h-[560px] object-cover"
                />
              </div>

              <div className="grid grid-cols-5 gap-3 mt-4">
                {product.images?.map((img) => (
                  <button
                    key={img.id}
                    onClick={() => setActiveImage(img.image)}
                    className={`rounded-2xl overflow-hidden border-2 bg-slate-50 ${
                      activeImage === img.image
                        ? "border-green-600"
                        : "border-transparent"
                    }`}
                  >
                    <img
                      src={img.image}
                      alt={img.alt_text || product.name}
                      className="w-full h-20 object-cover"
                    />
                  </button>
                ))}
              </div>
            </div>

            <div className="flex flex-col">
              <div className="flex flex-wrap gap-3 mb-4">
                <span className="bg-green-50 text-green-700 px-4 py-2 rounded-full text-xs font-black uppercase">
                  {product.category?.name || "Fresh Product"}
                </span>

                {product.stock_status === "in_stock" ? (
                  <span className="bg-emerald-50 text-emerald-700 px-4 py-2 rounded-full text-xs font-black flex items-center gap-1">
                    <CheckCircle size={14} /> In Stock
                  </span>
                ) : (
                  <span className="bg-red-50 text-red-600 px-4 py-2 rounded-full text-xs font-black">
                    Out of Stock
                  </span>
                )}
              </div>

              <h1 className="text-3xl md:text-5xl font-black text-slate-900 leading-tight">
                {product.name}
              </h1>

              <div className="flex items-center gap-3 mt-4">
                <div className="flex text-orange-400">
                  {[...Array(5)].map((_, i) => (
                    <Star key={i} size={18} fill="currentColor" />
                  ))}
                </div>
                <span className="text-sm text-slate-500 font-semibold">
                  5.0 Reviews
                </span>
              </div>

              <p className="mt-5 text-slate-600 leading-8">
                {product.short_description}
              </p>

              <div className="mt-6 flex items-end gap-3">
                <span className="text-4xl font-black text-green-600">
                  ৳{finalPrice}
                </span>

                {product.sale_price && (
                  <span className="text-xl text-slate-400 line-through font-bold mb-1">
                    ৳{product.price}
                  </span>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4 mt-7 text-sm">
                <Info title="Unit" value={`${product.unit_value || ""} ${product.unit_type || ""}`} />
                <Info title="SKU" value={product.sku || "N/A"} />
                <Info title="Brand" value={product.brand?.name || "No Brand"} />
                <Info title="Available" value={`${product.stock_quantity} items`} />
              </div>

              <div className="mt-8 flex flex-col sm:flex-row gap-4">
                <div className="flex items-center justify-between bg-slate-100 rounded-2xl px-4 py-3 sm:w-40">
                  <button
                    onClick={() => setQuantity(Math.max(1, quantity - 1))}
                    className="cursor-pointer w-9 h-9 rounded-xl bg-white flex items-center justify-center"
                  >
                    <Minus size={16} />
                  </button>

                  <span className="font-black">{quantity}</span>

                  <button
                    onClick={() => setQuantity(quantity + 1)}
                    className="cursor-pointer w-9 h-9 rounded-xl bg-white flex items-center justify-center"
                  >
                    <Plus size={16} />
                  </button>
                </div>

                <button
                  onClick={addToCart}
                  className="cursor-pointer flex-1 bg-green-600 hover:bg-green-700 text-white rounded-2xl py-4 font-black flex items-center justify-center gap-2 transition"
                >
                  <ShoppingCart size={20} />
                  Add to Cart
                </button>

                <button
                  onClick={addToWishlist}
                  className="cursor-pointer w-full sm:w-16 h-16 rounded-2xl bg-red-50 text-red-500 flex items-center justify-center hover:bg-red-100 transition"
                >
                  <Heart size={22} />
                </button>
              </div>

              <div className="grid sm:grid-cols-3 gap-4 mt-8">
                <Feature icon={<Truck />} title="Fast Delivery" />
                <Feature icon={<ShieldCheck />} title="Secure Payment" />
                <Feature icon={<RotateCcw />} title="Easy Return" />
              </div>
            </div>
          </div>

          <div className="mt-10 bg-white rounded-[2rem] p-6 md:p-8 border border-green-100 shadow-sm">
            <h2 className="text-2xl font-black text-slate-900 mb-4">
              Product Description
            </h2>

            <div
              className="prose max-w-none text-slate-600 leading-8"
              dangerouslySetInnerHTML={{
                __html: product.description || "No description available.",
              }}
            />
          </div>
        </section>
      </main>

      <Footer />
    </>
  );
}

function Info({ title, value }: { title: string; value: string }) {
  return (
    <div className="bg-slate-50 rounded-2xl p-4">
      <p className="text-slate-400 font-bold">{title}</p>
      <p className="font-black text-slate-800">{value}</p>
    </div>
  );
}

function Feature({
  icon,
  title,
}: {
  icon: React.ReactNode;
  title: string;
}) {
  return (
    <div className="bg-green-50 rounded-2xl p-4 flex items-center gap-3">
      <div className="text-green-600">{icon}</div>
      <p className="text-sm font-black text-slate-800">{title}</p>
    </div>
  );
}