'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { packageService } from '@/services/packageService';
import { useCart } from '@/context/CartContext';
import type { PackageDeal } from '@/types/package';
import Image from 'next/image';

export default function PackageDetailPage() {
  const params = useParams();
  const router = useRouter();
  const slug = params.slug as string;
  const { addToCart } = useCart();
  
  const [packageDeal, setPackageDeal] = useState<PackageDeal | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isAddingToCart, setIsAddingToCart] = useState(false);
  const [justAdded, setJustAdded] = useState(false);

  useEffect(() => {
    const fetchPackage = async () => {
      try {
        setLoading(true);
        const data = await packageService.getPackageBySlug(slug);
        setPackageDeal(data);
      } catch (err) {
        console.error('Failed to fetch package:', err);
        setError('Package not found');
      } finally {
        setLoading(false);
      }
    };

    if (slug) {
      fetchPackage();
    }
  }, [slug]);

  const handleAddToCart = async () => {
    if (!packageDeal || isAddingToCart) return;

    setIsAddingToCart(true);
    try {
      // Add each product in the package to cart
      for (const product of packageDeal.products) {
        const cartProduct = {
          id: product.id.toString(),
          title: product.name,
          price: product.base_price,
          imageSrc: product.images && product.images.length > 0 ? product.images[0] : '',
          slug: product.slug || ''
        };
        await addToCart(cartProduct, product.pivot.quantity);
      }
      
      setJustAdded(true);
      
      setTimeout(() => setJustAdded(false), 1500);
    } catch (error) {
      console.error('Error adding package to cart:', error);
      alert('Failed to add package to cart. Please try again.');
    } finally {
      setIsAddingToCart(false);
    }
  };

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-12">
        <div className="flex justify-center items-center min-h-[400px]">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-orange-500"></div>
        </div>
      </div>
    );
  }

  if (error || !packageDeal) {
    return (
      <div className="container mx-auto px-4 py-12">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-4">Package Not Found</h1>
          <p className="text-gray-600 mb-6">{error || 'The package you are looking for does not exist.'}</p>
          <button
            onClick={() => router.push('/packages')}
            className="px-6 py-3 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors"
          >
            View All Packages
          </button>
        </div>
      </div>
    );
  }

  const firstImage = packageDeal.images && packageDeal.images.length > 0 
    ? packageDeal.images[0] 
    : '/placeholder-package.jpg';

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Breadcrumb */}
      <nav className="mb-6 text-sm text-gray-600">
        <button onClick={() => router.push('/')} className="hover:text-orange-500">Home</button>
        <span className="mx-2">/</span>
        <button onClick={() => router.push('/packages')} className="hover:text-orange-500">Packages</button>
        <span className="mx-2">/</span>
        <span className="text-gray-900">{packageDeal.name}</span>
      </nav>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-12">
        {/* Images */}
        <div className="space-y-4">
          <div className="relative aspect-square rounded-lg overflow-hidden bg-gray-100">
            <Image
              src={firstImage}
              alt={packageDeal.name}
              fill
              className="object-cover"
              priority
            />
            {packageDeal.discount_percentage > 0 && (
              <div className="absolute top-4 right-4 bg-red-500 text-white px-3 py-1 rounded-full text-sm font-semibold">
                Save {packageDeal.discount_percentage}%
              </div>
            )}
          </div>
          
          {/* Additional images thumbnail grid */}
          {packageDeal.images && packageDeal.images.length > 1 && (
            <div className="grid grid-cols-4 gap-2">
              {packageDeal.images.slice(1, 5).map((image, index) => (
                <div key={index} className="relative aspect-square rounded-lg overflow-hidden bg-gray-100">
                  <Image
                    src={image}
                    alt={`${packageDeal.name} ${index + 2}`}
                    fill
                    className="object-cover"
                  />
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Package Info */}
        <div className="space-y-6">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">{packageDeal.name}</h1>
            <p className="text-gray-600">{packageDeal.description}</p>
          </div>

          {/* Pricing */}
          <div className="space-y-2">
            <div className="flex items-baseline gap-3">
              <span className="text-3xl font-bold text-orange-500">
                {packageDeal.package_price.toLocaleString()} IQD
              </span>
              {packageDeal.original_price > packageDeal.package_price && (
                <span className="text-xl text-gray-400 line-through">
                  {packageDeal.original_price.toLocaleString()} IQD
                </span>
              )}
            </div>
            {packageDeal.savings && packageDeal.savings > 0 && (
              <p className="text-green-600 font-semibold">
                You save {packageDeal.savings.toLocaleString()} IQD!
              </p>
            )}
          </div>

          {/* Stock Status */}
          <div>
            {packageDeal.stock > 0 ? (
              <p className="text-green-600 font-medium">
                ✓ In Stock ({packageDeal.stock} available)
              </p>
            ) : (
              <p className="text-red-600 font-medium">✗ Out of Stock</p>
            )}
          </div>

          {/* Add to Cart Button */}
          <button
            onClick={handleAddToCart}
            disabled={packageDeal.stock === 0 || isAddingToCart || justAdded}
            className={`w-full py-4 rounded-lg font-semibold text-white transition-all duration-300 ${
              justAdded
                ? 'bg-green-500 scale-105'
                : packageDeal.stock === 0
                ? 'bg-gray-400 cursor-not-allowed'
                : isAddingToCart
                ? 'bg-orange-400 scale-95'
                : 'bg-orange-500 hover:bg-orange-600 hover:scale-105'
            }`}
          >
            {justAdded ? (
              <span className="flex items-center justify-center gap-2 animate-bounce">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                Added to Cart!
              </span>
            ) : isAddingToCart ? (
              'Adding...'
            ) : packageDeal.stock === 0 ? (
              'Out of Stock'
            ) : (
              'Add Package to Cart'
            )}
          </button>

          {/* Package Details */}
          <div className="border-t pt-6">
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-600">Products:</span>
                <span className="ml-2 font-semibold">{packageDeal.products.length} items</span>
              </div>
              {packageDeal.starts_at && (
                <div>
                  <span className="text-gray-600">Available from:</span>
                  <span className="ml-2 font-semibold">
                    {new Date(packageDeal.starts_at).toLocaleDateString()}
                  </span>
                </div>
              )}
              {packageDeal.ends_at && (
                <div>
                  <span className="text-gray-600">Available until:</span>
                  <span className="ml-2 font-semibold text-red-600">
                    {new Date(packageDeal.ends_at).toLocaleDateString()}
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Products in Package */}
      <div className="border-t pt-8">
        <h2 className="text-2xl font-bold text-gray-900 mb-6">Products Included</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {packageDeal.products.map((product) => (
            <div key={product.id} className="border rounded-lg p-4 hover:shadow-lg transition-shadow">
              <div className="flex items-start gap-4">
                <div className="relative w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-gray-100">
                  {product.images && product.images.length > 0 ? (
                    <Image
                      src={product.images[0]}
                      alt={product.name}
                      fill
                      className="object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-gray-400">
                      📦
                    </div>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-gray-900 truncate">{product.name}</h3>
                  <p className="text-sm text-gray-600 mt-1">
                    Quantity: {product.pivot.quantity}
                  </p>
                  <p className="text-sm text-orange-600 font-semibold mt-1">
                    {product.base_price.toLocaleString()} IQD each
                  </p>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Back to Packages */}
      <div className="mt-8 text-center">
        <button
          onClick={() => router.push('/packages')}
          className="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
        >
          ← View All Packages
        </button>
      </div>
    </div>
  );
}
