'use client';

import React, { useState } from 'react';
import { X, ShoppingBag, Trash2, Send, CreditCard, CheckCircle, Flame, Lock } from 'lucide-react';
import { useApp, CartItem } from '@/context/AppContext';

export default function CartDrawer() {
  const { cartOpen, setCartOpen, cart, updateCartQty, removeFromCart, checkoutCart, theme, currentUser, formatPrice, setAuthModalOpen, setAuthModalTab, language } = useApp();
  
  // Checkout Form states
  const [formDataState, setFormDataState] = useState({
    name: '',
    email: '',
    contact: '',
  });

  // Dynamically derive active values (prefills to currentUser details if no input is typed)
  const formData = {
    name: formDataState.name || currentUser?.name || '',
    email: formDataState.email || currentUser?.email || '',
    contact: formDataState.contact || currentUser?.contact || '',
  };
  
  const [orderSuccess, setOrderSuccess] = useState<any>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const isDark = theme === 'dark';
  const cartTotal = cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormDataState({ ...formDataState, [e.target.name]: e.target.value });
  };

  const handleCheckOut = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.name || !formData.email || !formData.contact) return;
    
    setIsSubmitting(true);
    // Simulate loading
    setTimeout(() => {
      const order = checkoutCart(formData.name, formData.email, formData.contact);
      setOrderSuccess(order);
      setIsSubmitting(false);
      // Reset form
      setFormDataState({ name: '', email: '', contact: '' });
    }, 1500);
  };

  if (!cartOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex justify-end animate-fade-in" id="cart-drawer-overlay">
      {/* Backdrop */}
      <div 
        className="absolute inset-0 bg-black/60 backdrop-blur-sm transition-opacity"
        onClick={() => {
          if (!orderSuccess) {
            setCartOpen(false);
          }
        }}
      />

      {/* Sheet Container */}
      <div className={`relative w-full max-w-md h-full border-l flex flex-col shadow-[0_0_50px_rgba(0,0,0,0.5)] overflow-hidden z-10 font-sans transition-all duration-300 ${
        isDark ? 'bg-[#05040f] border-white/5' : 'bg-white border-slate-200 text-slate-900'
      }`}>
        
        {/* Glowing side accent */}
        <div className="absolute top-0 right-0 w-1 h-full bg-gradient-to-b from-cyan-500 via-purple-600 to-pink-500 opacity-60 pointer-events-none" />

        {/* Header */}
        <div className={`p-6 border-b flex items-center justify-between transition-colors duration-300 ${
          isDark ? 'border-white/5 bg-slate-950/40 backdrop-blur-md' : 'border-slate-150 bg-slate-50'
        }`}>
          <div className="flex items-center gap-2">
            <ShoppingBag className="w-5 h-5 text-purple-500 animate-bounce" />
            <h2 className={`font-display font-bold text-lg ${isDark ? 'text-white' : 'text-slate-900'}`}>Your Order Checkout</h2>
          </div>
          <button 
            onClick={() => {
              setCartOpen(false);
              setOrderSuccess(null);
            }}
            className={`p-1.5 rounded-lg border cursor-pointer transition-all duration-300 ${
              isDark 
                ? 'border-white/5 hover:bg-white/5 text-slate-400 hover:text-white' 
                : 'border-slate-200 hover:bg-slate-100 text-slate-500 hover:text-slate-900'
            }`}
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Success Screen */}
        {orderSuccess ? (
          <div className="flex-1 p-6 flex flex-col justify-center items-center text-center overflow-y-auto custom-scroll animate-slide-in">
            <div className="w-16 h-16 rounded-full bg-cyan-500/10 border border-cyan-500/30 flex items-center justify-center mb-6 shadow-[0_0_30px_rgba(6,182,212,0.2)]">
              <CheckCircle className="w-8 h-8 text-cyan-500" />
            </div>
            
            <h3 className={`font-display font-black text-2xl mb-2 ${isDark ? 'text-slate-100' : 'text-slate-900'}`}>Order Confirmed!</h3>
            <p className="font-mono text-cyan-600 dark:text-cyan-400 text-sm mb-6 uppercase tracking-wider font-bold">
              Ref: {orderSuccess.reference}
            </p>

            <div className={`text-left p-5 rounded-xl w-full text-xs space-y-3 border mb-6 transition-all duration-300 ${
              isDark 
                ? 'bg-slate-950/40 border-white/10 text-slate-300' 
                : 'bg-slate-50 border-slate-200 text-slate-700'
            }`}>
              <div className={`flex justify-between border-b pb-2 ${isDark ? 'border-white/5' : 'border-slate-200'}`}>
                <span className="text-slate-400 font-mono">Client:</span>
                <span className={`font-medium ${isDark ? 'text-slate-200' : 'text-slate-800'}`}>{orderSuccess.clientName}</span>
              </div>
              <div className={`flex justify-between border-b pb-2 ${isDark ? 'border-white/5' : 'border-slate-200'}`}>
                <span className="text-slate-400 font-mono">Notification Handle:</span>
                <span className="text-purple-600 dark:text-purple-300 font-semibold">{orderSuccess.clientContact}</span>
              </div>
              <div className={`flex justify-between border-b pb-2 ${isDark ? 'border-white/5' : 'border-slate-200'}`}>
                <span className="text-slate-400 font-mono">Amount Processed:</span>
                <span className="text-cyan-600 dark:text-cyan-400 font-black">{formatPrice(orderSuccess.totalPrice)}</span>
              </div>
              <div className="pt-1">
                <span className="text-slate-400 font-mono block mb-1">Items Enlisted:</span>
                <div className="space-y-1 pl-2">
                  {orderSuccess.items.map((item: CartItem, i: number) => (
                    <div key={i} className={`text-[11px] flex justify-between ${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                      <span>• {item.product.name} (x{item.quantity})</span>
                      <span className="text-slate-400 font-semibold">{formatPrice(item.product.price * item.quantity)}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="space-y-4 w-full">
              <div className="flex items-start gap-3 p-4 rounded-xl border text-left text-xs transition-colors duration-300 bg-cyan-500/5 border-cyan-500/10 text-cyan-600 dark:text-cyan-300">
                <Flame className="w-5 h-5 flex-shrink-0 text-cyan-500 mt-0.5" />
                <div>
                  <h4 className="font-bold uppercase tracking-wider text-[10px] mb-1">Estimated Provision SLA</h4>
                  <p className="leading-relaxed">
                    Account details will be emailed directly to <b className={`${isDark ? 'text-white' : 'text-slate-900'}`}>{orderSuccess.clientEmail}</b> or shared via <b className={`${isDark ? 'text-white' : 'text-slate-900'}`}>{orderSuccess.clientContact}</b>. Deliveries range from immediate access to a maximum of 4 hours for custom configurations.
                  </p>
                </div>
              </div>

              <button
                onClick={() => {
                  setCartOpen(false);
                  setOrderSuccess(null);
                }}
                className="w-full py-4.5 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 font-semibold rounded-xl text-xs text-white tracking-widest uppercase transition-all duration-300 shadow-[0_5px_15px_rgba(168,85,247,0.3)] cursor-pointer"
              >
                Return to Storefront
              </button>
            </div>
          </div>
        ) : (
          /* Checkout Cart Content */
          <>
            <div className="flex-1 overflow-y-auto p-6 space-y-6 custom-scroll">
              
              {cart.length === 0 ? (
                <div className="h-44 flex flex-col items-center justify-center text-center">
                  <ShoppingBag className="w-10 h-10 text-slate-400 mb-3 animate-pulse" />
                  <p className="text-sm text-slate-405 font-mono">Your shopping cart is currently empty.</p>
                </div>
              ) : (
                /* Cart Items List */
                <div className="space-y-4 animate-fade-in">
                  <h3 className="text-xs font-mono font-bold uppercase tracking-wider text-slate-400">
                    Services Ordered ({cart.length})
                  </h3>
                  
                  <div className="space-y-3">
                    {cart.map((item) => (
                      <div 
                        key={item.product.id}
                        className={`p-3.5 rounded-xl border relative group transition-colors duration-300 ${
                          isDark ? 'border-white/5 bg-slate-950/40' : 'border-slate-200 bg-slate-50 shadow-sm'
                        }`}
                      >
                        <div className="flex gap-3">
                          <div className={`w-12 h-12 rounded-lg bg-cover bg-center border flex-shrink-0 ${
                            isDark ? 'border-white/10' : 'border-slate-200'
                          }`} style={{ backgroundImage: `url(${item.product.mediaUrl})` }} />
                          <div className="flex-1 min-w-0">
                            <h4 className={`text-xs font-bold truncate pr-4 ${isDark ? 'text-slate-200' : 'text-slate-800'}`}>{item.product.name}</h4>
                            <p className="text-[10px] font-mono text-cyan-600 dark:text-cyan-400 mt-0.5 font-bold">{formatPrice(item.product.price)}</p>
                            
                            {item.customInstructions && (
                              <p className={`text-[9px] mt-2 italic px-2 py-1 rounded border line-clamp-2 transition-colors duration-300 ${
                                isDark 
                                  ? 'text-purple-300 bg-purple-950/20 border-purple-500/10' 
                                  : 'text-purple-600 bg-purple-50 border-purple-200'
                              }`}>
                                Brief: {item.customInstructions}
                              </p>
                            )}

                            {/* SLA Target Progress Bar */}
                            <div className="mt-2.5 space-y-1.5 bg-slate-500/[0.03] dark:bg-white/[0.01] border border-slate-500/10 rounded-lg p-2 text-left">
                              <div className="flex justify-between items-center text-[9px] font-mono">
                                <span className="text-slate-400">Estimated Delivery SLA:</span>
                                <span className="font-bold text-cyan-600 dark:text-cyan-400">{item.product.deliveryTime}</span>
                              </div>
                              <div className="w-full bg-slate-200 dark:bg-purple-950/40 h-1.5 rounded-full overflow-hidden relative border border-slate-205 dark:border-white/5">
                                <div className="h-full bg-gradient-to-r from-cyan-400 to-purple-500 rounded-full animate-pulse" style={{ width: item.product.deliveryTime.toLowerCase().includes('instant') || item.product.deliveryTime.toLowerCase().includes('15 min') ? '100%' : '35%' }} />
                              </div>
                            </div>
                          </div>
                          
                          <button 
                            onClick={() => removeFromCart(item.product.id)}
                            className="absolute top-2.5 right-2 text-slate-400 hover:text-rose-500 p-1 rounded-lg transition-colors cursor-pointer"
                          >
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        </div>

                        {/* Quantity Manipulator */}
                        <div className={`flex items-center justify-between mt-3 pt-3 border-t ${isDark ? 'border-white/5' : 'border-slate-200'}`}>
                          <span className="text-[10px] text-slate-400 font-mono">Quantity:</span>
                          <div className="flex items-center gap-2">
                            <button 
                              onClick={() => updateCartQty(item.product.id, item.quantity - 1)}
                              className={`w-5 h-5 rounded flex items-center justify-center text-xs cursor-pointer border transition-colors duration-300 ${
                                isDark 
                                  ? 'bg-white/5 border-white/10 text-slate-400 hover:text-white' 
                                  : 'bg-white border-slate-200 text-slate-600 hover:bg-slate-100 hover:text-slate-900'
                              }`}
                            >
                              -
                            </button>
                            <span className={`text-xs font-mono w-4 text-center font-bold ${isDark ? 'text-slate-300' : 'text-slate-705'}`}>{item.quantity}</span>
                            <button 
                              onClick={() => updateCartQty(item.product.id, item.quantity + 1)}
                              className={`w-5 h-5 rounded flex items-center justify-center text-xs cursor-pointer border transition-colors duration-300 ${
                                isDark 
                                  ? 'bg-white/5 border-white/10 text-slate-400 hover:text-white' 
                                  : 'bg-white border-slate-200 text-slate-600 hover:bg-slate-100 hover:text-slate-900'
                              }`}
                            >
                              +
                            </button>
                          </div>
                        </div>

                      </div>
                    ))}
                  </div>

                  {/* Subtotal calculation */}
                  <div className={`p-4 rounded-xl flex justify-between items-center mt-6 border transition-all duration-300 ${
                    isDark ? 'bg-purple-950/15 border-purple-500/10' : 'bg-purple-50 border-purple-200 shadow-sm'
                  }`}>
                    <div>
                      <span className={`text-[10px] font-mono block tracking-widest uppercase transition-colors duration-300 ${isDark ? 'text-purple-400' : 'text-purple-650 font-bold'}`}>Order Subtotal</span>
                      <span className={`text-[10px] sm:text-xs transition-colors duration-300 ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>Services fees and SLA taxes included</span>
                    </div>
                    <span className={`text-xl font-display font-black transition-colors duration-300 ${
                      isDark ? 'text-white hover:text-purple-300' : 'text-slate-900 hover:text-purple-650'
                    }`}>
                      {formatPrice(cartTotal)}
                    </span>
                  </div>
                </div>
              )}

              {/* Delivery Client Form Details */}
              {cart.length > 0 && (
                !currentUser ? (
                  <div className={`p-6 rounded-2xl border text-center space-y-4 mt-6 transition-all duration-300 ${
                    isDark ? 'bg-purple-950/20 border-purple-500/20' : 'bg-purple-50/50 border-purple-200 shadow-sm'
                  }`}>
                    <div className="w-12 h-12 bg-purple-500/10 border border-purple-500/20 rounded-full flex items-center justify-center mx-auto text-purple-400">
                      <Lock className="w-5 h-5" />
                    </div>
                    <div className="space-y-1">
                      <h4 className={`font-display font-bold text-sm ${isDark ? 'text-slate-100' : 'text-slate-800'}`}>
                        Account Signup Required
                      </h4>
                      <p className={`text-[11px] ${isDark ? 'text-slate-400' : 'text-slate-600'} leading-relaxed`}>
                        Create an account or sign in first to personalize delivery channels, verify specifications, and track order fulfillment securely.
                      </p>
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        setAuthModalTab('register');
                        setAuthModalOpen(true);
                      }}
                      className="w-full py-3.5 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-xs font-black tracking-widest text-white uppercase rounded-xl shadow-lg hover:shadow-purple-500/20 cursor-pointer transition-all duration-305"
                    >
                      Sign Up & Checkout
                    </button>
                  </div>
                ) : (
                  <form onSubmit={handleCheckOut} className={`space-y-4 pt-4 border-t ${isDark ? 'border-white/5' : 'border-slate-200'}`}>
                    <h3 className="text-xs font-mono font-bold uppercase tracking-wider text-slate-400">
                      Delivery Instructions
                    </h3>

                    <div className="space-y-3">
                      <div>
                        <label className={`text-[10px] font-mono block mb-1 uppercase tracking-wider font-bold transition-all ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>Client Full Name</label>
                        <div className="relative">
                          <input 
                            type="text"
                            required
                            name="name"
                            value={formData.name}
                            onChange={handleInputChange}
                            placeholder="Elizabeth Bennett"
                            className={`w-full border focus:border-purple-500 focus:ring-1 focus:ring-purple-500/30 rounded-xl px-4 py-3 text-xs outline-none transition-colors duration-300 ${
                              isDark 
                                ? 'bg-slate-900/40 border-white/10 text-slate-200' 
                                : 'bg-slate-50 border-slate-200 text-slate-800'
                            }`}
                          />
                        </div>
                      </div>

                      <div>
                        <label className={`text-[10px] font-mono block mb-1 uppercase tracking-wider font-bold transition-all ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>Secure Email Address</label>
                        <div className="relative">
                          <input 
                            type="email"
                            required
                            name="email"
                            value={formData.email}
                            onChange={handleInputChange}
                            placeholder="elizabeth@creative.com"
                            className={`w-full border focus:border-purple-500 focus:ring-1 focus:ring-purple-500/30 rounded-xl px-4 py-3 text-xs outline-none transition-colors duration-300 ${
                              isDark 
                                ? 'bg-slate-900/40 border-white/10 text-slate-200' 
                                : 'bg-slate-50 border-slate-200 text-slate-800'
                            }`}
                          />
                        </div>
                      </div>

                      <div>
                        <label className={`text-[10px] font-mono block mb-1 uppercase tracking-wider font-bold transition-all ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>Direct Contact Handle</label>
                        <div className="relative">
                          <input 
                            type="text"
                            required
                            name="contact"
                            value={formData.contact}
                            onChange={handleInputChange}
                            placeholder="Telegram @eliza_co or WhatsApp link"
                            className={`w-full border focus:border-purple-500 focus:ring-1 focus:ring-purple-500/30 rounded-xl px-4 py-3 text-xs outline-none transition-colors duration-300 ${
                              isDark 
                                ? 'bg-slate-900/40 border-white/10 text-slate-200' 
                                : 'bg-slate-50 border-slate-200 text-slate-800'
                            }`}
                          />
                        </div>
                      </div>
                    </div>

                    {/* Payment Disclaimer */}
                    <div className={`p-3.5 rounded-xl border text-[10px] space-y-1 transition-all duration-300 ${
                      isDark 
                        ? 'border-white/5 bg-slate-950/60 text-slate-500' 
                        : 'border-slate-200 bg-slate-50/70 text-slate-600'
                    }`}>
                      <div className="flex items-center gap-1.5 text-cyan-600 dark:text-cyan-400/80 mb-1">
                        <CreditCard className="w-3.5 h-3.5 animate-pulse" />
                        <span className="font-mono tracking-wider uppercase font-semibold">Secure Settlement</span>
                      </div>
                      <p className="leading-relaxed">
                        Instant delivery triggers automatic provisioning. Custom design portfolios or video tasks will be started upon confirming contact via Telegram. Safe, secured escrow workflows prioritized.
                      </p>
                    </div>

                    {/* Commit Button */}
                    <button
                      type="submit"
                      disabled={isSubmitting}
                      className="w-full py-4 bg-gradient-to-r from-purple-600 via-purple-500 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 font-bold rounded-xl text-xs text-white tracking-widest uppercase transition-all duration-300 disabled:opacity-50 flex items-center justify-center gap-2 shadow-[0_4px_25px_rgba(168,85,247,0.25)] hover:shadow-[0_4px_35px_rgba(168,85,247,0.45)] cursor-pointer"
                    >
                      {isSubmitting ? (
                        <div className="h-4 w-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                      ) : (
                        <>
                          <Send className="w-4.5 h-4.5" />
                          <span>Confirm and Checkout</span>
                        </>
                      )}
                    </button>
                  </form>
                )
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
