"use client";

import { Chip, Modal, ScrollShadow, Separator } from "@heroui/react";
import { useCartUI } from "../CartUIContext";
import { CartContent } from "../content/CartContent";
import { CartContentSkeleton } from "../state/CartContentSkeleton";
import { CartErrorState } from "../state/CartErrorState";
import { useCart } from "@/lib/cart/useCart";
import { useMediaQuery } from "@/lib/cart/useMediaQuery";
import { useCartMutations } from "@/lib/cart/useCartMutations";
import { useCartSessionId } from "@/lib/cart/useCartSessionId";

/**
 * Side drawer for cart on desktop (lg: 1024px+).
 * Uses HeroUI Modal with CSS overrides to dock the dialog to the right edge.
 *
 * Override chain:
 *  - Backdrop: `!justify-end` overrides default `justify-center` so children align right.
 *  - Container: `sm:!w-auto !p-0 sm:!p-0` removes padding so the dialog touches the edge.
 *  - Dialog: full viewport height, left-only border radius, fixed width.
 */
export function CartSideDrawer() {
  const { isOpen, closeCart } = useCartUI();
  const isLg = useMediaQuery("(min-width: 1024px)");

  const sessionId = useCartSessionId();
  const { items, subtotal, isLoading, error } = useCart(sessionId);
  const { updateItem, removeItem } = useCartMutations(sessionId);

  const show = isOpen && isLg;
  const itemCount = items.reduce((sum, i) => sum + i.quantity, 0);

  return (
    <Modal.Backdrop
      isOpen={show}
      onOpenChange={(open) => {
        if (!open) closeCart();
      }}
      variant="blur"
      className="!justify-end"
    >
      <Modal.Container
        scroll="inside"
        className="!p-0 sm:!p-0 sm:!w-auto"
      >
        <Modal.Dialog
          className="!my-0 !ml-auto !mr-0 !h-full !max-h-full !w-full !max-w-md !rounded-none !rounded-l-2xl !shadow-xl lg:!w-[420px]"
          aria-label="Shopping cart"
        >
          {/* Header */}
          <Modal.Header className="px-5 py-4">
            <div className="flex w-full items-center gap-2">
              <Modal.Heading className="text-lg font-semibold font-[family-name:var(--font-fraunces)]">
                Cart
              </Modal.Heading>
              {!isLoading && itemCount > 0 && (
                <Chip
                  size="sm"
                  variant="soft"
                  className="bg-[#e8f7f6] text-[var(--foreground)]"
                >
                  {itemCount}
                </Chip>
              )}
            </div>
            <Modal.CloseTrigger />
          </Modal.Header>

          <Separator />

          {/* Body */}
          <Modal.Body className="px-5 py-4">
            <ScrollShadow className="flex-1">
              {isLoading && <CartContentSkeleton />}
              {error && (
                <CartErrorState
                  message={
                    error.message ??
                    "Something went wrong loading your cart."
                  }
                  onRetry={() => window.location.reload()}
                />
              )}
              {!isLoading && !error && (
                <CartContent
                  items={items}
                  subtotal={subtotal}
                  onUpdateQuantity={updateItem}
                  onRemove={removeItem}
                  isEmpty={items.length === 0}
                  onCheckout={closeCart}
                  onViewFullCart={closeCart}
                  onClose={closeCart}
                  hideHeading
                  layout="overlay"
                />
              )}
            </ScrollShadow>
          </Modal.Body>
        </Modal.Dialog>
      </Modal.Container>
    </Modal.Backdrop>
  );
}
