'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { PriceDisplay } from '@/components/price-display';
import { useCart, useRemoveFromCart } from '@/lib/queries/use-cart';
import type { CartStoreGroup } from '@alqove/api-client';

function formatPrice(cents: number): string {
  return `$${(cents / 100).toFixed(2)}`;
}

export function CartClient() {
  const router = useRouter();
  const { data: cartResponse, isLoading } = useCart();
  const removeFromCart = useRemoveFromCart();

  const cart = cartResponse?.data;

  if (isLoading) {
    return (
      <div className="mx-auto max-w-7xl px-4 py-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 w-48 rounded bg-slate-200" />
          <div className="h-64 rounded bg-slate-200" />
        </div>
      </div>
    );
  }

  if (!cart || cart.item_count === 0) {
    return (
      <div className="mx-auto max-w-7xl px-4 py-16 text-center">
        <h1 className="text-2xl font-bold text-slate-900">Your cart is empty</h1>
        <p className="mt-2 text-slate-500">Browse items and add them to your cart.</p>
        <Link href="/items">
          <Button className="mt-6">Browse Items</Button>
        </Link>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-7xl px-4 py-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-slate-900">
          Shopping Cart{' '}
          <span className="text-base font-normal text-slate-400">
            ({cart.item_count} {cart.item_count === 1 ? 'item' : 'items'})
          </span>
        </h1>
        <Link href="/items" className="text-sm font-medium text-forest-600 hover:text-forest-700">
          Continue Shopping &rarr;
        </Link>
      </div>

      <div className="flex gap-8">
        <div className="flex-1 space-y-4">
          {cart.stores.map((storeGroup: CartStoreGroup) => (
            <div key={storeGroup.store.id} className="rounded-lg border border-slate-200 bg-white overflow-hidden">
              <div className="bg-slate-50 px-4 py-3 border-b border-slate-200 flex items-center gap-2">
                <div className="h-7 w-7 rounded-full bg-forest-600 flex items-center justify-center text-xs font-semibold text-white">
                  {storeGroup.store.name.charAt(0)}
                </div>
                <span className="font-semibold text-sm">{storeGroup.store.name}</span>
              </div>

              {storeGroup.items.map((cartItem) => (
                <div key={cartItem.id} className="flex gap-4 p-4 border-b border-slate-100 last:border-0">
                  <div className="h-20 w-20 flex-shrink-0 rounded bg-slate-100 overflow-hidden">
                    {cartItem.item.image_url ? (
                      <img src={cartItem.item.image_url} alt={cartItem.item.title} className="h-full w-full object-cover" />
                    ) : (
                      <div className="h-full w-full flex items-center justify-center text-xs text-slate-400">No image</div>
                    )}
                  </div>
                  <div className="flex-1">
                    <Link href={`/items/${cartItem.item.id}`} className="font-semibold text-sm hover:text-forest-600">
                      {cartItem.item.title}
                    </Link>
                    <div className="text-xs text-slate-400 mt-0.5">{cartItem.item.condition}</div>
                    <div className="mt-2 flex items-center gap-3">
                      <PriceDisplay price={cartItem.item.price} size="sm" />
                      <button
                        onClick={() => removeFromCart.mutate(cartItem.item.id)}
                        className="text-xs text-red-500 hover:text-red-700"
                        disabled={removeFromCart.isPending}
                      >
                        Remove
                      </button>
                    </div>
                  </div>
                </div>
              ))}

              <div className="bg-forest-50 px-4 py-2 text-xs text-forest-800 border-t border-slate-200">
                Shipping: {formatPrice(storeGroup.shipping)}
                {storeGroup.free_shipping_threshold && storeGroup.shipping > 0 && (
                  <span> &middot; Free over {formatPrice(storeGroup.free_shipping_threshold)}</span>
                )}
                {storeGroup.shipping === 0 && storeGroup.free_shipping_threshold && (
                  <span> &middot; Free shipping!</span>
                )}
              </div>
            </div>
          ))}
        </div>

        <div className="w-80 flex-shrink-0">
          <div className="sticky top-6 rounded-lg border border-slate-200 bg-white p-5">
            <h2 className="font-bold text-base mb-4">Order Summary</h2>

            {cart.stores.map((sg: CartStoreGroup) => (
              <div key={sg.store.id} className="flex justify-between text-sm mb-2">
                <span className="text-slate-500">
                  {sg.store.name} ({sg.items.length} {sg.items.length === 1 ? 'item' : 'items'})
                </span>
                <span>{formatPrice(sg.subtotal)}</span>
              </div>
            ))}

            <div className="border-t border-slate-100 mt-3 pt-3 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-slate-500">Subtotal</span>
                <span>{formatPrice(cart.subtotal)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-slate-500">Shipping</span>
                <span>{formatPrice(cart.shipping_total)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-slate-500">Discount</span>
                <span className="text-slate-400">&mdash;</span>
              </div>
            </div>

            <div className="border-t-2 border-slate-900 mt-3 pt-3 flex justify-between font-bold text-lg">
              <span>Total</span>
              <span>{formatPrice(cart.total)}</span>
            </div>

            <Button
              className="w-full mt-5"
              size="lg"
              onClick={() => router.push('/checkout')}
            >
              Proceed to Checkout
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
