import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Shell } from '../layouts/Shell'
import { useCartStore, selectGroupedCart, selectCartSummary } from '../stores/cartStore'
import { useAuth } from '../context/AuthContext'
import { ordersService, CreateOrderRequest } from '../services/ordersService'
import { formatCurrency } from '../utils/format'
import { ArrowLeft, CheckCircle2, Truck } from 'lucide-react'

export function CheckoutPage() {
  const navigate = useNavigate()
  const { user } = useAuth()
  const groups = useCartStore(selectGroupedCart)
  const summary = useCartStore(selectCartSummary)
  const clearAll = useCartStore((state) => state.clearAll)

  const [loading, setLoading] = useState(false)
  const [shipping, setShipping] = useState({
    recipient_name: user?.name || '',
    street: '',
    number: '',
    complement: '',
    district: '',
    city: '',
    state: '',
    zip_code: '',
    country: 'Brasil'
  })

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setShipping(prev => ({ ...prev, [name]: value }))
  }

  const handlePlaceOrder = async () => {
    if (!user) return

    setLoading(true)
    try {
      // Create an order for each vendor group
      const promises = Object.entries(groups).map(([sellerId, group]) => {
        const orderData: CreateOrderRequest = {
          buyer_id: user.id,
          seller_id: sellerId,
          items: group.items.map(item => ({
            product_id: item.id,
            quantity: item.quantity,
            unit_cents: item.unitPrice,
            batch: item.batch,
            expires_at: item.expiry // Ensure format matches backend expectation? Backend expects ISO. Cart stores string?
          })),
          shipping: {
            recipient_name: shipping.recipient_name,
            street: shipping.street,
            number: shipping.number,
            complement: shipping.complement,
            district: shipping.district,
            city: shipping.city,
            state: shipping.state,
            zip_code: shipping.zip_code,
            country: shipping.country
          }
        }
        return ordersService.createOrder(orderData)
      })

      await Promise.all(promises)

      clearAll()
      navigate('/orders')
    } catch (error) {
      console.error('Failed to create order', error)
      alert('Erro ao criar pedido. Verifique os dados e tente novamente.')
    } finally {
      setLoading(false)
    }
  }

  if (summary.totalItems === 0) {
    return (
      <Shell>
        <div className="flex flex-col items-center justify-center py-20">
          <h2 className="text-xl font-semibold">Seu carrinho está vazio</h2>
          <button onClick={() => navigate('/inventory')} className="mt-4 text-medicalBlue hover:underline">
            Voltar para o catálogo
          </button>
        </div>
      </Shell>
    )
  }

  return (
    <Shell>
      <div className="mx-auto max-w-4xl space-y-6">
        <button onClick={() => navigate('/cart')} className="flex items-center text-sm text-gray-500 hover:text-gray-900">
          <ArrowLeft className="mr-1 h-4 w-4" /> Voltar para o carrinho
        </button>

        <h1 className="text-2xl font-bold text-gray-900">Finalizar Compra</h1>

        <div className="grid grid-cols-1 gap-8 md:grid-cols-3">
          {/* Left Column: Form */}
          <div className="space-y-6 md:col-span-2">
            <div className="rounded-lg bg-white p-6 shadow-sm">
              <div className="mb-4 flex items-center gap-2">
                <Truck className="h-5 w-5 text-medicalBlue" />
                <h2 className="text-lg font-semibold text-gray-800">Endereço de Entrega</h2>
              </div>

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div className="sm:col-span-2">
                  <label className="mb-1 block text-sm font-medium text-gray-700">Destinatário</label>
                  <input
                    type="text"
                    name="recipient_name"
                    value={shipping.recipient_name}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">CEP</label>
                  <input
                    type="text"
                    name="zip_code"
                    value={shipping.zip_code}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">Rua</label>
                  <input
                    type="text"
                    name="street"
                    value={shipping.street}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">Número</label>
                  <input
                    type="text"
                    name="number"
                    value={shipping.number}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">Complemento</label>
                  <input
                    type="text"
                    name="complement"
                    value={shipping.complement}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">Bairro</label>
                  <input
                    type="text"
                    name="district"
                    value={shipping.district}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">Cidade</label>
                  <input
                    type="text"
                    name="city"
                    value={shipping.city}
                    onChange={handleInputChange}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
                <div>
                  <label className="mb-1 block text-sm font-medium text-gray-700">Estado</label>
                  <input
                    type="text"
                    name="state"
                    value={shipping.state}
                    onChange={handleInputChange}
                    maxLength={2}
                    className="w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-medicalBlue focus:outline-none focus:ring-1 focus:ring-medicalBlue"
                  />
                </div>
              </div>
            </div>

            {/* Payment Method Stub */}
            <div className="rounded-lg bg-white p-6 shadow-sm">
              <h2 className="text-lg font-semibold text-gray-800">Pagamento</h2>
              <p className="mt-2 text-sm text-gray-600">Este é um ambiente de demonstração. O pagamento será processado como "Confirmado" para fins de teste.</p>
              <div className="mt-4 flex items-center gap-3 rounded-lg border border-green-200 bg-green-50 p-4">
                <CheckCircle2 className="h-5 w-5 text-green-600" />
                <span className="text-sm font-medium text-green-800">Método de Teste (Aprovação Automática)</span>
              </div>
            </div>
          </div>

          {/* Right Column: Summary */}
          <div className="space-y-6">
            <div className="rounded-lg bg-white p-6 shadow-sm">
              <h2 className="mb-4 text-lg font-semibold text-gray-800">Resumo do Pedido</h2>
              <div className="space-y-4">
                {Object.entries(groups).map(([vendorId, group]) => (
                  <div key={vendorId} className="border-b border-gray-100 pb-4 last:border-0 last:pb-0">
                    <p className="mb-2 text-sm font-medium text-gray-600">{group.vendorName}</p>
                    {group.items.map(item => (
                      <div key={item.id} className="flex justify-between text-sm">
                        <span className="text-gray-800">{item.quantity}x {item.name}</span>
                        <span className="text-gray-600">R$ {formatCurrency(item.quantity * item.unitPrice)}</span>
                      </div>
                    ))}
                  </div>
                ))}

                <div className="mt-4 border-t border-gray-200 pt-4">
                  <div className="flex justify-between font-semibold text-gray-900">
                    <span>Total</span>
                    <span className="text-xl text-medicalBlue">R$ {formatCurrency(summary.totalValue)}</span>
                  </div>
                </div>

                <button
                  onClick={handlePlaceOrder}
                  disabled={loading}
                  className="mt-6 w-full rounded-lg bg-medicalBlue px-4 py-3 font-semibold text-white shadow-sm hover:bg-blue-700 disabled:opacity-50"
                >
                  {loading ? 'Processando...' : 'Confirmar Pedido'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Shell>
  )
}
