import React from "react";
import Image from "next/image";
import Link from "next/link";
import { useCart } from "@/context/helpers/cart/CartContext";
import { useHome } from "@/context/helpers/Home/HomeContext";
import { Button } from "@/components/ui/button";
import { motion } from "framer-motion";
import { useTranslation } from "react-i18next";
import { XIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import PriceDisplay from "@/components/shared/PriceDisplay";
import { isRtl } from "@/lib/direction";

// Drawer for a quick cart preview that appears on hover/click and supports RTL/LTR
export default function CartHoverDrawer({ onClose }) {
  const { removeFromCart } = useCart();
  const { cartItems, cartDetails } = useHome();
  const { t } = useTranslation("cart");

  // Calculate subtotal from cartDetails
  const totalsData = cartDetails?.totalsData || [];
  const subtotalItem = totalsData.find((item) => item.title === "Subtotal");
  const subtotal =
    subtotalItem?.formattedValue || cartDetails?.cartTotal || "EGP 0.00";

  // Determine reading direction
  const rtl = isRtl();

  // Offset and alignment depend on direction (slide from the nearest viewport edge)
  const xOffset = rtl ? -320 : 320;
  const sideClass = rtl ? "left-0" : "right-0";
  const removeBtnSideClass = rtl ? "-left-2" : "-right-2";

  return (
    // Animate enter/exit with a spring for a crisp drawer feel
    <motion.aside
      initial={{ x: xOffset, opacity: 0 }}
      animate={{ x: 0, opacity: 1 }}
      exit={{ x: xOffset, opacity: 0 }}
      transition={{ type: "spring", stiffness: 420, damping: 36 }}
      className={`fixed ${sideClass} top-0 h-[70%] w-[300px] bg-white dark:bg-gray-800 shadow-2xl z-[100] p-5 overflow-y-auto`}
      dir={rtl ? "rtl" : "ltr"}
    >
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-xl font-extrabold tracking-tight">
          {t("drawer.title")}
        </h3>
        {/* Close returns focus to the trigger in the parent context */}
        <Button
          type="button"
          onClick={onClose}
          variant="ghost"
          className="flex items-center gap-2 text-gray-500 hover:text-gray-700 dark:text-gray-300 dark:hover:text-gray-100 cursor-pointer"
          aria-label={t("drawer.close")}
        >
          <span className="text-sm">{t("drawer.close")}</span>
          <span aria-hidden>{rtl ? "←" : "→"}</span>
        </Button>
      </div>

      <div className="space-y-6">
        {/* Empty state */}
        {cartItems.length === 0 && (
          <p className="text-gray-500 dark:text-gray-300">
            {t("drawer.empty")}
          </p>
        )}

        {/* Cart item list */}
        {cartItems.map((item) => {
          return (
            <div key={item.id} className="flex items-start gap-4">
              <div className="flex-1">
                <p className="font-semibold leading-snug">{item.name}</p>
                <div className="mt-2 text-gray-500 dark:text-gray-300">
                  <span className="mr-2">
                    {item.qty} <XIcon className="w-4 h-4 inline" />
                  </span>
                  <PriceDisplay
                    product={item}
                    className="text-mainColor font-bold"
                    headingTag="span"
                    subHeadingTag="span"
                  />
                </div>
              </div>
              <div className="relative">
                {/* Remove is accessible and positioned according to direction */}
                <Button
                  aria-label={t("drawer.removeItem")}
                  onClick={() => removeFromCart(item.id)}
                  size="icon"
                  variant="outline"
                  className={cn(
                    `absolute -top-2 bg-white dark:bg-gray-800 rounded-full w-7 h-7 shadow border flex items-center justify-center cursor-pointer`,
                    removeBtnSideClass
                  )}
                >
                  <XIcon className="w-4 h-4" />
                </Button>
                <Link href={`/product-details/${item.productId}`} onClick={onClose}>
                  <Image
                    src={item.image}
                    alt={item.name}
                    width={104}
                    height={100}
                    className="w-[104px] h-[100px] object-contain"
                  />
                </Link>
              </div>
            </div>
          );
        })}
      </div>

      <div className="my-6 h-px bg-gray-200 dark:bg-gray-700" />

      {/* Totals summary (subtotal only; taxes/shipping may apply at checkout) */}
      <div className="flex items-center justify-between mb-6">
        <span className="font-semibold text-gray-700 dark:text-gray-300">
          {t("totals.subtotal")}
        </span>
        <span className="text-xl font-bold">{subtotal}</span>
      </div>

      {/* Primary actions */}
      <div className="flex items-center gap-3">
        <Link
          href="/cart"
          className="flex-1 border border-gray-400 rounded px-4 py-3 text-center font-semibold"
          onClick={onClose}
        >
          {t("drawer.viewCart")}
        </Link>
        <Link
          href="/checkout"
          className="flex-1 bg-[#336699] text-white rounded px-4 py-3 text-center font-semibold"
          onClick={onClose}
        >
          {t("drawer.checkout")}
        </Link>
      </div>
    </motion.aside>
  );
}
