"use client";

import React, { useState } from "react";
import { useApp } from "@/context/AppContext";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { FloatingWhatsApp } from "@/components/FloatingWhatsApp";
import { AIAssistant } from "@/components/AIAssistant";
import { Trash2, ArrowRight, ShoppingCart, Percent, Truck } from "lucide-react";
import Image from "next/image";
import Link from "next/link";

export default function CartPage() {
  const {
    cart,
    updateCartQty,
    removeFromCart,
    formatPrice,
    getCartSubtotal,
    getCartTotal,
    shippingEstimate,
    couponCode,
    applyCoupon,
    discountPercent,
    t
  } = useApp();

  const [promoInput, setPromoInput] = useState("");
  const [promoError, setPromoError] = useState("");
  const [promoSuccess, setPromoSuccess] = useState(false);

  const handleApplyPromo = (e: React.FormEvent) => {
    e.preventDefault();
    setPromoError("");
    setPromoSuccess(false);

    if (!promoInput.trim()) return;

    const applied = applyCoupon(promoInput);
    if (applied) {
      setPromoSuccess(true);
      setPromoInput("");
    } else {
      setPromoError("Invalid coupon code. Try WELCOME10 or FLASH20.");
    }
  };

  const subtotal = getCartSubtotal();
  const discountAmount = subtotal * (discountPercent / 100);
  const total = getCartTotal();

  return (
    <div className="flex min-h-screen flex-col bg-[#F8F7F2]">
      <Navbar />

      <main className="flex-1 py-12 px-6 md:px-12 mx-auto max-w-7xl w-full">
        {/* Header */}
        <div className="mb-12 border-b border-[#1A1A1A]/10 pb-6">
          <h1 className="font-serif text-3xl font-bold uppercase tracking-widest text-[#0a0a0a]">
            {t("cart.title")}
          </h1>
          <p className="text-xs text-neutral-500 font-light mt-1">
            Review your items and enter details to confirm checkout dispatch.
          </p>
        </div>

        {cart.length === 0 ? (
          <div className="border border-[#1A1A1A]/10 bg-white p-16 text-center space-y-6">
            <ShoppingCart className="w-12 h-12 mx-auto text-neutral-300" />
            <div className="space-y-1">
              <h3 className="font-serif text-lg font-bold uppercase tracking-widest text-black">YOUR BAG IS EMPTY</h3>
              <p className="text-xs text-neutral-500 font-light">Add items from our catalog collections to proceed.</p>
            </div>
            <Link
              href="/shop"
              className="inline-block bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-xs tracking-widest px-8 py-3.5 border border-black hover:border-[#D4AF37] transition-all uppercase"
            >
              SHOP NEW ARRIVALS
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-start">
            
            {/* Left Column: Cart Items Grid Table */}
            <div className="lg:col-span-8 space-y-6">
              <div className="border border-[#1A1A1A]/10 bg-white overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead>
                    <tr className="bg-[#0A0A0A] text-[#F8F7F2] uppercase text-[10px] tracking-widest font-bold border-b border-[#1A1A1A]/10">
                      <th className="p-4">Product Details</th>
                      <th className="p-4 text-center">Quantity</th>
                      <th className="p-4 text-right">Price</th>
                      <th className="p-4 text-center">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[#1A1A1A]/10">
                    {cart.map((item) => (
                      <tr key={`${item.id}-${item.size}-${item.color}`} className="hover:bg-neutral-50/50 transition-colors">
                        {/* Details */}
                        <td className="p-4 flex gap-4 min-w-[280px]">
                          <div className="relative h-20 w-16 bg-neutral-100 border border-[#1A1A1A]/10 flex-shrink-0">
                            <Image src={item.image} alt={item.name} fill className="object-cover" />
                          </div>
                          <div className="space-y-1 my-auto">
                            <h3 className="font-serif text-xs font-bold text-black uppercase tracking-wide truncate max-w-xs">
                              {item.name}
                            </h3>
                            <div className="text-[9px] uppercase tracking-wider text-neutral-400 space-x-2">
                              <span>Size: <strong className="text-black">{item.size}</strong></span>
                              <span>•</span>
                              <span>Color: <strong className="text-black">{item.color}</strong></span>
                            </div>
                          </div>
                        </td>

                        {/* Qty Controls */}
                        <td className="p-4 text-center min-w-[120px]">
                          <div className="inline-flex items-center border border-[#1A1A1A]/10 mx-auto">
                            <button
                              onClick={() => updateCartQty(item.id, item.size, item.color, item.quantity - 1)}
                              className="px-2.5 py-1 hover:bg-neutral-100 text-xs"
                            >
                              -
                            </button>
                            <span className="px-3 text-[11px] font-bold font-sans">{item.quantity}</span>
                            <button
                              onClick={() => updateCartQty(item.id, item.size, item.color, item.quantity + 1)}
                              className="px-2.5 py-1 hover:bg-neutral-100 text-xs"
                            >
                              +
                            </button>
                          </div>
                        </td>

                        {/* Price */}
                        <td className="p-4 text-right font-sans font-bold text-black min-w-[100px]">
                          {formatPrice(item.price * item.quantity)}
                        </td>

                        {/* Delete */}
                        <td className="p-4 text-center min-w-[80px]">
                          <button
                            onClick={() => removeFromCart(item.id, item.size, item.color)}
                            className="text-neutral-400 hover:text-red-600 transition-colors"
                          >
                            <Trash2 className="w-4.5 h-4.5 mx-auto" />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Coupon inputs */}
              <div className="border border-[#1A1A1A]/10 bg-white p-6">
                <h3 className="text-[10px] font-bold uppercase tracking-widest text-[#0a0a0a] mb-3 flex items-center gap-1.5">
                  <Percent className="w-3.5 h-3.5 text-[#D4AF37]" /> Promotional Coupon Code
                </h3>
                <form onSubmit={handleApplyPromo} className="flex gap-2">
                  <input
                    type="text"
                    value={promoInput}
                    onChange={(e) => setPromoInput(e.target.value)}
                    placeholder="Enter code (e.g. FLASH20)"
                    className="flex-1 bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-4 py-2.5 outline-none focus:border-[#D4AF37]"
                  />
                  <button
                    type="submit"
                    className="bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-xs tracking-widest px-6 py-2.5 transition-colors uppercase border border-black hover:border-[#D4AF37]"
                  >
                    Apply
                  </button>
                </form>

                {promoError && <p className="text-[10px] text-red-600 font-bold mt-2">{promoError}</p>}
                {promoSuccess && (
                  <p className="text-[10px] text-green-700 font-bold mt-2">
                    ✓ Promo applied! Your discount has been deducted.
                  </p>
                )}
                {couponCode && (
                  <div className="mt-3 flex items-center gap-2">
                    <span className="text-[9px] bg-[#D4AF37]/25 text-black border border-[#D4AF37]/50 font-bold px-2 py-0.5 uppercase tracking-wider">
                      Active: {couponCode} (-{discountPercent}%)
                    </span>
                  </div>
                )}
              </div>
            </div>

            {/* Right Column: Summary Invoice Panel */}
            <div className="lg:col-span-4 border border-[#1A1A1A]/10 bg-white p-6 md:p-8 space-y-6">
              <h3 className="text-xs font-bold uppercase tracking-widest border-b border-[#1A1A1A]/10 pb-4 text-[#0a0a0a]">
                {t("cart.summary")}
              </h3>

              <div className="space-y-4 text-xs">
                {/* Subtotal */}
                <div className="flex justify-between items-center text-neutral-600">
                  <span>{t("cart.subtotal")}</span>
                  <span className="font-bold text-black font-sans">{formatPrice(subtotal)}</span>
                </div>

                {/* Delivery */}
                <div className="flex justify-between items-center text-neutral-600">
                  <span className="flex items-center gap-1"><Truck className="w-3.5 h-3.5" /> Shipping (Nationwide)</span>
                  <span className="font-bold text-black font-sans">{formatPrice(shippingEstimate)}</span>
                </div>

                {/* Discount */}
                {discountPercent > 0 && (
                  <div className="flex justify-between items-center text-green-700 font-semibold">
                    <span>Discount ({discountPercent}%)</span>
                    <span className="font-sans">-{formatPrice(discountAmount)}</span>
                  </div>
                )}

                {/* Divider */}
                <div className="border-t border-[#1A1A1A]/10 my-2"></div>

                {/* Total */}
                <div className="flex justify-between items-center text-sm font-bold uppercase tracking-wide text-black">
                  <span>{t("cart.total")}</span>
                  <span className="font-sans text-base text-[#D4AF37]">{formatPrice(total)}</span>
                </div>
              </div>

              <div className="pt-4 space-y-3">
                <Link
                  href="/checkout"
                  className="w-full bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-xs tracking-widest py-4 text-center border border-black hover:border-[#D4AF37] transition-all flex items-center justify-center gap-2 uppercase"
                >
                  PROCEED TO SECURE CHECKOUT <ArrowRight className="w-4 h-4" />
                </Link>
                
                <Link
                  href="/shop"
                  className="w-full block bg-transparent hover:bg-neutral-50 text-neutral-600 font-semibold text-[10px] tracking-widest py-3 text-center border border-dashed border-[#1A1A1A]/20 transition-all uppercase"
                >
                  ← CONTINUE SHOPPING
                </Link>
              </div>

              {/* Delivery security notice */}
              <div className="bg-[#F8F7F2] border border-[#1A1A1A]/5 p-4 rounded space-y-2 text-[10px] leading-relaxed text-neutral-500 font-sans">
                <p className="font-semibold text-black uppercase tracking-wider">PAKISTAN FULFILLMENT NOTE:</p>
                <p>Orders are dispatched from our central warehouse via TCS or Leopards Courier. You will receive an SMS and email notification containing your shipment tracking number once dispatched.</p>
              </div>
            </div>

          </div>
        )}
      </main>

      <Footer />
      <FloatingWhatsApp />
      <AIAssistant />
    </div>
  );
}
