"use client"

import { Button } from "@/components/ui/button"
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { useCart } from "@/context/cart-context"
import { Minus, Plus, ShoppingCartIcon as CartIcon, Trash2 } from "lucide-react"
import { useRouter } from "next/navigation"
import { Separator } from "./ui/separator"
import { motion, AnimatePresence } from "framer-motion"
import { notify } from "@/lib/event-bus"

export function ShoppingCart() {
  const { cart, updateQuantity, removeFromCart, clearCart } = useCart()
  const router = useRouter()

  const totalItems = cart.reduce((total, item) => total + item.quantity, 0)
  const totalPrice = cart.reduce((total, item) => total + item.price * item.quantity, 0)

  const handleCheckout = () => {
    router.push("/cart")
  }

  const handleRemoveItem = (id: number, title: string) => {
    removeFromCart(id)

    notify({
      title: "已移除商品",
      message: title,
      type: "info",
      duration: 2000,
    })
  }

  return (
    <Sheet>
      <SheetTrigger asChild>
        <Button variant="outline" size="icon" className="relative">
          <CartIcon className="h-4 w-4" />
          {totalItems > 0 && (
            <span className="absolute -top-2 -right-2 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground cart-badge">
              {totalItems}
            </span>
          )}
        </Button>
      </SheetTrigger>
      <SheetContent className="w-full sm:max-w-md">
        <SheetHeader>
          <SheetTitle className="text-xl">购物车</SheetTitle>
        </SheetHeader>
        <div className="flex flex-col gap-4 py-4 h-[calc(100vh-18rem)] overflow-auto">
          {cart.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8">
              <CartIcon className="h-16 w-16 text-muted-foreground mb-4" />
              <p className="text-muted-foreground text-lg">您的购物车是空的</p>
              <Button variant="outline" className="mt-4" onClick={() => router.push("/books")}>
                浏览图书
              </Button>
            </div>
          ) : (
            <AnimatePresence>
              {cart.map((item) => (
                <motion.div
                  key={item.id}
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.3 }}
                  className="flex items-center gap-4 p-2 rounded-lg hover:bg-accent/50"
                >
                  <div className="h-20 w-14 overflow-hidden rounded-md">
                    <img
                      src={item.coverImage || "/placeholder.svg?height=80&width=60"}
                      alt={item.title}
                      className="h-full w-full object-cover"
                    />
                  </div>
                  <div className="flex-1 space-y-1">
                    <p className="text-sm font-medium line-clamp-1">{item.title}</p>
                    <p className="text-xs text-muted-foreground">¥{item.price.toFixed(2)}</p>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="icon"
                        className="h-6 w-6 rounded-full"
                        onClick={() => updateQuantity(item.id, Math.max(1, item.quantity - 1))}
                      >
                        <Minus className="h-3 w-3" />
                      </Button>
                      <span className="w-6 text-center text-sm">{item.quantity}</span>
                      <Button
                        variant="outline"
                        size="icon"
                        className="h-6 w-6 rounded-full"
                        onClick={() => updateQuantity(item.id, item.quantity + 1)}
                      >
                        <Plus className="h-3 w-3" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6 text-destructive ml-2"
                        onClick={() => handleRemoveItem(item.id, item.title)}
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium">¥{(item.price * item.quantity).toFixed(2)}</p>
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>
          )}
        </div>
        {cart.length > 0 && (
          <>
            <Separator />
            <div className="space-y-4 py-4">
              <div className="flex justify-between">
                <span>小计</span>
                <span>¥{totalPrice.toFixed(2)}</span>
              </div>
              <div className="flex justify-between">
                <span>运费</span>
                <span>免费</span>
              </div>
              <Separator />
              <div className="flex justify-between font-medium">
                <span>总计</span>
                <span className="text-lg">¥{totalPrice.toFixed(2)}</span>
              </div>
            </div>
            <SheetFooter className="flex flex-col gap-2 sm:flex-row">
              <Button
                variant="outline"
                className="w-full"
                onClick={() => {
                  clearCart()
                  notify({
                    title: "购物车已清空",
                    message: "所有商品已移除",
                    type: "info",
                    duration: 2000,
                  })
                }}
              >
                清空购物车
              </Button>
              <Button className="w-full" onClick={handleCheckout}>
                结账
              </Button>
            </SheetFooter>
          </>
        )}
      </SheetContent>
    </Sheet>
  )
}
