'use client';
import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { Minus, Plus, Trash2, ArrowLeft, Tag } from 'lucide-react';
import { useApi } from '@/hooks/useApi';
import { storeService } from '@/services/store.service';
import { couponsService } from '@/services/coupons.service';
import { useCart, cartItemKey } from '@/hooks/useCart';
import { EmptyState } from '@/components/ui/States';
import { formatCurrency } from '@/utils/formatCurrency';
import type { CouponValidationResult } from '@/types';

export default function CarrinhoPage() {
  const params = useParams();
  const router = useRouter();
  const slug = params.slug as string;
  const { items, subtotal, updateQty, remove } = useCart();
  const { data: store } = useApi(() => storeService.getBySlug(slug), [slug]);

  const [code, setCode] = useState('');
  const [coupon, setCoupon] = useState<CouponValidationResult | null>(null);
  const [checking, setChecking] = useState(false);

  async function applyCoupon() {
    if (!store || !code) return;
    setChecking(true);
    const res = await couponsService.validate(store.id, code, subtotal);
    setCoupon(res);
    setChecking(false);
  }

  const discount = coupon?.valid ? coupon.discount : 0;
  const shipping = subtotal > 0 ? 20 : 0;
  const total = Math.max(0, subtotal - discount) + shipping;

  if (items.length === 0) {
    return (
      <div className="py-16">
        <EmptyState
          title="Seu carrinho está vazio"
          description="Adicione produtos para continuar."
          action={<Link href={`/loja/${slug}`} className="rounded-lg px-5 py-2.5 text-sm font-medium text-white" style={{ background: 'var(--store-button)' }}>Ver produtos</Link>}
        />
      </div>
    );
  }

  return (
    <div className="py-6">
      <Link href={`/loja/${slug}`} className="mb-4 inline-flex items-center gap-1 text-sm text-ink-500 hover:text-ink-900">
        <ArrowLeft className="h-4 w-4" /> Continuar comprando
      </Link>
      <h1 className="mb-6 font-display text-2xl font-bold text-ink-900">Carrinho</h1>

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="space-y-3 lg:col-span-2">
          {items.map((it) => {
            const key = cartItemKey(it);
            return (
              <div key={key} className="flex gap-4 rounded-xl border border-ink-100 p-3">
                {it.imageUrl && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={it.imageUrl} alt={it.name} className="h-20 w-20 rounded-lg object-cover" />
                )}
                <div className="flex flex-1 flex-col">
                  <div className="flex items-start justify-between">
                    <div>
                      <p className="font-medium text-ink-900">{it.name}</p>
                      {it.variationLabel && <p className="text-xs text-ink-400">{it.variationLabel}</p>}
                    </div>
                    <button onClick={() => remove(key)} className="text-ink-400 hover:text-red-600" aria-label="Remover"><Trash2 className="h-4 w-4" /></button>
                  </div>
                  <div className="mt-auto flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <button onClick={() => updateQty(key, it.quantity - 1)} className="flex h-7 w-7 items-center justify-center rounded-md border border-ink-200 text-ink-600 hover:bg-ink-50"><Minus className="h-3 w-3" /></button>
                      <span className="w-6 text-center text-sm font-medium">{it.quantity}</span>
                      <button onClick={() => updateQty(key, it.quantity + 1)} disabled={it.quantity >= it.maxStock} className="flex h-7 w-7 items-center justify-center rounded-md border border-ink-200 text-ink-600 hover:bg-ink-50 disabled:opacity-40"><Plus className="h-3 w-3" /></button>
                    </div>
                    <span className="font-medium text-ink-900">{formatCurrency(it.unitPrice * it.quantity)}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="space-y-4">
          <div className="rounded-xl border border-ink-100 p-4">
            <p className="mb-3 flex items-center gap-2 text-sm font-medium text-ink-700"><Tag className="h-4 w-4" /> Cupom de desconto</p>
            <div className="flex gap-2">
              <input value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="CUPOM" className="h-10 flex-1 rounded-lg border border-ink-200 px-3 text-sm uppercase" />
              <button onClick={applyCoupon} disabled={checking || !code} className="rounded-lg px-4 text-sm font-medium text-white disabled:opacity-50" style={{ background: 'var(--store-primary)' }}>Aplicar</button>
            </div>
            {coupon && <p className={`mt-2 text-xs ${coupon.valid ? 'text-emerald-600' : 'text-red-600'}`}>{coupon.message}</p>}
          </div>

          <div className="rounded-xl border border-ink-100 p-4">
            <h2 className="mb-3 font-semibold text-ink-900">Resumo</h2>
            <div className="space-y-1.5 text-sm">
              <div className="flex justify-between text-ink-600"><span>Subtotal</span><span>{formatCurrency(subtotal)}</span></div>
              {discount > 0 && <div className="flex justify-between text-emerald-600"><span>Desconto</span><span>- {formatCurrency(discount)}</span></div>}
              <div className="flex justify-between text-ink-600"><span>Frete estimado</span><span>{formatCurrency(shipping)}</span></div>
              <div className="flex justify-between border-t border-ink-100 pt-2 text-base font-semibold text-ink-900"><span>Total</span><span>{formatCurrency(total)}</span></div>
            </div>
            <button
              onClick={() => router.push(`/loja/${slug}/checkout${coupon?.valid ? `?cupom=${code}` : ''}`)}
              className="mt-4 w-full rounded-lg py-3 text-sm font-medium text-white"
              style={{ background: 'var(--store-button)' }}
            >
              Finalizar compra
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
