import { createFileRoute, Link } from '@tanstack/react-router';
import { useState } from 'react';
import { Trash2, Minus, Plus, ShoppingBag, ArrowRight, Tag, Shield, Truck, Clock, X, Loader2, Star } from 'lucide-react';
import { useGqlCart } from '@/hooks/useGqlCart';
import { useLoyalty } from '@/hooks/useLoyalty';
import { useAuthStore } from '@/stores/authStore';
import { toast } from 'sonner';
import { useT, headLang, localizePath, SITE_URL } from '@/lib/i18n';

export const Route = createFileRoute('/cart')({
  head: (ctx) => {
    const lang = headLang(ctx);
    const url = `${SITE_URL}${localizePath('/cart', lang)}`;
    return {
      meta: [
        { title: lang === 'en' ? 'Cart | Peptidewinkel' : 'Winkelwagen | Peptidewinkel' },
        { name: 'description', content: lang === 'en' ? 'View and manage your cart at Peptidewinkel.' : 'Bekijk en beheer je winkelwagen bij Peptidewinkel.' },
        { name: 'robots', content: 'noindex, nofollow' },
      ],
      links: [{ rel: 'canonical', href: url }],
    };
  },
  component: CartPage,
});

const FREE_SHIPPING_HINT_THRESHOLD = 150;

