import { useState, useEffect } 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 { shippingService } from '@/services/shippingService'
import { apiClient } from '@/services/apiClient'
import { formatCurrency } from '@/utils/format'
import { ArrowLeft, CheckCircle, 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)

  // Shipping options state
  const [shippingOptions, setShippingOptions] = useState<Record<string, { delivery: boolean, pickup: boolean, pickupAddress: string, price: number }>>({})

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

  // Pre-fill address from company
  useEffect(() => {
    async function fetchCompanyAddress() {
      try {
        // TODO: Use a proper service for this
        const company = await apiClient.get<any>('/v1/companies/me')
        if (company) {
          setShipping(prev => ({
            ...prev,
            street: company.street || '', // Wait, company model fields differ from shipping fields?
            // Let's check company model in backend: city, state, etc.
            // Actually, the backend Company model has: city, state, latitude, longitude.
            // It seems it does NOT have street, number, district, zip_code separately in the main table?
            // Let's re-read models.go.
            // Ah, lines 18-21: Latitude, Longitude, City, State.
            // It seems we lack detailed address fields in Company model for pre-filling!
            // Wait, seeder line 113: city, state.
            // We might only be able to pre-fill city/state for now unless I missed something.
            city: company.city || '',
            state: company.state || '',
            // We can't pre-fill street/number if they aren't there.
          }))
        }
      } catch (e) {
        console.error("Failed to fetch company address", e)
      }
    }
    if (user) fetchCompanyAddress()
  }, [user])

  // Fetch shipping settings for sellers
  useEffect(() => {
    async function fetchShipping() {
      const options: Record<string, any> = {}
      for (const sellerId of Object.keys(groups)) {
        try {
          const settings = await shippingService.getSettings(sellerId)
          options[sellerId] = {
            delivery: settings.active,
            pickup: settings.pickup_active,
            pickupAddress: settings.pickup_address,
            price: 15.00 // Mock calc for now, or implement calculateShipping
          }
        } catch (e) {
          console.error(`Failed to fetch shipping for ${sellerId}`, e)
        }
      }
      setShippingOptions(options)
    }
    if (Object.keys(groups).length > 0) fetchShipping()
  }, [groups])

  // Payment method selection
  const [paymentMethod, setPaymentMethod] = useState<'pix' | 'credit_card' | 'debit_card'>('credit_card')

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setPaymentMethod(prev => prev) // Keep state if needed, though strictly not needed for this simple setter
    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
          },
          payment_method: paymentMethod
        }
        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 Selection */}
            <div className="rounded-lg bg-white p-6 shadow-sm">
              <div className="mb-4 flex items-center gap-2">
                <CheckCircle className="h-5 w-5 text-medicalBlue" />
                <h2 className="text-lg font-semibold text-gray-800">Forma de Pagamento</h2>
              </div>

              <div className="space-y-3">
                <label className={`flex cursor-pointer items-center rounded-lg border p-4 transition-colors ${paymentMethod === 'pix' ? 'border-medicalBlue bg-blue-50' : 'border-gray-200 hover:bg-gray-50'}`}>
                  <input
                    type="radio"
                    name="paymentMethod"
                    value="pix"
                    checked={paymentMethod === 'pix'}
                    onChange={() => setPaymentMethod('pix')}
                    className="h-4 w-4 border-gray-300 text-medicalBlue focus:ring-medicalBlue"
                  />
                  <div className="ml-3">
                    <span className="block text-sm font-medium text-gray-900">Pix</span>
                    <span className="block text-sm text-gray-500">Aprovação imediata</span>
                  </div>
                </label>

                <label className={`flex cursor-pointer items-center rounded-lg border p-4 transition-colors ${paymentMethod === 'credit_card' ? 'border-medicalBlue bg-blue-50' : 'border-gray-200 hover:bg-gray-50'}`}>
                  <input
                    type="radio"
                    name="paymentMethod"
                    value="credit_card"
                    checked={paymentMethod === 'credit_card'}
                    onChange={() => setPaymentMethod('credit_card')}
                    className="h-4 w-4 border-gray-300 text-medicalBlue focus:ring-medicalBlue"
                  />
                  <div className="ml-3">
                    <span className="block text-sm font-medium text-gray-900">Cartão de Crédito</span>
                    <span className="block text-sm text-gray-500">Em até 12x</span>
                  </div>
                </label>

                <label className={`flex cursor-pointer items-center rounded-lg border p-4 transition-colors ${paymentMethod === 'debit_card' ? 'border-medicalBlue bg-blue-50' : 'border-gray-200 hover:bg-gray-50'}`}>
                  <input
                    type="radio"
                    name="paymentMethod"
                    value="debit_card"
                    checked={paymentMethod === 'debit_card'}
                    onChange={() => setPaymentMethod('debit_card')}
                    className="h-4 w-4 border-gray-300 text-medicalBlue focus:ring-medicalBlue"
                  />
                  <div className="ml-3">
                    <span className="block text-sm font-medium text-gray-900">Cartão de Débito</span>
                    <span className="block text-sm text-gray-500">Pagamento à vista</span>
                  </div>
                </label>
              </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>
                    ))}

                    {/* Shipping Options for this Vendor */}
                    {shippingOptions[vendorId] && (
                      <div className="mt-3 rounded-md bg-gray-50 p-3">
                        <p className="mb-2 text-xs font-semibold text-gray-500 uppercase">Entrega</p>
                        <div className="flex flex-col gap-2">
                          {shippingOptions[vendorId].delivery ? (
                            <label className="flex cursor-pointer items-center justify-between text-sm">
                              <div className="flex items-center">
                                <input type="radio" name={`shipping-${vendorId}`} className="mr-2 text-medicalBlue focus:ring-medicalBlue" defaultChecked />
                                <span>Entrega Padrão</span>
                              </div>
                              <span className="font-medium text-gray-900">R$ {formatCurrency(shippingOptions[vendorId].price * 100)}</span>
                            </label>
                          ) : (
                            <div className="text-sm text-red-500">Entrega indisponível para esta região</div>
                          )}

                          {shippingOptions[vendorId].pickup && (
                            <label className="flex cursor-pointer items-center justify-between text-sm">
                              <div className="flex items-center">
                                <input type="radio" name={`shipping-${vendorId}`} className="mr-2 text-medicalBlue focus:ring-medicalBlue" />
                                <div className="flex flex-col">
                                  <span>Retirada na Loja</span>
                                  <span className="text-xs text-gray-500">{shippingOptions[vendorId].pickupAddress}</span>
                                </div>
                              </div>
                              <span className="font-medium text-green-600">Grátis</span>
                            </label>
                          )}
                        </div>
                      </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>
                  <p className="mt-1 text-xs text-gray-500 text-right">Taxas de entrega não incluídas no total acima</p>
                </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>
  )
}
