import { useEffect, useMemo, useState } from 'react'
import { initMercadoPago, Payment } from '@mercadopago/sdk-react'
import { Shell } from '../layouts/Shell'
import { selectGroupedCart, selectCartSummary, useCartStore } from '../stores/cartStore'
import { useAuth } from '../context/AuthContext'

const MP_PUBLIC_KEY = import.meta.env.VITE_MP_PUBLIC_KEY || 'TEST-PUBLIC-KEY'

export function CheckoutPage() {
  const { user } = useAuth()
  const summary = useCartStore(selectCartSummary)
  const groups = useCartStore(selectGroupedCart)
  const [status, setStatus] = useState<'pendente' | 'pago' | null>(null)

  useEffect(() => {
    initMercadoPago(MP_PUBLIC_KEY, { locale: 'pt-BR' })
  }, [])

  const preferenceId = useMemo(() => `pref-${Date.now()}`, [])

  return (
    <Shell>
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2 space-y-3 rounded-lg bg-white p-4 shadow-sm">
          <div className="flex items-center justify-between border-b border-gray-200 pb-3">
            <div>
              <h1 className="text-xl font-semibold text-medicalBlue">Checkout e Pagamento</h1>
              <p className="text-sm text-gray-600">Split automático por distribuidora, status pendente/pago.</p>
            </div>
            <div className="text-right">
              <p className="text-xs text-gray-500">Comprador</p>
              <p className="font-semibold text-gray-800">{user?.name}</p>
            </div>
          </div>
          {Object.entries(groups).map(([vendorId, group]) => (
            <div key={vendorId} className="rounded border border-gray-200 bg-gray-50 p-3">
              <div className="flex items-center justify-between">
                <p className="font-semibold text-gray-800">{group.vendorName}</p>
                <p className="text-sm font-bold text-medicalBlue">R$ {group.total.toFixed(2)}</p>
              </div>
              <p className="text-xs text-gray-600">Itens enviados no split de pagamento.</p>
            </div>
          ))}
        </div>
        <div className="space-y-3 rounded-lg bg-white p-4 shadow-sm">
          <div>
            <p className="text-sm font-semibold text-gray-700">Resumo</p>
            <p className="text-2xl font-bold text-medicalBlue">R$ {summary.totalValue.toFixed(2)}</p>
          </div>
          <div className="rounded bg-gray-100 p-3 text-sm">
            <p className="font-semibold text-gray-700">Status</p>
            <p className="text-gray-600">{status ? status.toUpperCase() : 'Aguardando pagamento'}</p>
          </div>
          <div className="rounded bg-gray-50 p-3">
            <p className="text-sm font-semibold text-gray-700">Pagamento Mercado Pago</p>
            <Payment
              initialization={{ preferenceId, amount: summary.totalValue || 0.01 }}
              customization={{ paymentMethods: { creditCard: 'all', bankTransfer: 'all' } }}
              onSubmit={async () => {
                setStatus('pendente')
              }}
              onReady={() => console.log('Payment brick pronto')}
              onError={(error) => {
                console.error(error)
                setStatus(null)
              }}
            />
          </div>
        </div>
      </div>
    </Shell>
  )
}
