import React, { useState, useEffect } from "react";
import { useParams, Link } from "react-router-dom";
import axios from "axios";
import {
  ArrowLeft,
  ShoppingCart,
  Minus,
  Plus,
  Package,
  Shield,
  Truck,
  Star,
  Send,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Badge } from "../components/ui/badge";
import { Separator } from "../components/ui/separator";
import { Input } from "../components/ui/input";
import { Textarea } from "../components/ui/textarea";
import { Label } from "../components/ui/label";
import { useCart } from "../context/CartContext";
import { useAuth } from "../context/AuthContext";
import { toast } from "sonner";
import ProductImageCarousel from "../components/ProductImageCarousel";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

const ProductDetail = () => {
  const { id } = useParams();
  const [product, setProduct] = useState(null);
  const [loading, setLoading] = useState(true);
  const [quantity, setQuantity] = useState(1);
  const [reviewForm, setReviewForm] = useState({
    rating: 5,
    title: "",
    comment: "",
  });
  const [submittingReview, setSubmittingReview] = useState(false);
  const { addToCart } = useCart();
  const { isAuthenticated, token } = useAuth();

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

  // Auto-refresh every 5 seconds for real-time updates
  useEffect(() => {
    const interval = setInterval(() => {
      fetchProduct(true);
    }, 5000);

    return () => clearInterval(interval);
  }, [id]);

  // Refresh when user returns to the tab
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        fetchProduct();
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);
    return () =>
      document.removeEventListener("visibilitychange", handleVisibilityChange);
  }, [id]);

  const fetchProduct = async (silent = false) => {
    try {
      const response = await axios.get(`${API}/products/${id}`);
      setProduct(response.data);
    } catch (error) {
      console.error("Failed to fetch product:", error);
    } finally {
      if (!silent) setLoading(false);
    }
  };

  const handleAddToCart = async () => {
    if (!isAuthenticated) {
      toast.error("Please login to add items to cart");
      return;
    }
    try {
      await addToCart(product.id, quantity);
      toast.success(`${product.name} added to cart`);
    } catch (error) {
      toast.error("Failed to add item to cart");
    }
  };

  const handleSubmitReview = async (e) => {
    e.preventDefault();
    if (!isAuthenticated) {
      toast.error("Please login to submit a review");
      return;
    }
    setSubmittingReview(true);
    try {
      await axios.post(
        `${API}/reviews`,
        {
          product_id: product.id,
          ...reviewForm,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        },
      );
      toast.success("Review submitted successfully!");
      setReviewForm({ rating: 5, title: "", comment: "" });
      fetchProduct();
    } catch (error) {
      toast.error("Failed to submit review");
    } finally {
      setSubmittingReview(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen py-8 md:py-12">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
            <div className="aspect-square bg-muted rounded-2xl animate-pulse" />
            <div className="space-y-4">
              <div className="h-8 bg-muted rounded w-1/3" />
              <div className="h-12 bg-muted rounded w-2/3" />
              <div className="h-24 bg-muted rounded" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!product) {
    return (
      <div className="min-h-screen py-8 md:py-12">
        <div className="max-w-7xl mx-auto px-4 md:px-8 text-center py-16">
          <h2 className="text-2xl font-bold mb-4 font-['Outfit']">
            Product not found
          </h2>
          <Link to="/products">
            <Button className="rounded-full">Back to Products</Button>
          </Link>
        </div>
      </div>
    );
  }

  const renderStars = (rating, interactive = false, size = "h-4 w-4") => {
    return (
      <div className="flex gap-1">
        {[1, 2, 3, 4, 5].map((star) => (
          <button
            key={star}
            type="button"
            disabled={!interactive}
            onClick={() =>
              interactive && setReviewForm({ ...reviewForm, rating: star })
            }
            className={interactive ? "cursor-pointer" : "cursor-default"}
          >
            <Star
              className={`${size} ${
                star <= rating
                  ? "fill-yellow-400 text-yellow-400"
                  : "text-muted-foreground"
              }`}
            />
          </button>
        ))}
      </div>
    );
  };

  return (
    <div className="min-h-screen py-8 md:py-12">
      <div className="max-w-7xl mx-auto px-4 md:px-8">
        <Link
          to="/products"
          className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground mb-8 transition-colors"
          data-testid="back-to-products"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to Products
        </Link>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Image Carousel */}
          <div className="relative">
            <ProductImageCarousel
              images={
                product.images && product.images.length > 0
                  ? product.images
                  : [product.image_url]
              }
              alt={product.name}
            />
            {product.stock <= 5 && product.stock > 0 && (
              <Badge className="absolute top-4 left-4 bg-orange-500">
                Only {product.stock} left
              </Badge>
            )}
          </div>

          {/* Details */}
          <div className="space-y-6">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <Badge variant="secondary" className="capitalize">
                  {product.category}
                </Badge>
                {product.brand && (
                  <span className="text-sm text-muted-foreground">
                    {product.brand}
                  </span>
                )}
              </div>
              <h1
                className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-4"
                data-testid="product-title"
              >
                {product.name}
              </h1>

              {/* Rating */}
              {product.review_count > 0 && (
                <div className="flex items-center gap-2 mb-4">
                  {renderStars(Math.round(product.average_rating))}
                  <span className="text-sm text-muted-foreground">
                    ({product.average_rating?.toFixed(1)}) ·{" "}
                    {product.review_count} reviews
                  </span>
                </div>
              )}

              <div
                className="text-muted-foreground leading-relaxed prose prose-sm max-w-none max-h-[300px] overflow-y-auto custom-scrollbar pr-2"
                data-testid="product-description"
                dangerouslySetInnerHTML={{ __html: product.description }}
              />
            </div>

            <Separator />

            <div>
              <span className="text-sm text-muted-foreground">Price</span>
              <p
                className="text-4xl font-bold font-['Outfit']"
                data-testid="product-price"
              >
                ${product.price.toFixed(2)}
              </p>
            </div>

            {product.specs && Object.keys(product.specs).length > 0 && (
              <div>
                <h3 className="font-semibold mb-3 font-['Outfit']">
                  Specifications
                </h3>
                <div className="grid grid-cols-2 gap-3">
                  {Object.entries(product.specs).map(([key, value]) => (
                    <div
                      key={key}
                      className="flex justify-between p-3 bg-muted rounded-lg"
                    >
                      <span className="text-sm text-muted-foreground capitalize">
                        {key.replace("_", " ")}
                      </span>
                      <span className="text-sm font-medium">{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <Separator />

            <div className="space-y-4">
              <div className="flex items-center gap-4">
                <span className="text-sm font-medium">Quantity</span>
                <div className="flex items-center border border-input rounded-full">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="rounded-full h-10 w-10"
                    onClick={() => setQuantity(Math.max(1, quantity - 1))}
                    data-testid="quantity-decrease"
                  >
                    <Minus className="h-4 w-4" />
                  </Button>
                  <span
                    className="w-12 text-center font-medium"
                    data-testid="quantity-value"
                  >
                    {quantity}
                  </span>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="rounded-full h-10 w-10"
                    onClick={() =>
                      setQuantity(Math.min(product.stock, quantity + 1))
                    }
                    data-testid="quantity-increase"
                  >
                    <Plus className="h-4 w-4" />
                  </Button>
                </div>
              </div>
              <Button
                size="lg"
                className="w-full rounded-full gap-2 btn-press"
                onClick={handleAddToCart}
                disabled={product.stock === 0}
                data-testid="add-to-cart"
              >
                <ShoppingCart className="h-5 w-5" />
                Add to Cart
              </Button>
              {product.stock === 0 && (
                <p className="text-destructive text-sm">
                  This product is currently out of stock
                </p>
              )}
            </div>

            <div className="grid grid-cols-3 gap-4 pt-4">
              <div className="text-center p-4 rounded-xl bg-muted/50">
                <Truck className="h-6 w-6 mx-auto mb-2 text-primary" />
                <p className="text-xs text-muted-foreground">Free Shipping</p>
              </div>
              <div className="text-center p-4 rounded-xl bg-muted/50">
                <Shield className="h-6 w-6 mx-auto mb-2 text-primary" />
                <p className="text-xs text-muted-foreground">1 Year Warranty</p>
              </div>
              <div className="text-center p-4 rounded-xl bg-muted/50">
                <Package className="h-6 w-6 mx-auto mb-2 text-primary" />
                <p className="text-xs text-muted-foreground">Easy Returns</p>
              </div>
            </div>
          </div>
        </div>

        {/* Reviews Section */}
        <div className="mt-16">
          <Separator className="mb-8" />
          <h2 className="text-2xl font-bold font-['Outfit'] mb-6">
            Customer Reviews
          </h2>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Write Review */}
            <div className="lg:col-span-1">
              <div className="border border-border rounded-xl p-6 bg-card sticky top-24">
                <h3 className="font-semibold mb-4 font-['Outfit']">
                  Write a Review
                </h3>
                <form onSubmit={handleSubmitReview} className="space-y-4">
                  <div className="space-y-2">
                    <Label>Rating</Label>
                    {renderStars(reviewForm.rating, true, "h-6 w-6")}
                  </div>
                  <div className="space-y-2">
                    <Label>Title</Label>
                    <Input
                      value={reviewForm.title}
                      onChange={(e) =>
                        setReviewForm({ ...reviewForm, title: e.target.value })
                      }
                      placeholder="Summary of your review"
                      data-testid="review-title"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Comment</Label>
                    <Textarea
                      value={reviewForm.comment}
                      onChange={(e) =>
                        setReviewForm({
                          ...reviewForm,
                          comment: e.target.value,
                        })
                      }
                      placeholder="Share your experience..."
                      rows={4}
                      data-testid="review-comment"
                    />
                  </div>
                  <Button
                    type="submit"
                    className="w-full rounded-full gap-2"
                    disabled={submittingReview}
                    data-testid="submit-review"
                  >
                    <Send className="h-4 w-4" />
                    {submittingReview ? "Submitting..." : "Submit Review"}
                  </Button>
                </form>
              </div>
            </div>

            {/* Reviews List */}
            <div className="lg:col-span-2 space-y-4">
              {product.reviews && product.reviews.length > 0 ? (
                product.reviews.map((review) => (
                  <div
                    key={review.id}
                    className="border border-border rounded-xl p-6 bg-card"
                    data-testid={`review-${review.id}`}
                  >
                    <div className="flex items-start justify-between mb-3">
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-semibold">
                            {review.user_name}
                          </span>
                          {review.is_verified_purchase && (
                            <Badge variant="secondary" className="text-xs">
                              Verified Purchase
                            </Badge>
                          )}
                        </div>
                        {renderStars(review.rating)}
                      </div>
                      <span className="text-xs text-muted-foreground">
                        {new Date(review.created_at).toLocaleDateString()}
                      </span>
                    </div>
                    {review.title && (
                      <h4 className="font-medium mb-2">{review.title}</h4>
                    )}
                    {review.comment && (
                      <p className="text-sm text-muted-foreground">
                        {review.comment}
                      </p>
                    )}
                  </div>
                ))
              ) : (
                <div className="text-center py-12 border border-border rounded-xl bg-card">
                  <Star className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
                  <p className="text-muted-foreground">
                    No reviews yet. Be the first to review this product!
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProductDetail;
