import { ShoppingBasket } from 'lucide-react'
import { Link } from 'react-router-dom'
import { Shell } from '@/layouts/Shell'
import { selectGroupedCart, selectCartSummary, useCartStore } from '@/stores/cartStore'
import { formatCents } from '@/utils/format'

// Debug logging for price values
const logPrice = (label: string, value: number | undefined) => {
  console.log(`%c🛒 [Cart] ${label}:`, 'color: #10B981; font-weight: bold', {
    rawValue: value,
    inCents: value,
    inReais: value ? (value / 100).toFixed(2) : '0.00',
    formatted: value ? formatCents(value) : 'N/A'
  })
}

export function CartPage() {
  const items = useCartStore((state) => state.items)
  const groups = useCartStore(selectGroupedCart)
  const summary = useCartStore(selectCartSummary)
  const isEmpty = items.length === 0
  const updateQuantity = useCartStore((state) => state.updateQuantity)
  const removeItem = useCartStore((state) => state.removeItem)
  const clearVendor = useCartStore((state) => state.clearVendor)
  const clearAll = useCartStore((state) => state.clearAll)

  return (
    <Shell>
      <div className="space-y-4">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-semibold text-medicalBlue">Carrinho B2B</h1>
            <p className="text-sm text-gray-600">
              Agrupamento automático por distribuidora para suportar checkout unificado ou múltiplo.
            </p>
          </div>
          {!isEmpty && (
            <div className="text-right">
              <p className="text-sm text-gray-600">Itens: {summary.totalItems}</p>
              {/* Log total value */}
              {(() => { logPrice('Total do carrinho', summary.totalValue); return null })()}
              <p className="text-lg font-semibold text-medicalBlue">{formatCents(summary.totalValue)}</p>
            </div>
          )}
        </div>
        {isEmpty ? (
          <div className="flex min-h-[60vh] items-center justify-center">
            <div className="w-full max-w-2xl rounded-2xl bg-white px-6 py-10 text-center shadow-sm sm:px-10">
              <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-gray-100">
                <ShoppingBasket className="h-10 w-10 text-gray-300" />
              </div>
              <h2 className="mt-5 text-xl font-semibold text-gray-800">Seu carrinho está vazio</h2>
              <p className="mt-3 text-sm text-gray-600 sm:text-base">
                Parece que você ainda não adicionou produtos das distribuidoras. Explore nosso catálogo para
                encontrar medicamentos e suprimentos.
              </p>
              <a
                href="/inventory"
                className="mt-6 inline-flex items-center justify-center rounded-lg px-6 py-3 text-sm font-semibold text-white shadow-sm transition hover:opacity-90"
                style={{ backgroundColor: '#0F4C81' }}
              >
                Explorar Produtos
              </a>
            </div>
          </div>
        ) : (
          Object.entries(groups).map(([vendorId, group]) => (
            <div key={vendorId} className="space-y-2 rounded-lg bg-white p-4 shadow-sm">
              <div className="flex items-center justify-between border-b border-gray-200 pb-2">
                <div>
                  <p className="text-lg font-semibold text-gray-800">{group.vendorName}</p>
                  <p className="text-xs text-gray-500">Checkout dedicado ou combine no fluxo unificado.</p>
                </div>
                <button
                  className="text-xs font-semibold text-medicalBlue hover:underline"
                  onClick={() => clearVendor(vendorId)}
                >
                  Limpar fornecedor
                </button>
              </div>
              <div className="space-y-2">
                {group.items.map((item) => (
                  <div
                    key={item.id}
                    className="grid grid-cols-6 items-center gap-3 rounded bg-gray-50 px-3 py-2 text-sm"
                  >
                    <div className="col-span-2">
                      <p className="font-semibold text-gray-800">{item.name}</p>
                      <p className="text-xs text-gray-500">{item.activeIngredient} • Lote {item.batch}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">Validade</p>
                      <p className="font-medium text-gray-800">{item.expiry}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-gray-500">Preço</p>
                      {/* Log unit price */}
                      {(() => { logPrice(`Preço unitário ${item.name}`, item.unitPrice); return null })()}
                      <p className="font-semibold text-medicalBlue">{formatCents(item.unitPrice)}</p>
                    </div>
                    <div className="flex items-center justify-end gap-2">
                      <input
                        type="number"
                        min={1}
                        className="w-20 rounded border border-gray-200 px-2 py-1"
                        value={item.quantity}
                        onChange={(e) => updateQuantity(item.id, Number(e.target.value))}
                      />
                      <span className="text-xs text-gray-500">unidades</span>
                    </div>
                    <div className="text-right">
                      <p className="text-xs text-gray-500">Subtotal</p>
                      {/* Log subtotal */}
                      {(() => { logPrice(`Subtotal ${item.name} (${item.quantity}x)`, item.quantity * item.unitPrice); return null })()}
                      <p className="font-semibold text-gray-800">
                        {formatCents(item.quantity * item.unitPrice)}
                      </p>
                      <button
                        className="text-xs text-red-500 hover:underline"
                        onClick={() => removeItem(item.id)}
                      >
                        Remover
                      </button>
                    </div>
                  </div>
                ))}
                <div className="flex items-center justify-between rounded bg-gray-100 px-3 py-2 text-sm">
                  <span className="font-semibold text-gray-700">Total do fornecedor</span>
                  {/* Log vendor total */}
                  {(() => { logPrice('Total fornecedor', group.total); return null })()}
                  <span className="font-bold text-medicalBlue">{formatCents(group.total)}</span>
                </div>
              </div>
            </div>
          ))
        )}
        {!isEmpty && (
          <div className="flex justify-end gap-3">
            <button className="rounded bg-gray-200 px-4 py-2 text-sm font-semibold" onClick={clearAll}>
              Limpar carrinho
            </button>
            <Link
              to="/checkout"
              className="rounded bg-healthGreen px-4 py-2 text-sm font-semibold text-white"
            >
              Seguir para checkout unificado
            </Link>
          </div>
        )}
      </div>
    </Shell>
  )
}
