"use client";

import React from 'react';
import { useCart } from '@/context/CartContext';
import { Button } from '@/components/ui/button';
import { Container } from '@/components/ui/container';
import { Separator } from '@/components/ui/separator';
import { Minus, Plus, Trash2, ShoppingBag } from 'lucide-react';
import Link from 'next/link';

const CartPage: React.FC = () => {
  const { cart, removeFromCart, updateQuantity, clearCart } = useCart();

  const handleQuantityChange = async (productId: string, newQuantity: number) => {
    try {
      if (newQuantity < 1) {
        await removeFromCart(productId);
      } else {
        await updateQuantity(productId, newQuantity);
      }
    } catch (error) {
      console.error('Error updating cart:', error);
    }
  };

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(price);
  };

  if (cart.items.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Container className="py-12">
          <div className="text-center py-16">
            <ShoppingBag className="mx-auto h-24 w-24 text-gray-400 mb-6" />
            <h2 className="text-2xl font-bold text-gray-900 mb-4">عربة التسوق فارغة</h2>
            <p className="text-gray-600 mb-8">ابدأ التسوق لإضافة منتجات إلى عربتك</p>
            <Button asChild className="bg-black hover:bg-gray-800 text-white px-8 py-3">
              <Link href="/products">متابعة التسوق</Link>
            </Button>
          </div>
        </Container>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Container className="py-8 px-2">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">عربة التسوق</h1>
          <p className="text-gray-600">{cart.totalItems} {cart.totalItems === 1 ? 'منتج' : 'منتجات'} في عربتك</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Cart Items */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
              <div className="p-6">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-semibold">المنتجات في العربة</h2>
                  <Button
                    variant="ghost"
                    onClick={() => clearCart().catch(console.error)}
                    className="text-red-600 hover:text-red-700 hover:bg-red-50 flex-row-reverse"
                  >
                    إفراغ العربة
                    <Trash2 className="h-4 w-4 ml-2" />
                  </Button>
                </div>

                <div className="space-y-6">
                  {cart.items.map((item) => {
                    // Validate and get image source
                    const getImageSrc = () => {
                      if (!item.imageSrc) return '/assets/placeholder.png';
                      if (item.imageSrc.startsWith('data:image')) return item.imageSrc;
                      if (item.imageSrc.startsWith('http') || item.imageSrc.startsWith('/')) return item.imageSrc;
                      return '/assets/placeholder.png';
                    };
                    
                    const imageSrc = getImageSrc();
                    const isBase64 = imageSrc.startsWith('data:image');
                    
                    return (
                      <div key={item.id} className="flex gap-4">
                        <div className="relative h-24 w-24 rounded-lg overflow-hidden bg-gray-100 flex-shrink-0">
                          {isBase64 ? (
                            // Use regular img tag for base64 images (same as ProductCard)
                            <img
                              src={imageSrc}
                              alt={item.title}
                              className="w-full h-full object-cover"
                              loading="lazy"
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.src = '/assets/placeholder.png';
                              }}
                            />
                          ) : (
                            // Use regular img tag for all URLs to avoid Next.js Image validation issues
                            <img
                              src={imageSrc}
                              alt={item.title}
                              className="w-full h-full object-cover"
                              loading="lazy"
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.src = '/assets/placeholder.png';
                              }}
                            />
                          )}
                        </div>

                        <div className="flex-1 min-w-0">
                          <div className="flex items-start justify-between">
                            <div className="flex-1 min-w-0">
                              <h3 className="text-lg font-medium text-gray-900 truncate">
                                {item.title}
                              </h3>
                              <p className="text-lg font-semibold text-gray-900 mt-1">
                                {formatPrice(item.price)}
                              </p>
                            </div>

                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => removeFromCart(item.productId).catch(console.error)}
                              className="text-red-600 hover:text-red-700 hover:bg-red-50 ml-4"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>

                          <div className="flex items-center gap-3 mt-4">
                            <div className="flex items-center border rounded-lg">
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleQuantityChange(item.productId, item.quantity - 1)}
                                className="h-8 w-8 p-0 hover:bg-gray-100"
                              >
                                <Minus className="h-4 w-4" />
                              </Button>
                              <span className="px-3 py-1 text-sm font-medium min-w-[3rem] text-center">
                                {item.quantity}
                              </span>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleQuantityChange(item.productId, item.quantity + 1)}
                                className="h-8 w-8 p-0 hover:bg-gray-100"
                              >
                                <Plus className="h-4 w-4" />
                              </Button>
                            </div>
                            
                            <span className="text-sm text-gray-500">
                              المجموع الفرعي: {formatPrice(item.price * item.quantity)}
                            </span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>

          {/* Order Summary */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow-sm border p-6 sticky top-8">
              <h2 className="text-xl font-semibold mb-6">ملخص الطلب</h2>
              
              <div className="space-y-4">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">المجموع الفرعي ({cart.totalItems} منتجات)</span>
                  <span className="font-medium">{formatPrice(cart.totalPrice)}</span>
                </div>
                
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">الشحن</span>
                  <span className="font-medium">مجاني</span>
                </div>
                
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">الضريبة</span>
                  <span className="font-medium">{formatPrice(cart.totalPrice * 0.1)}</span>
                </div>
                
                <Separator />
                
                <div className="flex justify-between text-lg font-semibold">
                  <span>الإجمالي</span>
                  <span>{formatPrice(cart.totalPrice + cart.totalPrice * 0.1)}</span>
                </div>
              </div>

              <div className="space-y-3 mt-6">
                <Button asChild className="w-full bg-black hover:bg-gray-800 text-white py-3">
                  <Link href="/checkout">إتمام الطلب</Link>
                </Button>
                
                <Button variant="outline" asChild className="w-full">
                  <Link href="/products">متابعة التسوق</Link>
                </Button>
              </div>

              <div className="mt-6 text-xs text-gray-500 text-center">
                <p>شحن مجاني للطلبات فوق 50$</p>
                <p>سياسة إرجاع لمدة 30 يوم</p>
              </div>
            </div>
          </div>
        </div>
      </Container>
    </div>
  );
};

export default CartPage;