import { Shell } from '../layouts/Shell'
import { selectGroupedCart, selectCartSummary, useCartStore } from '../stores/cartStore'

export function CartPage() {
  const items = useCartStore((state) => state.items)
  const groups = useCartStore(selectGroupedCart)
  const summary = useCartStore(selectCartSummary)
  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 items-center justify-between">
          <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>
          <div className="text-right">
            <p className="text-sm text-gray-600">Itens: {summary.totalItems}</p>
            <p className="text-lg font-semibold text-medicalBlue">R$ {summary.totalValue.toFixed(2)}</p>
          </div>
        </div>
        {items.length === 0 ? (
          <div className="rounded-lg bg-white p-6 text-center text-gray-600 shadow">Nenhum item no carrinho.</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>
                      <p className="font-semibold text-medicalBlue">R$ {item.unitPrice.toFixed(2)}</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>
                      <p className="font-semibold text-gray-800">
                        R$ {(item.quantity * item.unitPrice).toFixed(2)}
                      </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>
                  <span className="font-bold text-medicalBlue">R$ {group.total.toFixed(2)}</span>
                </div>
              </div>
            </div>
          ))
        )}
        {items.length > 0 && (
          <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>
            <a
              href="/checkout"
              className="rounded bg-healthGreen px-4 py-2 text-sm font-semibold text-white"
            >
              Seguir para checkout unificado
            </a>
          </div>
        )}
      </div>
    </Shell>
  )
}
