import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useAuth } from '../lib/auth-context'
import { useGetCart } from '../hooks/cart-query-hooks'
import { useAllProducts } from '../hooks/prominent-api-hooks'
import { ProtectedRoute } from '../components/ProtectedRoute'
import { CheckoutAddressSelector } from '../components/CheckoutAddressSelector'
import { PaymentAndOrderComponent } from '../components/PaymentAndOrderComponent'
import { AddressForm } from '../components/AddressForm'
import { Dialog } from '../components/Dialog'
import { useAddressStore } from '../lib/stores/address-store'
import { useQueryClient } from '@tanstack/react-query'
import { p, div } from 'web-components'
import { MapPin, ShoppingCart, ChevronLeft } from 'lucide-react'

export const Route = createFileRoute('/checkout')({ component: CheckoutPage })

function CheckoutPage() {
  return (
    <ProtectedRoute>
      <CheckoutContent />
    </ProtectedRoute>
  )
}

function CheckoutContent() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { isAuthenticated } = useAuth()
  const { selectedAddressId, setSelectedAddressId } = useAddressStore()
  const [showAddAddress, setShowAddAddress] = useState(false)
  const [editingAddress, setEditingAddress] = useState<any>(null)

  const cartType: 'regular' | 'flash' = 'regular'
  const { data: cartData } = useGetCart(cartType)
  const { data: productsData } = useAllProducts()

  const products = productsData?.products || []
  const productsById: Record<number, any> = {}
  products.forEach((p: any) => { productsById[p.id] = p })

  const cartItems = (cartData?.items || []).filter((item) => productsById[item.productId])

  // Handle empty cart case
  if (cartItems.length === 0) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-gray-50 p-6">
        <ShoppingCart className="mb-4 h-16 w-16 text-gray-400" />
        <p className="font-bold mb-2 text-center text-xl text-gray-900">
          Your cart is empty
        </p>
        <p className="mb-6 text-center text-gray-500">
          Add some delicious items to your cart before checking out
        </p>
        <div
          onClick={() => navigate({ to: '/home' })}
          className="rounded-lg bg-brand-500 px-6 py-3"
        >
          <p className="font-bold text-white">
            Back to Shopping
          </p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 pb-8">
      {/* Checkout Header */}
      <div className="sticky top-0 z-10 mb-4 border-b border-gray-100 bg-white px-4 py-3">
        <div className="flex items-center">
          <div
            onClick={() => navigate({ to: '/cart' })}
            className="-ml-2 mr-1 flex items-center p-2"
          >
            <ChevronLeft className="h-7 w-7 text-gray-700" />
          </div>
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-50">
            <MapPin className="h-5 w-5 text-blue-500" />
          </div>
          <p className="font-bold ml-3 text-lg text-gray-800">
            Checkout
          </p>
        </div>
      </div>

      <div className="px-4">
        {/* Address Selection */}
        <CheckoutAddressSelector
          onAddressSelect={setSelectedAddressId}
          onAddAddress={() => {
            setEditingAddress(null)
            setShowAddAddress(true)
          }}
          onEditAddress={(address) => {
            setEditingAddress(address)
            setShowAddAddress(true)
          }}
        />

        {/* Payment and Order Summary */}
        <PaymentAndOrderComponent
          selectedAddress={selectedAddressId}
          cartItems={cartItems}
          isFlashDelivery={false}
          onBack={() => navigate({ to: '/cart' })}
        />
      </div>

      {/* Add/Edit Address Dialog */}
      <Dialog
        open={showAddAddress}
        onClose={() => {
          setShowAddAddress(false)
          setEditingAddress(null)
        }}
        title={editingAddress ? 'Edit Address' : 'Add Address'}
      >
        <AddressForm
          onSuccess={(addressId) => {
            setShowAddAddress(false)
            setEditingAddress(null)
            if (addressId) {
              setSelectedAddressId(addressId)
            }
            queryClient.invalidateQueries({ queryKey: ['user.address.getUserAddresses'] })
          }}
          initialValues={editingAddress || undefined}
          isEdit={!!editingAddress}
        />
      </Dialog>
    </div>
  )
}
