import React, { useState, useMemo } from 'react'
import { trpc } from '../lib/trpc-client'
import { useQueryClient } from '@tanstack/react-query'
import { p, MyButton, pInput, div, LoadingDialog } from 'web-components'
import { useAllProducts } from '../hooks/prominent-api-hooks'
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
import { clearLocalCart } from '../hooks/cart-query-hooks'
import { useNavigate } from '@tanstack/react-router'
import { CreditCard, Banknote, Wallet, Tag, Info, Star, ShoppingBag, ArrowLeft } from 'lucide-react'

interface PaymentAndOrderProps {
  selectedAddress: number | null
  cartItems: any[]
  isFlashDelivery?: boolean
  onBack?: () => void
}

export function PaymentAndOrderComponent({
  selectedAddress,
  cartItems,
  isFlashDelivery = false,
  onBack,
}: PaymentAndOrderProps) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [userNotes, setUserNotes] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod')

  const { data: productsData } = useAllProducts()
  const { data: constsData } = useGetEssentialConsts()

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

  // Calculate totals
  const totalPrice = cartItems.reduce((sum, item) => {
    const product = productsById[item.productId]
    if (!product) return sum
    const price = isFlashDelivery ? (product.flashPrice ?? product.price ?? 0) : (product.price || 0)
    return sum + price * item.quantity
  }, 0)

  const deliveryCharge = useMemo(() => {
    const threshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold
    const charge = isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge
    return totalPrice < threshold ? charge : 0
  }, [totalPrice, constsData, isFlashDelivery])

  const finalTotalWithDelivery = totalPrice + deliveryCharge

  const placeOrderMutation = trpc.user.order.placeOrder.useMutation({
    onSuccess: (data) => {
      const orders = data.data
      const firstOrder = orders[0]

      // Clear cart and navigate to success page
      clearLocalCart(isFlashDelivery ? 'flash' : 'regular')
      queryClient.invalidateQueries({ queryKey: [`local-cart-${isFlashDelivery ? 'flash' : 'regular'}`] })

      navigate({
        to: '/home/order-success',
        search: { orderId: firstOrder?.id, totalAmount: finalTotalWithDelivery },
      })
    },
    onError: (error: any) => {
      alert(error.message || 'Failed to place order')
    },
    onSettled: () => {
      setIsLoading(false)
    },
  })

  const handlePlaceOrder = () => {
    if (!selectedAddress) {
      alert('Please select a delivery address')
      return
    }

    if (cartItems.length === 0) {
      alert('No items in cart')
      return
    }

    setIsLoading(true)

    const orderData = {
      selectedItems: cartItems.map((item) => ({
        productId: item.productId,
        quantity: item.quantity,
        slotId: isFlashDelivery ? null : item.slotId,
      })),
      addressId: selectedAddress,
      paymentMethod: paymentMethod,
      userNotes: userNotes,
      isFlashDelivery: isFlashDelivery,
    }

    placeOrderMutation.mutate(orderData)
  }

  return (
    <>
      {/* Back Button */}
      {onBack && (
        <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-4 shadow-sm">
          <div onClick={onBack} className="flex items-center gap-2">
            <ArrowLeft className="h-5 w-5 text-gray-500" />
            <p className="font-medium text-gray-600">Back to Cart</p>
          </div>
        </div>
      )}

      {/* Special Instructions */}
      <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <p className="font-bold mb-3 text-base text-gray-900">
          Delivery Instructions
        </p>
        <textarea
          value={userNotes}
          onChange={(e) => setUserNotes(e.target.value)}
          placeholder="Any special instructions for the delivery partner..."
          rows={3}
          className="w-full resize-none rounded-xl border border-gray-200 bg-gray-50 p-3 text-base outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500"
        />
      </div>

      {/* Payment Method */}
      <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <p className="font-bold mb-4 text-lg text-gray-900">
          Payment Method
        </p>

        {/* Online Payment (Coming Soon) */}
        <div className="mb-3 flex cursor-not-allowed items-center rounded-xl border border-gray-200 bg-gray-100 p-4 opacity-50">
          <div className="mr-3 flex h-5 w-5 items-center justify-center rounded-full border-2 border-gray-300" />
          <div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-gray-200">
            <CreditCard className="h-5 w-5 text-gray-400" />
          </div>
          <div>
            <p className="font-bold text-gray-500">
              Pay Online (Coming Soon)
            </p>
            <p className="text-xs text-gray-400">UPI, Cards, Netbanking</p>
          </div>
        </div>

        {/* Cash on Delivery */}
        <div
          onClick={() => setPaymentMethod('cod')}
          className={`flex items-center rounded-xl border p-4 transition-all ${
            paymentMethod === 'cod' ? 'border-brand-500 bg-blue-50' : 'border-gray-200'
          }`}
        >
          <div
            className={`mr-3 flex h-5 w-5 items-center justify-center rounded-full border-2 ${
              paymentMethod === 'cod' ? 'border-brand-500' : 'border-gray-400'
            }`}
          >
            {paymentMethod === 'cod' && <div className="h-2.5 w-2.5 rounded-full bg-brand-500" />}
          </div>
          <div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-green-50">
            <Banknote className="h-5 w-5 text-green-500" />
          </div>
          <div>
            <p className="font-bold text-gray-900">
              Cash on Delivery
            </p>
            <p className="text-xs text-gray-500">Pay when you receive</p>
          </div>
        </div>

        <div className="mt-3 flex items-center gap-4">
          <div className="flex items-center gap-1.5">
            <Wallet className="h-3 w-3 text-purple-600" />
            <p className="text-xs text-gray-500">UPI accepted during COD</p>
          </div>
          <div className="flex items-center gap-1.5">
            <Banknote className="h-3 w-3 text-green-500" />
            <p className="text-xs text-gray-500">Cash payment</p>
          </div>
        </div>
      </div>

      {/* Bill Details */}
      <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <p className="font-bold mb-4 text-lg text-gray-900">
          Bill Details
        </p>

        {/* Item Total */}
        <div className="mb-2 flex items-center justify-between">
          <p className="text-gray-500">Item Total</p>
          <p className="font-medium text-gray-900">
            ₹{totalPrice}
          </p>
        </div>

        {/* Delivery Fee */}
        <div className="mb-2 flex items-center justify-between">
          <div className="flex items-center gap-1">
            <p className="text-gray-500">Delivery Fee</p>
            <Info className="h-3.5 w-3.5 text-gray-400" />
          </div>
          <div className="flex items-center">
            {deliveryCharge === 0 && (
              <p className="mr-2 text-xs text-gray-400 line-through">
                ₹{isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge}
              </p>
            )}
            <p className={`font-medium ${deliveryCharge === 0 ? 'text-green-600' : 'text-gray-900'}`}>
              {deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`}
            </p>
          </div>
        </div>

        {/* Free Delivery Nudge */}
        {deliveryCharge > 0 && (() => {
          const threshold = isFlashDelivery
            ? constsData?.flashFreeDeliveryThreshold
            : constsData?.freeDeliveryThreshold
          return threshold > 0 && totalPrice < threshold ? (
            <div className="mb-2 flex items-center gap-2 rounded-lg bg-blue-50 p-2.5">
              <ShoppingBag className="h-4 w-4 text-blue-600" />
              <p className="font-medium flex-1 text-xs text-blue-700">
                Add products worth ₹{(threshold - totalPrice).toFixed(0)} for free delivery
              </p>
            </div>
          ) : null
        })()}

        {/* Divider */}
        <div className="my-2 h-px bg-gray-100" />

        {/* Grand Total */}
        <div className="flex items-center justify-between">
          <p className="font-bold text-lg text-gray-900">
            To Pay
          </p>
          <p className="font-bold text-xl text-gray-900">
            ₹{finalTotalWithDelivery.toFixed(2)}
          </p>
        </div>

        {/* Savings Banner */}
        {deliveryCharge === 0 && (
          <div className="mt-4 flex items-center justify-center gap-1.5 rounded-lg bg-green-50 p-2">
            <Star className="h-4 w-4 text-green-600" />
            <p className="font-bold text-xs text-green-700">
              You saved ₹{(isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge)?.toFixed(2)} on delivery
            </p>
          </div>
        )}
      </div>

      {/* Download App for Coupons */}
      <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <div className="mb-3 flex items-center gap-2">
          <Tag className="h-5 w-5 text-brand-500" />
          <p className="font-bold text-lg text-gray-900">
            Coupons & Offers
          </p>
        </div>
        <p className="text-sm text-gray-600 mb-3">
          Download our app to unlock exclusive coupons and special offers!
        </p>
        <a
          href={constsData?.playStoreUrl || '#'}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 rounded-xl bg-brand-500 px-4 py-2 text-sm font-bold text-white hover:bg-brand-600 transition-colors"
        >
          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
          </svg>
          Download App
        </a>
      </div>

      {/* Bottom Action Bar */}
      <div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        {!selectedAddress && (
          <div className="mb-3 flex items-center gap-2 rounded-lg bg-red-50 p-3">
            <Info className="h-4 w-4 text-red-500" />
            <p className="font-medium text-sm text-red-600">
              Please select a delivery address to place order
            </p>
          </div>
        )}

        <MyButton
          fullWidth
          textContent="Place Order"
          onClick={handlePlaceOrder}
          disabled={!selectedAddress || placeOrderMutation.isPending}
          className={`py-4 text-lg ${
            selectedAddress ? 'bg-brand-500 text-white' : 'bg-gray-300 text-gray-500'
          }`}
        />
      </div>

      <LoadingDialog open={isLoading} message="Placing your order..." />
    </>
  )
}
