"use client";

import { motion } from "framer-motion";
import { Plus, Minus, ShoppingCart } from "lucide-react";
import { useCartStore } from "@/lib/store";
import { useState } from "react";

interface ProductCardProps {
  id: number;
  name: string;
  description: string;
  price: number;
  image_url?: string;
  stock_quantity: number;
  category_name?: string;
}

export default function ProductCard({ id, name, description, price, image_url, stock_quantity }: ProductCardProps) {
  const { items, addItem, updateQuantity, removeItem, tableToken } = useCartStore();
  const cartItem = items.find((i) => i.product_id === id);
  const [isAdding, setIsAdding] = useState(false);

  const handleAdd = () => {
    if (!tableToken) {
      alert("Lütfen sipariş vermek için masadaki QR kodu okutunuz.");
      return;
    }
    setIsAdding(true);
    addItem({ product_id: id, product_name: name, price, image_url: image_url || undefined });
    setTimeout(() => setIsAdding(false), 600);
  };

  const outOfStock = stock_quantity <= 0;

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      whileHover={{ y: -4 }}
      transition={{ duration: 0.3 }}
      className={`group relative bg-card rounded-2xl border border-border/50 overflow-hidden transition-shadow duration-300 hover:shadow-xl hover:shadow-primary/5 ${
        outOfStock ? "opacity-50 pointer-events-none" : ""
      }`}
    >
      {/* Image */}
      <div className="relative h-40 bg-gradient-to-br from-muted to-muted/50 overflow-hidden">
        {image_url ? (
          <img src={image_url} alt={name} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" />
        ) : (
          <div className="w-full h-full flex items-center justify-center text-4xl">
            🍽️
          </div>
        )}

        {/* Price Badge */}
        <div className="absolute top-3 right-3 bg-primary text-primary-foreground px-3 py-1 rounded-full text-sm font-bold shadow-lg">
          ₺{Number(price).toFixed(0)}
        </div>

        {/* Out of stock overlay */}
        {outOfStock && (
          <div className="absolute inset-0 bg-background/60 flex items-center justify-center">
            <span className="text-destructive font-bold text-lg">Tükendi</span>
          </div>
        )}

        {/* Add animation */}
        {isAdding && (
          <motion.div
            initial={{ scale: 0, opacity: 1 }}
            animate={{ scale: 2, opacity: 0 }}
            transition={{ duration: 0.6 }}
            className="absolute inset-0 flex items-center justify-center"
          >
            <ShoppingCart className="w-8 h-8 text-primary" />
          </motion.div>
        )}
      </div>

      {/* Content */}
      <div className="p-4">
        <h3 className="font-semibold text-foreground text-sm line-clamp-1 mb-1">{name}</h3>
        <p className="text-xs text-muted-foreground line-clamp-2 mb-3 min-h-[2rem]">{description}</p>

        {/* Cart Controls */}
        <div className="flex items-center justify-between">
          {stock_quantity <= 5 && stock_quantity > 0 && (
            <span className="text-[10px] text-amber-dark font-medium">Son {stock_quantity} adet!</span>
          )}
          <div className="ml-auto">
            {cartItem ? (
              <div className="flex items-center gap-2 bg-muted rounded-full px-1 py-0.5">
                <button
                  onClick={() =>
                    cartItem.quantity <= 1
                      ? removeItem(id)
                      : updateQuantity(id, cartItem.quantity - 1)
                  }
                  className="w-7 h-7 rounded-full bg-background flex items-center justify-center hover:bg-destructive/10 transition-colors"
                >
                  <Minus className="w-3 h-3" />
                </button>
                <span className="text-sm font-bold min-w-[1.5rem] text-center">{cartItem.quantity}</span>
                <button
                  onClick={handleAdd}
                  className="w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:opacity-90 transition-opacity"
                >
                  <Plus className="w-3 h-3" />
                </button>
              </div>
            ) : (
              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={handleAdd}
                className="flex items-center gap-1.5 bg-primary text-primary-foreground px-4 py-2 rounded-full text-xs font-semibold hover:opacity-90 transition-opacity"
              >
                <Plus className="w-3.5 h-3.5" />
                Ekle
              </motion.button>
            )}
          </div>
        </div>
      </div>
    </motion.div>
  );
}
