"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
  Empty,
  EmptyContent,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
} from "@/components/ui/empty";
import { RiHeartLine, RiShoppingCartLine } from "@remixicon/react";
import { CartItemsSection } from "@/components/cart/CartItemsSection";
import { OrderSummaryCard } from "@/components/cart/OrderSummaryCard";
import {
  updateCartItemQuantity,
  removeCartItem,
} from "@/lib/actions/cart";

type CartItem = {
  id: string;
  productId: string;
  name: string;
  slug: string;
  details: string;
  quantity: number;
  price: number;
  image: string;
  stockQuantity: number;
  maxQuantity: number;
  inStock: boolean;
};

type Cart = {
  id: string;
  items: CartItem[];
  subtotal: number;
} | null;

export default function CartPageClient({
  cart,
  deliveryFee = 0,
}: {
  cart: Cart;
  deliveryFee?: number;
}) {
  const router = useRouter();
  const [busyId, setBusyId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const items = cart?.items ?? [];
  const subtotal = cart?.subtotal ?? 0;

  async function handleUpdateQuantity(id: string, quantity: number) {
    setBusyId(id);
    setError(null);
    const res = await updateCartItemQuantity(id, quantity);
    setBusyId(null);
    if (!res.ok) {
      setError(res.error);
      return;
    }
    router.refresh();
  }

  async function handleRemove(id: string) {
    setBusyId(id);
    setError(null);
    const res = await removeCartItem(id);
    setBusyId(null);
    if (!res.ok) {
      setError(res.error);
      return;
    }
    router.refresh();
  }

  const mappedItems = items.map((item) => ({
    id: item.id,
    name: item.name,
    details: item.details,
    quantity: item.quantity,
    price: item.price,
    image: item.image,
    maxQuantity: item.maxQuantity,
  }));

  return (
    <div className="min-h-screen">
      <main className="mx-auto w-full">
        <div className="my-8">
          <h2 className="text-2xl font-bold">Shopping Cart</h2>
          <p className="mb-2 font-body-md text-body-md text-on-surface-variant">
            Review your selected items, update quantities, and proceed to
            <br />
            checkout when you&apos;re ready.
          </p>
        </div>

        {error && (
          <p
            role="alert"
            className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm text-red-600"
          >
            {error}
          </p>
        )}

        {items.length === 0 ? (
          <Empty className="py-16">
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <RiShoppingCartLine />
              </EmptyMedia>
              <EmptyTitle>Your cart is empty</EmptyTitle>
              <EmptyDescription>
                Looks like you haven&apos;t added anything yet. Browse the
                catalogue to find your next product.
              </EmptyDescription>
            </EmptyHeader>
            <EmptyContent>
              <div className="flex flex-wrap items-center justify-center gap-2">
                <Link href="/products">
                  <Button>
                    <RiShoppingCartLine data-icon="inline-start" />
                    Browse Products
                  </Button>
                </Link>
                <Link href="/wishlist">
                  <Button variant="outline">
                    <RiHeartLine data-icon="inline-start" />
                    View Wishlist
                  </Button>
                </Link>
              </div>
            </EmptyContent>
          </Empty>
        ) : (
          <div className="flex flex-col gap-8 lg:flex-row">
            <CartItemsSection
              items={mappedItems}
              onUpdateQuantity={handleUpdateQuantity}
              onRemove={handleRemove}
              busyId={busyId}
            />
            <OrderSummaryCard
              subtotal={subtotal}
              deliveryFee={deliveryFee}
              total={subtotal + deliveryFee}
            />
          </div>
        )}
      </main>
    </div>
  );
}