import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useCartStore, type CartItem } from '@/lib/cart/store';
import { useCartSettings } from '@/hooks/useAppearanceSettings';
import { updateCartItemQuantity, removeCartItem, clearCartAPI, fetchCart, applyCoupon, removeCoupon } from '@/lib/cart/api';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import Container from '@/components/Layout/Container';
import SEOHead from '@/components/SEOHead';
import { formatPrice } from '@/lib/currency';
import { Trash2, Plus, Minus, ShoppingBag, ArrowLeft, Loader2, X, Tag } from 'lucide-react';
import { toast } from 'sonner';

export default function Cart() {
  const navigate = useNavigate();
  const { cart, setCart } = useCartStore();
  const { layout, elements } = useCartSettings();
  const [showClearDialog, setShowClearDialog] = useState(false);
  const [isUpdating, setIsUpdating] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [couponCode, setCouponCode] = useState('');
  const [isApplyingCoupon, setIsApplyingCoupon] = useState(false);

  // Fetch cart from server on mount to sync with WooCommerce
  useEffect(() => {
    const loadCart = async () => {
      try {
        const serverCart = await fetchCart();
        setCart(serverCart);
      } catch (error) {
        console.error('Failed to fetch cart:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadCart();
  }, [setCart]);

  // Calculate total from items
  const total = cart.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);

  const handleUpdateQuantity = async (key: string, newQuantity: number) => {
    if (newQuantity < 1) {
      handleRemoveItem(key);
      return;
    }

    setIsUpdating(true);
    try {
      const updatedCart = await updateCartItemQuantity(key, newQuantity);
      setCart(updatedCart);
    } catch (error) {
      console.error('Failed to update quantity:', error);
      toast.error('Failed to update quantity');
    } finally {
      setIsUpdating(false);
    }
  };

  const handleRemoveItem = async (key: string) => {
    setIsUpdating(true);
    try {
      const updatedCart = await removeCartItem(key);
      setCart(updatedCart);
      toast.success('Item removed from cart');
    } catch (error) {
      console.error('Failed to remove item:', error);
      toast.error('Failed to remove item');
    } finally {
      setIsUpdating(false);
    }
  };

  const handleClearCart = async () => {
    setIsUpdating(true);
    try {
      const updatedCart = await clearCartAPI();
      setCart(updatedCart);
      setShowClearDialog(false);
      toast.success('Cart cleared');
    } catch (error) {
      console.error('Failed to clear cart:', error);
      toast.error('Failed to clear cart');
      setShowClearDialog(false);
    } finally {
      setIsUpdating(false);
    }
  };

  const handleApplyCoupon = async () => {
    if (!couponCode.trim()) return;

    setIsApplyingCoupon(true);
    try {
      const updatedCart = await applyCoupon(couponCode.trim());
      setCart(updatedCart);
      setCouponCode('');
      toast.success('Coupon applied successfully');
    } catch (error: any) {
      console.error('Failed to apply coupon:', error);
      toast.error(error.message || 'Failed to apply coupon');
    } finally {
      setIsApplyingCoupon(false);
    }
  };

  const handleRemoveCoupon = async (code: string) => {
    setIsUpdating(true);
    try {
      const updatedCart = await removeCoupon(code);
      setCart(updatedCart);
      toast.success('Coupon removed');
    } catch (error: any) {
      console.error('Failed to remove coupon:', error);
      toast.error(error.message || 'Failed to remove coupon');
    } finally {
      setIsUpdating(false);
    }
  };

  // Show loading state while fetching cart
  if (isLoading) {
    return (
      <Container>
        <div className="text-center py-16">
          <Loader2 className="mx-auto h-16 w-16 text-gray-400 mb-4 animate-spin" />
          <p className="text-gray-600">Loading cart...</p>
        </div>
      </Container>
    );
  }

  if (cart.items.length === 0) {
    return (
      <Container>
        <div className="text-center py-16">
          <ShoppingBag className="mx-auto h-16 w-16 text-gray-400 mb-4" />
          <h2 className="text-2xl font-bold mb-2">Your cart is empty</h2>
          <p className="text-gray-600 mb-6">Add some products to get started!</p>
          <Button onClick={() => navigate('/shop')}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Continue Shopping
          </Button>
        </div>
      </Container>
    );
  }

  return (
    <Container>
      <SEOHead title="Shopping Cart" description="Review your shopping cart" />
      <div className={`py-8 ${layout.style === 'boxed' ? 'max-w-5xl mx-auto' : ''}`}>
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <h1 className="text-3xl font-bold">Shopping Cart</h1>
          <Button variant="outline" onClick={() => setShowClearDialog(true)}>
            <Trash2 className="mr-2 h-4 w-4" />
            Clear Cart
          </Button>
        </div>

        <div className={`grid gap-8 ${layout.summary_position === 'bottom' ? 'grid-cols-1' : 'lg:grid-cols-3'}`}>
          {/* Cart Items */}
          <div className={`space-y-4 ${layout.summary_position === 'bottom' ? '' : 'lg:col-span-2'}`}>
            {cart.items.map((item: CartItem) => (
              <div
                key={item.key}
                className="flex flex-col sm:flex-row gap-4 p-4 border rounded-lg bg-white relative"
              >
                <div className="flex gap-4 sm:flex-1">
                  {/* Product Image */}
                  {elements.product_images && (
                    <div className="relative w-20 h-20 sm:w-24 sm:h-24 flex-shrink-0 rounded-lg overflow-hidden bg-gray-100">
                      {item.image ? (
                        <img
                          src={item.image}
                          alt={item.name}
                          className="block w-full !h-full object-cover object-center"
                        />
                      ) : (
                        <div className="w-full !h-full flex items-center justify-center text-gray-400 text-xs">
                          No Image
                        </div>
                      )}
                    </div>
                  )}

                  {/* Product Info */}
                  <div className="flex-1 min-w-0 pr-8 sm:pr-0">
                    <h3 className="font-semibold text-base sm:text-lg mb-1 truncate">
                      {item.name}
                    </h3>

                    {/* Variation Attributes */}
                    {item.attributes && Object.keys(item.attributes).length > 0 && (
                      <div className="text-xs sm:text-sm text-gray-500 mb-1 flex flex-wrap gap-x-3 gap-y-1">
                        {Object.entries(item.attributes).map(([key, value]) => {
                          const formattedKey = key.charAt(0).toUpperCase() + key.slice(1);
                          return (
                            <span key={key}>
                              {formattedKey}: <span className="font-medium">{value}</span>
                            </span>
                          );
                        })}
                      </div>
                    )}

                    <p className="text-gray-600 mb-2 font-medium">
                      {formatPrice(item.price)}
                    </p>

                    {/* Quantity Controls - Desktop */}
                    <div className="hidden sm:flex items-center gap-2 mt-2">
                      <button
                        onClick={() => handleUpdateQuantity(item.key, item.quantity - 1)}
                        className="font-[inherit] p-1 hover:bg-gray-100 rounded"
                      >
                        <Minus className="h-4 w-4" />
                      </button>
                      <input
                        type="number"
                        value={item.quantity}
                        onChange={(e) =>
                          handleUpdateQuantity(item.key, parseInt(e.target.value) || 1)
                        }
                        className="w-16 text-center border rounded py-1"
                        min="1"
                      />
                      <button
                        onClick={() => handleUpdateQuantity(item.key, item.quantity + 1)}
                        className="font-[inherit] p-1 hover:bg-gray-100 rounded"
                      >
                        <Plus className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>

                {/* Mobile Quantity & Item Total Container */}
                <div className="flex items-center justify-between sm:hidden pt-3 border-t border-gray-100">
                  {/* Quantity Controls - Mobile */}
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => handleUpdateQuantity(item.key, item.quantity - 1)}
                      className="font-[inherit] p-1 hover:bg-gray-100 rounded border"
                    >
                      <Minus className="h-4 w-4" />
                    </button>
                    <input
                      type="number"
                      value={item.quantity}
                      onChange={(e) =>
                        handleUpdateQuantity(item.key, parseInt(e.target.value) || 1)
                      }
                      className="w-12 text-center border rounded py-1"
                      min="1"
                    />
                    <button
                      onClick={() => handleUpdateQuantity(item.key, item.quantity + 1)}
                      className="font-[inherit] p-1 hover:bg-gray-100 rounded border"
                    >
                      <Plus className="h-4 w-4" />
                    </button>
                  </div>
                  <p className="font-bold text-base">
                    {formatPrice(item.price * item.quantity)}
                  </p>
                </div>

                {/* Desktop Item Total & Remove + Mobile Absolute Remove */}
                <div className="absolute top-2 right-2 sm:static sm:flex sm:flex-col sm:items-end sm:justify-between">
                  <button
                    onClick={() => handleRemoveItem(item.key)}
                    className="font-[inherit] text-gray-400 hover:text-red-600 p-2 sm:p-1"
                  >
                    <Trash2 className="h-5 w-5" />
                  </button>
                  <p className="hidden sm:block font-bold text-lg">
                    {formatPrice(item.price * item.quantity)}
                  </p>
                </div>
              </div>
            ))}
          </div>

          {/* Cart Summary */}
          <div className="lg:col-span-1">
            <div className="border rounded-lg p-6 bg-white sticky top-4">
              <h2 className="text-xl font-bold mb-4">Cart Summary</h2>

              {/* Coupon Field */}
              {elements.coupon_field && (
                <div className="mb-6">
                  <label className="block text-sm font-medium mb-2">Coupon Code</label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      placeholder="Enter coupon code"
                      value={couponCode}
                      onChange={(e) => setCouponCode(e.target.value)}
                      onKeyDown={(e) => e.key === 'Enter' && handleApplyCoupon()}
                      className="flex-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                      disabled={isApplyingCoupon}
                    />
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleApplyCoupon}
                      disabled={isApplyingCoupon || !couponCode.trim()}
                    >
                      {isApplyingCoupon ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Apply'}
                    </Button>
                  </div>

                  {/* Applied Coupons */}
                  {(cart as any).coupons?.length > 0 && (
                    <div className="mt-3 space-y-2">
                      {(cart as any).coupons.map((coupon: { code: string; discount: number }) => (
                        <div key={coupon.code} className="flex items-center justify-between p-2 bg-green-50 border border-green-200 rounded-md">
                          <div className="flex items-center gap-2">
                            <Tag className="h-4 w-4 text-green-600" />
                            <span className="text-sm font-medium text-green-800">{coupon.code}</span>
                            <span className="text-sm text-green-600">-{formatPrice(coupon.discount)}</span>
                          </div>
                          <button
                            onClick={() => handleRemoveCoupon(coupon.code)}
                            className="text-green-600 hover:text-green-800 p-1"
                            disabled={isUpdating}
                          >
                            <X className="h-4 w-4" />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {/* Shipping Calculator */}
              {elements.shipping_calculator && (
                <div className="mb-6 p-4 bg-gray-50 rounded-lg">
                  <h3 className="font-medium mb-3">Calculate Shipping</h3>
                  <div className="space-y-2">
                    <input
                      type="text"
                      placeholder="Postal Code"
                      className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                    />
                    <Button variant="outline" size="sm" className="w-full">Calculate</Button>
                  </div>
                </div>
              )}

              <div className="space-y-3 mb-6">
                <div className="flex justify-between text-gray-600">
                  <span>Subtotal</span>
                  <span>{formatPrice((cart as any).subtotal || total)}</span>
                </div>
                {/* Show discount if coupons applied */}
                {(cart as any).discount_total > 0 && (
                  <div className="flex justify-between text-green-600">
                    <span>Discount</span>
                    <span>-{formatPrice((cart as any).discount_total)}</span>
                  </div>
                )}
                <div className="flex justify-between text-gray-600">
                  <span>Shipping</span>
                  <span>{(cart as any).shipping_total > 0 ? formatPrice((cart as any).shipping_total) : 'Calculated at checkout'}</span>
                </div>
                <div className="border-t pt-3 flex justify-between text-lg font-bold">
                  <span>Total</span>
                  <span>{formatPrice((cart as any).total || total)}</span>
                </div>
              </div>

              <Button
                onClick={() => navigate('/checkout')}
                size="lg"
                className="w-full mb-3"
              >
                Proceed to Checkout
              </Button>

              {elements.continue_shopping_button && (
                <Button
                  onClick={() => navigate('/shop')}
                  variant="outline"
                  className="w-full"
                >
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  Continue Shopping
                </Button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Clear Cart Confirmation Dialog */}
      <Dialog open={showClearDialog} onOpenChange={setShowClearDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Clear Cart?</DialogTitle>
            <DialogDescription>
              Are you sure you want to remove all items from your cart? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowClearDialog(false)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleClearCart}>
              Clear Cart
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Container>
  );
}
