import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import productService from '../services/productService';
import cartService from '../services/cartService';
import './ProductDetails.css';

const ProductDetails = () => {
  const location = useLocation();
  const selectedProduct = location.state?.selectedProduct; // Product passed from Shop page
  
  const [products, setProducts] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('details');
  const [selectedSize, setSelectedSize] = useState('Large');

  useEffect(() => {
    fetchProducts();
  }, []);

  useEffect(() => {
    // If a product was selected from Shop page, find it and set as current
    if (selectedProduct && products.length > 0) {
      const productIndex = products.findIndex(p => p.id === selectedProduct.id);
      if (productIndex !== -1) {
        setCurrentIndex(productIndex);
      }
    }
  }, [selectedProduct, products]);

  const fetchProducts = async () => {
    try {
      setLoading(true);
      const data = await productService.getProducts();
      setProducts(data.products || []);
      setLoading(false);
    } catch (err) {
      console.error('Error fetching products:', err);
      setError('Failed to load products. Please try again later.');
      setLoading(false);
    }
  };

  const currentProduct = products[currentIndex];

  const handlePrevious = () => {
    setCurrentIndex((prev) => (prev > 0 ? prev - 1 : products.length - 1));
  };

  const handleNext = () => {
    setCurrentIndex((prev) => (prev < products.length - 1 ? prev + 1 : 0));
  };

  const navigate = useNavigate();

  const handleAddToCart = async () => {
    if (!currentProduct) return;
    try {
      await cartService.addToCart(currentProduct.id, 1);
      alert(`Added ${currentProduct.name} to cart.`);
    } catch (err) {
      // If unauthorized, redirect to login
      if (err.response && (err.response.status === 401 || err.response.status === 403)) {
        alert('Please login to add items to your cart.');
        navigate('/auth');
      } else if (err.response && err.response.data && err.response.data.message) {
        alert(err.response.data.message);
      } else {
        console.error('Add to cart error', err);
        alert('Failed to add to cart. Please try again later.');
      }
    }
  };

  if (loading) {
    return (
      <div className="product-details-loading">
        <p>Loading products...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="product-details-error">
        <p>{error}</p>
        <button onClick={fetchProducts}>Retry</button>
      </div>
    );
  }

  if (!currentProduct) {
    return (
      <div className="product-details-error">
        <p>No products available</p>
      </div>
    );
  }

  return (
    <div className="product-details-container">
      <div className="product-details-wrapper">
        {/* Left Panel - Details */}
        <div className="details-panel">
          <h2 className="details-title">Details</h2>
          
          <div className="details-tabs">
            <button 
              className={`tab-button ${activeTab === 'details' ? 'active' : ''}`}
              onClick={() => setActiveTab('details')}
            >
              {currentProduct.category || 'Product'}
            </button>
            <button 
              className={`tab-button ${activeTab === 'sale' ? 'active' : ''}`}
              onClick={() => setActiveTab('sale')}
            >
              Sale
            </button>
            <button 
              className={`tab-button ${activeTab === 'faq' ? 'active' : ''}`}
              onClick={() => setActiveTab('faq')}
            >
              FAQ
            </button>
          </div>

          <div className="details-content">
            {activeTab === 'details' && (
              <div className="tab-content">
                <p className="details-description">
                  {currentProduct.description || `Meet the ${currentProduct.name} – where clean style meets unmatched comfort. Built from ultra-premium fabric, this product delivers a soft, relaxed feel that keeps you cozy while looking effortlessly sharp. Its crisp finish gives it a refined edge, and the upcoming fresh design details make it a true standout piece.`}
                </p>
              </div>
            )}
            {activeTab === 'sale' && (
              <div className="tab-content">
                <p className="details-description">
                  Special offer! Get exclusive discounts on this amazing product. Limited time only. Don't miss out on this incredible deal!
                </p>
              </div>
            )}
            {activeTab === 'faq' && (
              <div className="tab-content">
                <p className="details-description">
                  <strong>Q: What materials is this made from?</strong><br/>
                  A: Premium quality materials for maximum comfort and durability.<br/><br/>
                  <strong>Q: How do I care for this product?</strong><br/>
                  A: Machine wash cold, tumble dry low. Iron on low heat if needed.
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Center Panel - Product Image */}
        <div className="product-image-panel">
          <div className="product-image-wrapper">
            <img 
              src={currentProduct.image || currentProduct.image_url || currentProduct.imageUrl || 'https://via.placeholder.com/500x600?text=Product+Image'} 
              alt={currentProduct.name}
              className="product-image"
            />
          </div>
        </div>

        {/* Right Panel - Product Info */}
        <div className="product-info-panel">
          <h1 className="product-name">{currentProduct.name}</h1>
          
          <p className="product-tagline">
            {currentProduct.tagline || `Whether you're dressing it up, keeping it casual, or aiming for that street-ready vibe, the ${currentProduct.name} is your new go-to. Elevate your wardrobe with a product that blends style – effortlessly.`}
          </p>

          <div className="product-price">
            ₹ {currentProduct.price ? currentProduct.price.toLocaleString() : 'XXX'}
          </div>

          <div className="size-selector">
            <label htmlFor="size">Size</label>
            <select 
              id="size"
              value={selectedSize}
              onChange={(e) => setSelectedSize(e.target.value)}
              className="size-dropdown"
            >
              <option value="Small">Small</option>
              <option value="Medium">Medium</option>
              <option value="Large">Large</option>
              <option value="X-Large">X-Large</option>
              <option value="XX-Large">XX-Large</option>
            </select>
          </div>

          <button className="add-to-cart-btn" onClick={handleAddToCart}>
            Add to Cart
          </button>
        </div>
      </div>

      {/* Navigation Arrows */}
      <div className="navigation-arrows">
        <button 
          className="arrow-button arrow-left"
          onClick={handlePrevious}
          aria-label="Previous product"
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M15 18L9 12L15 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        
        <button 
          className="arrow-button arrow-right"
          onClick={handleNext}
          aria-label="Next product"
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M9 18L15 12L9 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </div>
  );
};

export default ProductDetails;