"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";

/**
 * Bottom sheet for cart on mobile and tablet (< lg: 1024px).
 * Uses HeroUI Modal with placement="bottom" for native overlay behavior.
 * Includes drag handle visual cue, scrollable body, and sticky footer.
 */
export function CartBottomSheet() {
  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="opaque"
    >
      <Modal.Container placement="bottom" size="full" scroll="inside">
        <Modal.Dialog
          className="max-h-[85vh] rounded-t-2xl"
          aria-label="Shopping cart"
          style={{ paddingBottom: "env(safe-area-inset-bottom, 0px)" }}
        >
          {/* Drag handle */}
          <div className="flex shrink-0 justify-center pt-3 pb-1">
            <span
              className="h-1 w-10 rounded-full bg-[var(--border)]"
              aria-hidden="true"
            />
          </div>

          {/* Header */}
          <Modal.Header className="px-4 pb-2 pt-0">
            <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-4 py-3">
            <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>
  );
}
