"use client";

import React, { useState, useEffect } from "react";
import { Product, Review } from "@/types";
import { useCart } from "@/context/CartContext";
import {
  X,
  Star,
  ShoppingCart,
  Zap,
  Heart,
  Truck,
  ShieldCheck,
  RotateCcw,
  CheckCircle2,
  Plus,
  Minus,
  Share2,
  MessageSquare,
  Sparkles,
} from "lucide-react";

export const ProductModal: React.FC = () => {
  const {
    activeProductModal,
    closeProductModal,
    addToCart,
    buyNow,
    toggleWishlist,
    isInWishlist,
    recentlyViewed,
  } = useCart();

  const [selectedImage, setSelectedImage] = useState<string>("");
  const [quantity, setQuantity] = useState<number>(1);
  const [activeTab, setActiveTab] = useState<"desc" | "specs" | "delivery" | "reviews">("desc");
  const [reviewsList, setReviewsList] = useState<Review[]>([]);
  const [isLoadingReviews, setIsLoadingReviews] = useState(false);

  // New review state
  const [reviewAuthor, setReviewAuthor] = useState("");
  const [reviewRating, setReviewRating] = useState(5);
  const [reviewTitle, setReviewTitle] = useState("");
  const [reviewComment, setReviewComment] = useState("");
  const [isSubmittingReview, setIsSubmittingReview] = useState(false);
  const [reviewSuccessMsg, setReviewSuccessMsg] = useState("");

  useEffect(() => {
    if (activeProductModal) {
      setSelectedImage(activeProductModal.image);
      setQuantity(1);
      setActiveTab("desc");
      fetchReviews(activeProductModal.id);
    }
  }, [activeProductModal]);

  const fetchReviews = async (productId: string) => {
    setIsLoadingReviews(true);
    try {
      const res = await fetch(`/api/reviews?productId=${productId}`);
      const data = await res.json();
      if (data.reviews) setReviewsList(data.reviews);
    } catch (e) {
      console.error("Failed to load reviews", e);
    } finally {
      setIsLoadingReviews(false);
    }
  };

  const handleReviewSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeProductModal || !reviewAuthor || !reviewComment) return;

    setIsSubmittingReview(true);
    try {
      const res = await fetch("/api/reviews", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          productId: activeProductModal.id,
          author: reviewAuthor,
          location: "South Africa",
          rating: reviewRating,
          title: reviewTitle || "Verified Purchase Review",
          comment: reviewComment,
        }),
      });

      const data = await res.json();
      if (data.success) {
        setReviewSuccessMsg("Thank you! Your review has been submitted.");
        setReviewAuthor("");
        setReviewTitle("");
        setReviewComment("");
        fetchReviews(activeProductModal.id);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsSubmittingReview(false);
    }
  };

  if (!activeProductModal) return null;

  const product = activeProductModal;
  const inWishlist = isInWishlist(product.id);
  const numericPrice = typeof product.price === "number" ? product.price : parseFloat(product.price);
  const numericOriginal = product.originalPrice
    ? typeof product.originalPrice === "number"
      ? product.originalPrice
      : parseFloat(product.originalPrice)
    : null;

  const galleryImages = [
    product.image,
    ...(product.gallery || []),
  ].filter((v, i, a) => a.indexOf(v) === i);

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/70 backdrop-blur-sm flex items-center justify-center p-3 sm:p-6 animate-fadeIn">
      <div className="relative bg-white rounded-3xl shadow-2xl border border-slate-200 w-full max-w-5xl max-h-[90vh] overflow-y-auto my-auto">
        {/* Close Button */}
        <button
          onClick={closeProductModal}
          className="absolute top-4 right-4 z-20 bg-slate-100 hover:bg-slate-200 text-slate-700 p-2 rounded-full transition-colors"
          aria-label="Close"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="p-5 sm:p-8">
          <div className="grid lg:grid-cols-12 gap-8 items-start">
            {/* Left Image Gallery Column */}
            <div className="lg:col-span-6 space-y-4">
              <div className="relative rounded-2xl bg-slate-100 overflow-hidden border border-slate-200 aspect-square">
                <img
                  src={selectedImage || product.image}
                  alt={product.name}
                  className="w-full h-full object-cover"
                />

                <button
                  onClick={() => toggleWishlist(product)}
                  className={`absolute top-3 right-3 p-2.5 rounded-full shadow-md transition-colors ${
                    inWishlist ? "bg-rose-50 text-rose-600" : "bg-white text-slate-400 hover:text-rose-600"
                  }`}
                >
                  <Heart className={`w-5 h-5 ${inWishlist ? "fill-rose-600" : ""}`} />
                </button>
              </div>

              {/* Gallery Thumbnails */}
              {galleryImages.length > 1 && (
                <div className="flex gap-3 overflow-x-auto pb-1">
                  {galleryImages.map((imgUrl, idx) => (
                    <button
                      key={idx}
                      onClick={() => setSelectedImage(imgUrl)}
                      className={`w-16 h-16 rounded-xl border-2 overflow-hidden shrink-0 transition-all ${
                        selectedImage === imgUrl ? "border-blue-900 ring-2 ring-blue-900/30" : "border-slate-200 opacity-70 hover:opacity-100"
                      }`}
                    >
                      <img src={imgUrl} alt="" className="w-full h-full object-cover" />
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Right Product Details Column */}
            <div className="lg:col-span-6 space-y-5">
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-bold text-amber-700 uppercase tracking-wider bg-amber-100 px-2.5 py-0.5 rounded-md">
                    {product.brandName}
                  </span>
                  <span className="text-xs text-slate-500 font-mono">SKU: {product.sku}</span>
                </div>

                <h1 className="text-xl sm:text-2xl font-black text-slate-900 leading-snug">
                  {product.name}
                </h1>

                {/* Rating */}
                <div className="flex items-center gap-2 mt-2">
                  <div className="flex text-amber-400">
                    {[1, 2, 3, 4, 5].map((s) => (
                      <Star key={s} className="w-4 h-4 fill-amber-400 text-amber-400" />
                    ))}
                  </div>
                  <span className="text-xs font-bold text-slate-800">
                    {product.rating || "4.9"} out of 5
                  </span>
                  <span className="text-xs text-slate-400">&bull; {reviewsList.length || product.reviewCount || 12} Verified Customer Reviews</span>
                </div>
              </div>

              {/* Price Tag */}
              <div className="p-4 bg-slate-50 rounded-2xl border border-slate-200 flex items-center justify-between">
                <div>
                  <span className="text-2xl sm:text-3xl font-black text-slate-950">
                    R{numericPrice.toFixed(2)}
                  </span>
                  {numericOriginal && (
                    <span className="ml-2 text-sm text-slate-400 line-through">
                      R{numericOriginal.toFixed(2)}
                    </span>
                  )}
                  <div className="text-[11px] text-slate-500 font-medium">Includes 15% South African VAT</div>
                </div>

                <div className="text-right">
                  <span className="inline-flex items-center gap-1 text-xs font-bold text-emerald-700 bg-emerald-100 px-2.5 py-1 rounded-full">
                    <CheckCircle2 className="w-3.5 h-3.5" /> In Stock - JHB & CPT
                  </span>
                  <div className="text-[11px] text-slate-500 mt-1">Dispatched in 24 hrs</div>
                </div>
              </div>

              {/* Quantity Selector & Action CTAs */}
              <div className="space-y-3">
                <div className="flex items-center gap-4">
                  <span className="text-xs font-bold uppercase text-slate-600">Quantity:</span>
                  <div className="flex items-center border border-slate-300 rounded-xl overflow-hidden bg-slate-100">
                    <button
                      onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                      className="p-2 text-slate-700 hover:bg-slate-200 transition-colors"
                    >
                      <Minus className="w-4 h-4" />
                    </button>
                    <span className="px-4 text-sm font-bold text-slate-900">{quantity}</span>
                    <button
                      onClick={() => setQuantity((q) => q + 1)}
                      className="p-2 text-slate-700 hover:bg-slate-200 transition-colors"
                    >
                      <Plus className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                <div className="grid sm:grid-cols-2 gap-3 pt-2">
                  <button
                    onClick={() => {
                      addToCart(product, quantity);
                    }}
                    className="py-3 px-4 bg-blue-950 hover:bg-slate-900 text-white font-extrabold text-sm rounded-xl flex items-center justify-center gap-2 shadow-md transition-all cursor-pointer"
                  >
                    <ShoppingCart className="w-4 h-4 text-amber-400" />
                    <span>ADD TO CART</span>
                  </button>

                  <button
                    onClick={() => {
                      buyNow(product, quantity);
                      closeProductModal();
                    }}
                    className="py-3 px-4 bg-amber-500 hover:bg-amber-600 text-slate-950 font-extrabold text-sm rounded-xl flex items-center justify-center gap-2 shadow-md transition-all cursor-pointer"
                  >
                    <Zap className="w-4 h-4 fill-slate-950" />
                    <span>BUY NOW & CHECKOUT</span>
                  </button>
                </div>
              </div>

              {/* Quick Trust Badges */}
              <div className="grid grid-cols-3 gap-2 pt-2 text-[11px] text-slate-600 font-medium border-t border-slate-100">
                <div className="flex items-center gap-1.5">
                  <Truck className="w-4 h-4 text-blue-900 shrink-0" />
                  <span>Door Courier SA</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <ShieldCheck className="w-4 h-4 text-emerald-600 shrink-0" />
                  <span>Original Brand</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <RotateCcw className="w-4 h-4 text-amber-600 shrink-0" />
                  <span>30-Day Returns</span>
                </div>
              </div>
            </div>
          </div>

          {/* Details Accordion / Tabs Section */}
          <div className="mt-8 pt-6 border-t border-slate-200">
            <div className="flex border-b border-slate-200 overflow-x-auto gap-4">
              <button
                onClick={() => setActiveTab("desc")}
                className={`pb-3 text-sm font-bold border-b-2 transition-colors whitespace-nowrap cursor-pointer ${
                  activeTab === "desc"
                    ? "border-blue-900 text-blue-950"
                    : "border-transparent text-slate-500 hover:text-slate-800"
                }`}
              >
                Product Description
              </button>
              <button
                onClick={() => setActiveTab("specs")}
                className={`pb-3 text-sm font-bold border-b-2 transition-colors whitespace-nowrap cursor-pointer ${
                  activeTab === "specs"
                    ? "border-blue-900 text-blue-950"
                    : "border-transparent text-slate-500 hover:text-slate-800"
                }`}
              >
                Technical Specifications
              </button>
              <button
                onClick={() => setActiveTab("delivery")}
                className={`pb-3 text-sm font-bold border-b-2 transition-colors whitespace-nowrap cursor-pointer ${
                  activeTab === "delivery"
                    ? "border-blue-900 text-blue-950"
                    : "border-transparent text-slate-500 hover:text-slate-800"
                }`}
              >
                South Africa Courier Info
              </button>
              <button
                onClick={() => setActiveTab("reviews")}
                className={`pb-3 text-sm font-bold border-b-2 transition-colors whitespace-nowrap cursor-pointer ${
                  activeTab === "reviews"
                    ? "border-blue-900 text-blue-950"
                    : "border-transparent text-slate-500 hover:text-slate-800"
                }`}
              >
                Customer Reviews ({reviewsList.length})
              </button>
            </div>

            <div className="py-5 text-sm text-slate-700 leading-relaxed">
              {activeTab === "desc" && (
                <div className="space-y-3">
                  <p>{product.description}</p>
                  <p className="text-xs text-slate-500">
                    Diverse Stationery Co. guarantees authentic stock sourced directly from official South African importers and manufacturers. Perfect for school requirement lists and corporate procurement.
                  </p>
                </div>
              )}

              {activeTab === "specs" && (
                <div className="space-y-2">
                  <h4 className="font-bold text-slate-900 text-xs uppercase tracking-wider mb-2">Key Specifications:</h4>
                  <ul className="space-y-1.5 list-disc list-inside bg-slate-50 p-4 rounded-2xl border border-slate-200">
                    {product.specs?.map((spec, i) => (
                      <li key={i} className="text-slate-800 font-medium">
                        {spec}
                      </li>
                    )) || <li>100% High Grade Stationery Product</li>}
                  </ul>
                </div>
              )}

              {activeTab === "delivery" && (
                <div className="space-y-3">
                  <div className="grid sm:grid-cols-2 gap-4">
                    <div className="p-4 bg-slate-50 rounded-2xl border border-slate-200">
                      <h5 className="font-bold text-slate-900 mb-1">Gauteng & Major SA Hubs</h5>
                      <p className="text-xs text-slate-600">1 to 2 business days via Courier Guy / Aramex. Free on orders over R750.</p>
                    </div>
                    <div className="p-4 bg-slate-50 rounded-2xl border border-slate-200">
                      <h5 className="font-bold text-slate-900 mb-1">Regional & Outlying Areas</h5>
                      <p className="text-xs text-slate-600">2 to 4 business days. Standard flat rate R85 nationwide.</p>
                    </div>
                  </div>
                </div>
              )}

              {activeTab === "reviews" && (
                <div className="space-y-6">
                  {/* Reviews List */}
                  {reviewsList.length === 0 ? (
                    <p className="text-slate-500 text-xs italic">No customer reviews yet. Be the first to review this product!</p>
                  ) : (
                    <div className="space-y-4">
                      {reviewsList.map((rev) => (
                        <div key={rev.id || Math.random()} className="p-4 bg-slate-50 rounded-2xl border border-slate-200 space-y-1">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <span className="font-bold text-slate-900 text-xs">{rev.author}</span>
                              <span className="text-[10px] text-slate-400">({rev.location})</span>
                            </div>
                            <div className="flex text-amber-400">
                              {[...Array(rev.rating)].map((_, i) => (
                                <Star key={i} className="w-3.5 h-3.5 fill-amber-400" />
                              ))}
                            </div>
                          </div>
                          <div className="font-semibold text-slate-800 text-xs">{rev.title}</div>
                          <p className="text-slate-600 text-xs">{rev.comment}</p>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Submit Review Form */}
                  <form onSubmit={handleReviewSubmit} className="p-4 bg-blue-50/50 rounded-2xl border border-blue-100 space-y-3">
                    <h4 className="font-bold text-slate-900 text-xs">Write a Review for {product.name}</h4>
                    {reviewSuccessMsg && <p className="text-xs text-emerald-700 font-bold">{reviewSuccessMsg}</p>}

                    <div className="grid sm:grid-cols-2 gap-3">
                      <input
                        type="text"
                        placeholder="Your Name"
                        value={reviewAuthor}
                        onChange={(e) => setReviewAuthor(e.target.value)}
                        required
                        className="px-3 py-2 text-xs bg-white border border-slate-300 rounded-xl"
                      />
                      <select
                        value={reviewRating}
                        onChange={(e) => setReviewRating(Number(e.target.value))}
                        className="px-3 py-2 text-xs bg-white border border-slate-300 rounded-xl"
                      >
                        <option value={5}>5 Stars ★★★★★ - Excellent</option>
                        <option value={4}>4 Stars ★★★★☆ - Very Good</option>
                        <option value={3}>3 Stars ★★★☆☆ - Average</option>
                      </select>
                    </div>

                    <input
                      type="text"
                      placeholder="Review Headline (e.g. Great quality paper)"
                      value={reviewTitle}
                      onChange={(e) => setReviewTitle(e.target.value)}
                      className="w-full px-3 py-2 text-xs bg-white border border-slate-300 rounded-xl"
                    />

                    <textarea
                      placeholder="Share details of your experience with this product..."
                      value={reviewComment}
                      onChange={(e) => setReviewComment(e.target.value)}
                      required
                      rows={2}
                      className="w-full px-3 py-2 text-xs bg-white border border-slate-300 rounded-xl"
                    />

                    <button
                      type="submit"
                      disabled={isSubmittingReview}
                      className="px-4 py-2 bg-blue-950 text-white font-bold text-xs rounded-xl hover:bg-slate-900 transition-colors"
                    >
                      {isSubmittingReview ? "Submitting..." : "Submit Verified Review"}
                    </button>
                  </form>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
