"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Trash2, Plus, Minus, ShoppingBag, ArrowLeft, Check, MessageSquare } from "lucide-react";
import { useCartStore } from "@/lib/store";
import { orderApi } from "@/lib/api";
import BottomNav from "@/components/menu/BottomNav";
import Link from "next/link";

export default function CartPage() {
  const { items, updateQuantity, removeItem, clearCart, tableNumber, tableToken, setTableNumber, getTotalPrice } = useCartStore();
  const [note, setNote] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");

  const total = getTotalPrice();

  const handleOrder = async () => {
    if (items.length === 0) return;

    setSubmitting(true);
    setError("");

    try {
      await orderApi.create({
        table_number: tableNumber,
        token: tableToken,
        items: items.map((i) => ({
          product_id: i.product_id,
          product_name: i.product_name,
          quantity: i.quantity,
        })),
        customer_note: note || undefined,
      });
      setSuccess(true);
      clearCart();
      setNote("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Sipariş gönderilemedi.");
    } finally {
      setSubmitting(false);
    }
  };

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center pb-20">
        <motion.div
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ type: "spring", bounce: 0.3 }}
          className="text-center px-6"
        >
          <div className="w-20 h-20 bg-emerald/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <Check className="w-10 h-10 text-emerald" />
          </div>
          <h2 className="text-2xl font-bold mb-2">Siparişiniz Alındı! 🎉</h2>
          <p className="text-muted-foreground text-sm mb-6">Siparişiniz mutfağa iletildi. Kısa süre içinde hazır olacak.</p>
          <div className="flex gap-3 justify-center">
            <Link
              href="/menu"
              className="flex items-center gap-2 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold text-sm"
            >
              <ShoppingBag className="w-4 h-4" /> Menüye Dön
            </Link>
            <Link
              href="/ai-garson"
              className="flex items-center gap-2 bg-muted text-foreground px-6 py-3 rounded-xl font-semibold text-sm"
            >
              <MessageSquare className="w-4 h-4" /> AI Garson
            </Link>
          </div>
        </motion.div>
        <BottomNav />
      </div>
    );
  }

  return (
    <div className="min-h-screen pb-20">
      {/* Header */}
      <div className="glass border-b border-border/30 sticky top-0 z-40">
        <div className="max-w-lg mx-auto px-4 py-3 flex items-center gap-3">
          <Link href="/menu" className="w-8 h-8 rounded-full bg-muted flex items-center justify-center">
            <ArrowLeft className="w-4 h-4" />
          </Link>
          <h1 className="text-xl font-bold">Sepet</h1>
          {items.length > 0 && (
            <span className="text-xs text-muted-foreground ml-auto">{items.length} ürün</span>
          )}
        </div>
      </div>

      <div className="max-w-lg mx-auto px-4 mt-4">
        {items.length === 0 ? (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center py-20">
            <p className="text-5xl mb-4">🛒</p>
            <p className="text-muted-foreground text-sm mb-4">Sepetiniz boş</p>
            <Link href="/menu" className="inline-flex items-center gap-2 bg-primary text-primary-foreground px-6 py-3 rounded-xl font-semibold text-sm">
              <ShoppingBag className="w-4 h-4" /> Menüye Git
            </Link>
          </motion.div>
        ) : (
          <>
            {/* Table Number Match */}
            <div className="bg-card rounded-xl border border-border/50 p-4 mb-4 flex items-center justify-between">
              <div>
                <span className="text-xs text-muted-foreground font-medium block">Masa Numarası</span>
                <span className="text-lg font-black text-primary">Masa {tableNumber}</span>
              </div>
              <div className="bg-emerald/10 text-emerald text-xs px-3 py-1 rounded-full font-bold">
                ✓ QR Kod ile Tanımlandı
              </div>
            </div>

            {/* Cart Items */}
            <div className="space-y-3 mb-4">
              <AnimatePresence>
                {items.map((item) => (
                  <motion.div
                    key={item.product_id}
                    layout
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: 100, height: 0 }}
                    className="bg-card rounded-xl border border-border/50 p-4 flex items-center gap-3"
                  >
                    <div className="w-14 h-14 rounded-lg bg-muted flex items-center justify-center text-2xl flex-shrink-0 overflow-hidden">
                      {item.image_url ? (
                        <img src={item.image_url} alt={item.product_name} className="w-full h-full object-cover" />
                      ) : ( "🍽️" )}
                    </div>

                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold truncate">{item.product_name}</p>
                      <p className="text-primary font-bold text-sm">₺{(Number(item.price) * item.quantity).toFixed(0)}</p>
                    </div>

                    <div className="flex items-center gap-1.5">
                      <button
                        onClick={() => updateQuantity(item.product_id, item.quantity - 1)}
                        className="w-7 h-7 rounded-full bg-muted flex items-center justify-center hover:bg-destructive/10"
                      >
                        {item.quantity <= 1 ? <Trash2 className="w-3 h-3 text-destructive" /> : <Minus className="w-3 h-3" />}
                      </button>
                      <span className="w-6 text-center text-sm font-bold">{item.quantity}</span>
                      <button
                        onClick={() => updateQuantity(item.product_id, item.quantity + 1)}
                        className="w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center"
                      >
                        <Plus className="w-3 h-3" />
                      </button>
                    </div>
                  </motion.div>
                ))}
              </AnimatePresence>
            </div>

            {/* Note */}
            <div className="bg-card rounded-xl border border-border/50 p-4 mb-4">
              <label className="text-xs text-muted-foreground font-medium mb-2 block">Not (isteğe bağlı)</label>
              <textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="Ör: Acısız olsun, yanında ekstra ekmek..."
                className="w-full bg-muted/50 rounded-lg p-3 text-sm resize-none h-20 border border-border/50 focus:outline-none focus:ring-2 focus:ring-primary/30"
              />
            </div>

            {/* Error */}
            {error && (
              <div className="bg-destructive/10 border border-destructive/30 rounded-xl p-3 mb-4 text-sm text-destructive">
                {error}
              </div>
            )}

            {/* Total & Order Button */}
            <div className="bg-card rounded-2xl border border-border/50 p-4">
              <div className="flex justify-between items-center mb-4">
                <span className="text-muted-foreground text-sm">Toplam</span>
                <span className="text-2xl font-bold text-primary">₺{Number(total).toFixed(0)}</span>
              </div>
              <motion.button
                whileTap={{ scale: 0.98 }}
                onClick={handleOrder}
                disabled={submitting}
                className="w-full bg-gradient-to-r from-primary to-amber py-4 rounded-xl text-primary-foreground font-bold text-base shadow-lg shadow-primary/25 disabled:opacity-50 transition-opacity flex items-center justify-center gap-2"
              >
                {submitting ? (
                  <div className="w-5 h-5 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
                ) : (
                  <>
                    <ShoppingBag className="w-5 h-5" />
                    Sipariş Ver
                  </>
                )}
              </motion.button>
            </div>
          </>
        )}
      </div>
      <BottomNav />
    </div>
  );
}
