'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCartStore, useAuthStore, useToastStore } from '@/lib/store';

interface AddressForm {
  first_name: string;
  last_name: string;
  street_address: string;
  apartment: string;
  city: string;
  state: string;
  zip_code: string;
  country: string;
  phone: string;
}

const emptyAddress: AddressForm = {
  first_name: '', last_name: '', street_address: '', apartment: '',
  city: '', state: '', zip_code: '', country: 'US', phone: '',
};

const US_STATES = [
  'AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA',
  'KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ',
  'NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT',
  'VA','WA','WV','WI','WY','DC',
];

export default function CheckoutPage() {
  const router = useRouter();
  const items = useCartStore(s => s.items);
  const getTotal = useCartStore(s => s.getTotal);
  const clearCart = useCartStore(s => s.clearCart);
  const user = useAuthStore(s => s.user);
  const toast = useToastStore(s => s.show);

  const [shipping, setShipping] = useState<AddressForm>({ ...emptyAddress });
  const [sameAsBilling, setSameAsBilling] = useState(true);
  const [billing, setBilling] = useState<AddressForm>({ ...emptyAddress });
  const [saveCard, setSaveCard] = useState(false);
  const [loading, setLoading] = useState(false);
  const [zipError, setZipError] = useState('');
  const [addressSuggestions, setAddressSuggestions] = useState<string[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const suggestionsRef = useRef<HTMLDivElement>(null);

  const subtotal = getTotal();
  const shippingCost = subtotal >= 49 ? 0 : 9.99;
  const tax = subtotal * 0.08;
  const total = subtotal + shippingCost + tax;

  useEffect(() => {
    if (items.length === 0) router.push('/cart');
  }, [items.length, router]);

  // Close address suggestions on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (suggestionsRef.current && !suggestionsRef.current.contains(e.target as Node)) {
        setShowSuggestions(false);
      }
    }
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, []);

  // Zip code validation — numbers only, 5 digits
  function handleZipChange(value: string, target: 'shipping' | 'billing') {
    const numericOnly = value.replace(/\D/g, '').slice(0, 5);
    if (target === 'shipping') {
      setShipping(prev => ({ ...prev, zip_code: numericOnly }));
    } else {
      setBilling(prev => ({ ...prev, zip_code: numericOnly }));
    }

    if (numericOnly.length > 0 && numericOnly.length < 5) {
      setZipError('Zip code must be 5 digits');
    } else {
      setZipError('');
    }
  }

  // Address finder / autocomplete
  async function handleAddressSearch(query: string) {
    setShipping(prev => ({ ...prev, street_address: query }));
    if (query.length < 3) { setShowSuggestions(false); return; }

    // Using a simple approach - in production you'd use Google Places API
    // For now, show a placeholder that this would connect to Google Places
    setAddressSuggestions([
      `${query}, New York, NY`,
      `${query}, Los Angeles, CA`,
      `${query}, Chicago, IL`,
    ]);
    setShowSuggestions(true);
  }

  function selectAddress(addr: string) {
    const parts = addr.split(', ');
    setShipping(prev => ({
      ...prev,
      street_address: parts[0] || prev.street_address,
      city: parts[1] || prev.city,
      state: parts[2] || prev.state,
    }));
    setShowSuggestions(false);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    if (shipping.zip_code.length !== 5) {
      toast('Please enter a valid 5-digit zip code', 'error');
      return;
    }

    setLoading(true);
    try {
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          items: items.map(i => ({ product_id: i.product.id, quantity: i.quantity, unit_price: i.product.price })),
          shipping_address: shipping,
          billing_address: sameAsBilling ? shipping : billing,
          subtotal,
          shipping_cost: shippingCost,
          tax_amount: tax,
          total_amount: total,
          save_card: saveCard,
        }),
      });

      const data = await res.json();
      if (data.success) {
        clearCart();
        toast('Order placed successfully! Check your email for confirmation.', 'success');
        router.push(`/account/orders`);
      } else {
        toast(data.error || 'Order failed', 'error');
      }
    } catch {
      toast('Network error. Please try again.', 'error');
    }
    setLoading(false);
  }

  if (items.length === 0) return null;

  return (
    <div className="max-w-7xl mx-auto px-4 py-6">
      <nav className="flex items-center gap-2 text-sm text-gray-500 mb-6">
        <Link href="/" className="hover:text-primary">Home</Link>
        <span>/</span>
        <Link href="/cart" className="hover:text-primary">Cart</Link>
        <span>/</span>
        <span className="text-gray-800 font-semibold">Checkout</span>
      </nav>

      <form onSubmit={handleSubmit}>
        <div className="grid lg:grid-cols-3 gap-6">
          {/* Left — Shipping & Payment */}
          <div className="lg:col-span-2 space-y-6">
            {/* Shipping Address */}
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                Shipping Address
              </h2>
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">First Name *</label>
                  <input type="text" required value={shipping.first_name} onChange={e => setShipping(p => ({ ...p, first_name: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary focus:ring-1 focus:ring-primary" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Last Name *</label>
                  <input type="text" required value={shipping.last_name} onChange={e => setShipping(p => ({ ...p, last_name: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary focus:ring-1 focus:ring-primary" />
                </div>
                <div className="md:col-span-2 relative" ref={suggestionsRef}>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Street Address * <span className="text-gray-400 font-normal">(start typing for suggestions)</span></label>
                  <input type="text" required value={shipping.street_address} onChange={e => handleAddressSearch(e.target.value)}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary focus:ring-1 focus:ring-primary" placeholder="123 Main Street" />
                  {showSuggestions && addressSuggestions.length > 0 && (
                    <div className="absolute top-full left-0 right-0 mt-1 bg-white rounded-xl shadow-2xl border border-gray-100 overflow-hidden z-50">
                      {addressSuggestions.map((s, i) => (
                        <button key={i} type="button" onClick={() => selectAddress(s)}
                          className="w-full text-left px-4 py-3 text-sm hover:bg-gray-50 border-b border-gray-50 flex items-center gap-2">
                          <svg className="w-4 h-4 text-gray-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /></svg>
                          {s}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                <div className="md:col-span-2">
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Apartment, Suite, etc.</label>
                  <input type="text" value={shipping.apartment} onChange={e => setShipping(p => ({ ...p, apartment: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">City *</label>
                  <input type="text" required value={shipping.city} onChange={e => setShipping(p => ({ ...p, city: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">State *</label>
                  <select required value={shipping.state} onChange={e => setShipping(p => ({ ...p, state: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary">
                    <option value="">Select State</option>
                    {US_STATES.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Zip Code * <span className="text-gray-400 font-normal">(5 digits)</span></label>
                  <input type="text" required value={shipping.zip_code} onChange={e => handleZipChange(e.target.value, 'shipping')}
                    inputMode="numeric" pattern="[0-9]{5}" maxLength={5}
                    className={`w-full px-4 py-2.5 rounded-xl border text-sm focus:ring-1 ${zipError ? 'border-red-400 focus:border-red-500 focus:ring-red-200' : 'border-gray-200 focus:border-primary focus:ring-primary'}`} placeholder="12345" />
                  {zipError && <p className="text-xs text-red-500 mt-1">{zipError}</p>}
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Phone *</label>
                  <input type="tel" required value={shipping.phone} onChange={e => setShipping(p => ({ ...p, phone: e.target.value }))}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" placeholder="+1 (555) 000-0000" />
                </div>
              </div>
            </div>

            {/* Billing Toggle */}
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <label className="flex items-center gap-3 cursor-pointer">
                <input type="checkbox" checked={sameAsBilling} onChange={e => setSameAsBilling(e.target.checked)} className="w-4 h-4 rounded" />
                <span className="text-sm font-semibold text-gray-800">Billing address same as shipping</span>
              </label>
              {!sameAsBilling && (
                <div className="grid md:grid-cols-2 gap-4 mt-4 pt-4 border-t border-gray-100">
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">First Name *</label>
                    <input type="text" required value={billing.first_name} onChange={e => setBilling(p => ({ ...p, first_name: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">Last Name *</label>
                    <input type="text" required value={billing.last_name} onChange={e => setBilling(p => ({ ...p, last_name: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm" />
                  </div>
                  <div className="md:col-span-2">
                    <label className="block text-xs font-semibold text-gray-700 mb-1">Street Address *</label>
                    <input type="text" required value={billing.street_address} onChange={e => setBilling(p => ({ ...p, street_address: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">City *</label>
                    <input type="text" required value={billing.city} onChange={e => setBilling(p => ({ ...p, city: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">State *</label>
                    <select required value={billing.state} onChange={e => setBilling(p => ({ ...p, state: e.target.value }))}
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm">
                      <option value="">Select State</option>
                      {US_STATES.map(s => <option key={s} value={s}>{s}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">Zip Code *</label>
                    <input type="text" required value={billing.zip_code} onChange={e => handleZipChange(e.target.value, 'billing')}
                      inputMode="numeric" pattern="[0-9]{5}" maxLength={5}
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm" placeholder="12345" />
                  </div>
                </div>
              )}
            </div>

            {/* Payment Method */}
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" /></svg>
                Payment Method
              </h2>

              {/* Sandbox Mode Banner */}
              <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 mb-4 flex items-start gap-2">
                <span className="text-lg">🧪</span>
                <div>
                  <p className="text-sm font-bold text-amber-800">Sandbox Mode</p>
                  <p className="text-xs text-amber-600">No real payment will be charged. Test card details are pre-filled below.</p>
                </div>
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Card Number</label>
                  <input type="text" value="4242 4242 4242 4242" readOnly
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm bg-gray-50 text-gray-600" />
                </div>
                <div className="grid grid-cols-3 gap-3">
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">Expiry</label>
                    <input type="text" value="12/28" readOnly
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm bg-gray-50 text-gray-600" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">CVC</label>
                    <input type="text" value="123" readOnly
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm bg-gray-50 text-gray-600" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">ZIP</label>
                    <input type="text" value="10001" readOnly
                      className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm bg-gray-50 text-gray-600" />
                  </div>
                </div>
                <div className="flex items-center gap-2 text-xs text-gray-400">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                  <span>Your card info is encrypted and stored securely via Stripe</span>
                </div>
              </div>
            </div>

            {/* Save Card Option */}
            {user && (
              <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
                <label className="flex items-center gap-3 cursor-pointer">
                  <input type="checkbox" checked={saveCard} onChange={e => setSaveCard(e.target.checked)} className="w-4 h-4 rounded" />
                  <div>
                    <span className="text-sm font-semibold text-gray-800">💳 Save card for faster checkout</span>
                    <p className="text-xs text-gray-400 mt-0.5">Your card info is encrypted and stored securely</p>
                  </div>
                </label>
              </div>
            )}
          </div>

          {/* Right — Order Summary */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 sticky top-28">
              <h2 className="text-lg font-bold text-gray-900 mb-4">Order Summary</h2>
              <div className="space-y-3 mb-4 max-h-60 overflow-y-auto">
                {items.map(item => (
                  <div key={item.product.id} className="flex gap-3">
                    <img src={item.product.image_url} alt={item.product.name} className="w-14 h-14 object-cover rounded-lg shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-800 line-clamp-1">{item.product.name}</p>
                      <p className="text-xs text-gray-500">Qty: {item.quantity}</p>
                    </div>
                    <p className="text-sm font-bold shrink-0">${(item.product.price * item.quantity).toFixed(2)}</p>
                  </div>
                ))}
              </div>
              <hr className="my-3" />
              <div className="space-y-2 text-sm">
                <div className="flex justify-between"><span className="text-gray-500">Subtotal</span><span className="font-semibold">${subtotal.toFixed(2)}</span></div>
                <div className="flex justify-between">
                  <span className="text-gray-500">Shipping</span>
                  <span className={`font-semibold ${shippingCost === 0 ? 'text-green-600' : ''}`}>{shippingCost === 0 ? 'FREE' : `$${shippingCost.toFixed(2)}`}</span>
                </div>
                <div className="flex justify-between"><span className="text-gray-500">Tax</span><span className="font-semibold">${tax.toFixed(2)}</span></div>
                <hr />
                <div className="flex justify-between text-lg"><span className="font-bold">Total</span><span className="font-black">${total.toFixed(2)}</span></div>
              </div>
              <button type="submit" disabled={loading}
                className="w-full btn-accent py-3.5 rounded-xl font-bold text-sm flex items-center justify-center gap-2 mt-5 disabled:opacity-50">
                {loading ? (
                  <div className="w-5 h-5 border-2 border-gray-900 border-t-transparent rounded-full animate-spin"></div>
                ) : (
                  <>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                    Place Order — ${total.toFixed(2)}
                  </>
                )}
              </button>
              <p className="text-xs text-gray-400 text-center mt-3">🔒 Secured with 256-bit SSL encryption</p>
            </div>
          </div>
        </div>
      </form>
    </div>
  );
}