function CartPage() {
  const t = useT();
  const {
    items,
    totals,
    isReady,
    isFetching,
    updateItem,
    removeItem,
    emptyCart,
    applyCoupon,
    applyCouponPending,
    removeCoupon,
    updatePending,
    removePending,
    loadError,
    refresh,
  } = useGqlCart();
  const [couponInput, setCouponInput] = useState('');
  const [couponError, setCouponError] = useState<string | null>(null);
  const { isLoggedIn } = useAuthStore();
  const { loyalty } = useLoyalty();

  const mutating = updatePending || removePending;

  if (!isReady) {
    return (
      <div className="container py-20 flex justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="container py-20 text-center">
        <div className="mx-auto w-24 h-24 rounded-full bg-muted flex items-center justify-center mb-6">
          <ShoppingBag className="w-11 h-11 text-muted-foreground/60" aria-hidden="true" />
        </div>
        <h1 className="text-2xl font-bold mb-2">{t('Uw winkelwagen is leeg', 'Your cart is empty')}</h1>
        <p className="text-muted-foreground mb-6 max-w-md mx-auto">{t('Ontdek onze producten en voeg ze toe aan uw wagen.', 'Discover our products and add them to your cart.')}</p>
        <Link to="/shop" className="inline-flex items-center gap-2 bg-primary text-primary-foreground font-semibold px-6 py-3 rounded-md hover:bg-primary-hover transition-colors">
          {t('Bekijk producten', 'View products')} <ArrowRight className="w-4 h-4" />
        </Link>
        {loadError && (
          <p className="mt-6 text-sm text-muted-foreground">
            {t('Kon je winkelwagen niet laden.', 'Could not load your cart.')}{' '}
            <button type="button" onClick={() => refresh()} className="text-primary hover:underline">
              {t('Opnieuw proberen', 'Try again')}
            </button>
          </p>
        )}
      </div>
    );
  }

  const handleApplyCoupon = async (e: React.FormEvent) => {
    e.preventDefault();
    setCouponError(null);
    try {
      await applyCoupon(couponInput.trim());
      setCouponInput('');
    } catch (err) {
      setCouponError(err instanceof Error ? err.message : t('Kortingscode ongeldig.', 'Invalid coupon code.'));
    }
  };

  const appliedCoupon = totals.appliedCoupons[0];

  return (
    <div className="container py-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold flex items-center gap-2">
          {t('Winkelwagen', 'Cart')} ({totals.itemCount} {totals.itemCount === 1 ? t('item', 'item') : t('items', 'items')})
          {isFetching && <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />}
        </h1>
        <button
          onClick={() => emptyCart().catch(() => toast.error(t('Kon winkelwagen niet legen.', 'Could not empty cart.')))}
          className="text-sm text-muted-foreground hover:text-destructive transition-colors"
        >
          {t('Wagen legen', 'Empty cart')}
        </button>
      </div>

      <div className="grid lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-4">
          <div className="hidden md:grid grid-cols-12 gap-4 px-4 text-xs font-medium text-muted-foreground uppercase">
            <div className="col-span-6">{t('Product', 'Product')}</div>
            <div className="col-span-2 text-center">{t('Prijs', 'Price')}</div>
            <div className="col-span-2 text-center">{t('Aantal', 'Quantity')}</div>
            <div className="col-span-2 text-right">{t('Totaal', 'Total')}</div>
          </div>

          {items.map((item) => item.bundled ? (
            <div key={item.key} className="flex items-center gap-3 -mt-2 ml-8 pl-3 border-l-2 border-primary/30">
              <img src={item.image} alt={item.name} width={40} height={40} loading="lazy" className="w-10 h-10 object-contain bg-surface rounded-md shrink-0" />
              <div className="min-w-0">
                <p className="text-sm font-medium truncate">{item.quantity > 1 ? `${item.quantity}× ` : ''}{item.name}</p>
                <p className="text-xs text-muted-foreground">{t('Inbegrepen in bundel', 'Included in bundle')}</p>
              </div>
            </div>
          ) : (
            <div key={item.key} className="bg-card border border-border rounded-lg p-4">
              <div className="md:grid md:grid-cols-12 md:gap-4 md:items-center flex gap-4">
                <div className="md:col-span-6 flex gap-3 items-center min-w-0">
                  <Link to="/product/$slug" params={{ slug: item.slug }} className="w-16 h-16 bg-surface rounded-md overflow-hidden shrink-0">
                    <img src={item.image} alt={t(`${item.name} in winkelwagen`, `${item.name} in cart`)} width={120} height={120} loading="lazy" decoding="async" className="w-full h-full object-contain p-2" />
                  </Link>
                  <div className="min-w-0">
                    <Link to="/product/$slug" params={{ slug: item.slug }} className="font-semibold text-sm hover:text-primary transition-colors block truncate">{item.name}</Link>
                    {item.variationLabel && <span className="text-xs text-muted-foreground">{item.variationLabel}</span>}
                  </div>
                </div>
                <div className="md:col-span-2 text-center hidden md:block">
                  <span className="text-sm font-medium">€{item.unitPrice.toFixed(2)}</span>
                </div>
                <div className="md:col-span-2 flex justify-center">
                  <div className="flex items-center border border-border rounded-md">
                    <button disabled={mutating} onClick={() => updateItem(item.key, Math.max(0, item.quantity - 1))} className="p-1.5 hover:bg-muted transition-colors disabled:opacity-50"><Minus className="w-3.5 h-3.5" /></button>
                    <span className="px-3 text-sm font-medium min-w-[2rem] text-center">{item.quantity}</span>
                    <button disabled={mutating} onClick={() => updateItem(item.key, item.quantity + 1)} className="p-1.5 hover:bg-muted transition-colors disabled:opacity-50"><Plus className="w-3.5 h-3.5" /></button>
                  </div>
                </div>
                <div className="md:col-span-2 flex items-center justify-end gap-3">
                  <span className="text-sm font-bold">€{item.lineTotal.toFixed(2)}</span>
                  <button disabled={mutating} onClick={() => removeItem(item.key)} className="p-1.5 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50">
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}

          <Link to="/shop" className="inline-flex items-center gap-2 text-sm text-primary font-medium hover:underline mt-2">
            <ArrowRight className="w-4 h-4 rotate-180" /> {t('Verder winkelen', 'Continue shopping')}
          </Link>
        </div>

        <div className="space-y-4">
          <div className="bg-card border border-border rounded-lg p-6 sticky top-24">
            <h2 className="font-bold mb-4">{t('Besteloverzicht', 'Order summary')}</h2>
            <div className="space-y-3 text-sm">
              <div className="flex justify-between"><span className="text-muted-foreground">{t('Subtotaal', 'Subtotal')}</span><span>€{totals.subtotal.toFixed(2)}</span></div>
              {appliedCoupon && (
                <div className="flex justify-between text-success">
                  <span className="flex items-center gap-1">
                    {t('Korting', 'Discount')} ({appliedCoupon.code})
                    <button onClick={() => removeCoupon(appliedCoupon.code).catch(() => undefined)} className="text-muted-foreground hover:text-destructive"><X className="w-3 h-3" /></button>
                  </span>
                  <span>-€{totals.discount.toFixed(2)}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-muted-foreground">{t('Verzending', 'Shipping')}</span>
                <span>{totals.shipping === 0 ? <span className="text-primary">{t('Gratis', 'Free')}</span> : `€${totals.shipping.toFixed(2)}`}</span>
              </div>
              {totals.shipping > 0 && totals.subtotal < FREE_SHIPPING_HINT_THRESHOLD && (
                <p className="text-xs text-muted-foreground">{t(`Nog €${(FREE_SHIPPING_HINT_THRESHOLD - totals.subtotal).toFixed(2)} tot gratis verzending`, `€${(FREE_SHIPPING_HINT_THRESHOLD - totals.subtotal).toFixed(2)} to go until free shipping`)}</p>
              )}
            </div>
            <div className="border-t border-border my-4 pt-4 flex justify-between font-bold text-lg">
              <span>{t('Totaal', 'Total')}</span>
              <span className="text-primary">€{totals.total.toFixed(2)}</span>
            </div>

            {!appliedCoupon && (
              <form className="flex gap-2 mb-4" onSubmit={handleApplyCoupon}>
                <div className="relative flex-1">
                  <Tag className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
                  <input type="text" value={couponInput} onChange={(e) => setCouponInput(e.target.value)} placeholder={t('Kortingscode', 'Coupon code')} disabled={applyCouponPending} className="w-full pl-9 pr-3 py-2 text-sm border border-border rounded-md bg-background focus:ring-2 focus:ring-ring outline-none disabled:opacity-50" />
                </div>
                <button type="submit" disabled={applyCouponPending || !couponInput.trim()} className="px-3 py-2 text-sm border border-border rounded-md hover:bg-muted transition-colors font-medium disabled:opacity-50">
                  {applyCouponPending ? <Loader2 className="w-4 h-4 animate-spin" /> : t('Toepassen', 'Apply')}
                </button>
              </form>
            )}
            {appliedCoupon && <p className="text-xs text-success mb-3">{t(`✓ Kortingscode "${appliedCoupon.code}" toegepast`, `✓ Coupon code "${appliedCoupon.code}" applied`)}</p>}
            {couponError && <p className="text-xs text-destructive mb-3">{couponError}</p>}

            {isLoggedIn && loyalty && loyalty.availableBalance > 0 && (
              <div className="mb-3 p-3 bg-primary/5 border border-primary/20 rounded-lg">
                <div className="flex items-center gap-2 text-sm">
                  <Star className="w-4 h-4 text-primary" />
                  <span className="font-medium">{t('U heeft', 'You have')} <span className="font-bold text-primary">{loyalty.availableBalance.toLocaleString()}</span> {t('punten', 'points')}</span>
                </div>
                {loyalty.canRedeem && <p className="text-xs text-muted-foreground mt-1">{t(`= €${loyalty.redeemableEuros.toFixed(2)} korting bij afrekenen`, `= €${loyalty.redeemableEuros.toFixed(2)} discount at checkout`)}</p>}
              </div>
            )}

            <Link to="/checkout" className="w-full flex items-center justify-center gap-2 bg-primary text-primary-foreground font-semibold py-3 rounded-md hover:bg-primary-hover transition-colors">
              {t('Afrekenen', 'Checkout')} <ArrowRight className="w-4 h-4" />
            </Link>

            <div className="mt-4 space-y-2">
              {[
                { icon: Shield, text: t('Veilig betalen via iDEAL & Bancontact', 'Secure payment via iDEAL & Bancontact') },
                { icon: Truck, text: t('Discrete & snelle verzending', 'Discreet & fast shipping') },
                { icon: Clock, text: t('Voor 15:30 besteld = zelfde dag verstuurd', 'Orders placed on weekdays before 12:00 ship the same day') },
              ].map((item) => (
                <div key={item.text} className="flex items-center gap-2 text-xs text-muted-foreground">
                  <item.icon className="w-3.5 h-3.5 text-primary shrink-0" />
                  {item.text}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
