<template>
  <div class="container mx-auto px-4 py-8 max-w-4xl">
    <!-- Loading State -->
    <div v-if="isLoading" class="flex justify-center items-center min-h-64">
      <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
    </div>

    <!-- Error State -->
    <div v-else-if="error || !checkoutCart" class="text-center py-12">
      <h2 class="text-2xl font-bold text-red-600 mb-4">Checkout Error</h2>
      <p class="text-muted-foreground mb-4">{{ error || 'Cart not found' }}</p>
      <Button @click="$router.push('/cart')" variant="outline">
        Return to Cart
      </Button>
    </div>

    <!-- Checkout Content -->
    <div v-else class="space-y-8">
      <!-- Header -->
      <div class="text-center">
        <h1 class="text-3xl font-bold text-foreground mb-2">Checkout</h1>
        <p class="text-muted-foreground">{{ stallName }}</p>
      </div>

      <!-- Order Review -->
      <Card>
        <CardHeader>
          <CardTitle>Order Review</CardTitle>
          <CardDescription>Review your items before placing the order</CardDescription>
        </CardHeader>
        <CardContent>
          <!-- Cart Items -->
          <div class="space-y-4 mb-6">
            <div 
              v-for="item in checkoutCart.products" 
              :key="item.product.id"
              class="flex items-center justify-between p-4 border border-border rounded-lg"
            >
              <div class="flex items-center space-x-4">
                <!-- Product Image -->
                <div class="w-16 h-16 bg-muted rounded-lg flex items-center justify-center">
                  <img 
                    v-if="item.product.images?.[0]" 
                    :src="item.product.images[0]" 
                    :alt="item.product.name"
                    class="w-full h-full object-cover rounded-lg"
                  />
                  <Package v-else class="w-8 h-8 text-muted-foreground" />
                </div>
                
                <!-- Product Details -->
                <div>
                  <h3 class="font-semibold text-foreground">{{ item.product.name }}</h3>
                  <p class="text-sm text-muted-foreground">{{ formatPrice(item.product.price, item.product.currency) }} each</p>
                  <p class="text-sm text-muted-foreground">Quantity: {{ item.quantity }}</p>
                </div>
              </div>
              
              <!-- Item Total -->
              <div class="text-right">
                <p class="font-semibold text-foreground">
                  {{ formatPrice(item.product.price * item.quantity, item.product.currency) }}
                </p>
              </div>
            </div>
          </div>

          <!-- Order Summary -->
          <div class="border-t border-border pt-4">
            <div class="space-y-2">
              <div class="flex justify-between text-sm">
                <span class="text-muted-foreground">Subtotal</span>
                <span class="text-foreground">{{ formatPrice(orderSubtotal, checkoutCart.currency) }}</span>
              </div>
              <div class="flex justify-between text-sm">
                <span class="text-muted-foreground">Shipping</span>
                <span class="text-foreground">
                  {{ selectedShippingZone ? formatPrice(selectedShippingZone.cost, checkoutCart.currency) : 'Select zone' }}
                </span>
              </div>
              <div class="flex justify-between text-lg font-semibold border-t border-border pt-2">
                <span>Total</span>
                <span class="text-green-600">{{ formatPrice(orderTotal, checkoutCart.currency) }}</span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Shipping Information -->
      <Card v-if="!orderConfirmed">
        <CardHeader>
          <CardTitle>Shipping Information</CardTitle>
          <CardDescription>Select your shipping zone</CardDescription>
        </CardHeader>
        <CardContent>
          <!-- Shipping Zones -->
          <div v-if="availableShippingZones.length > 0" class="space-y-3">
            <div 
              v-for="zone in availableShippingZones"
              :key="zone.id"
              @click="selectShippingZone(zone)"
              :class="[
                'p-4 border rounded-lg cursor-pointer transition-colors',
                selectedShippingZone?.id === zone.id 
                  ? 'border-primary bg-primary/10' 
                  : 'border-border hover:border-primary/50'
              ]"
            >
              <div class="flex justify-between items-center">
                <div>
                  <h3 class="font-medium text-foreground">{{ zone.name }}</h3>
                  <p class="text-sm text-muted-foreground">
                    {{ zone.countries?.join(', ') || 'Available' }}
                    <span v-if="!zone.requiresPhysicalShipping" class="ml-2 text-blue-600">
                      • No shipping required
                    </span>
                  </p>
                  <p v-if="zone.description" class="text-xs text-muted-foreground mt-1">
                    {{ zone.description }}
                  </p>
                </div>
                <div class="text-right">
                  <p class="font-semibold text-foreground">
                    {{ formatPrice(zone.cost, checkoutCart.currency) }}
                  </p>
                  <p class="text-xs text-muted-foreground">shipping</p>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="text-center py-6">
            <p class="text-muted-foreground">This merchant hasn't configured shipping zones yet.</p>
            <p class="text-sm text-muted-foreground">Please contact the merchant for shipping information.</p>
          </div>

          <!-- Confirm Order Button -->
          <div class="mt-6">
            <Button 
              @click="confirmOrder"
              :disabled="availableShippingZones.length > 0 && !selectedShippingZone"
              class="w-full"
              size="lg"
            >
              Confirm Order
            </Button>
          </div>
        </CardContent>
      </Card>

      <!-- Contact & Payment Information -->
      <Card v-if="orderConfirmed">
        <CardHeader>
          <CardTitle>Contact & Payment Information</CardTitle>
          <CardDescription>Provide your details for order processing</CardDescription>
        </CardHeader>
        <CardContent class="space-y-6">
          <!-- Contact Form -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <Label for="email">Email (optional)</Label>
              <Input 
                id="email"
                v-model="contactData.email"
                type="email"
                placeholder="your@email.com"
              />
              <p class="text-xs text-muted-foreground mt-1">Merchant may not use email</p>
            </div>
            
            <div>
              <Label for="npub">Alternative Npub (optional)</Label>
              <Input 
                id="npub"
                v-model="contactData.npub"
                placeholder="npub..."
              />
              <p class="text-xs text-muted-foreground mt-1">Different Npub for communication</p>
            </div>
          </div>

          <div>
            <Label for="address">
              {{ selectedShippingZone?.requiresPhysicalShipping !== false ? 'Shipping Address' : 'Contact Address (optional)' }}
            </Label>
            <Textarea 
              id="address"
              v-model="contactData.address"
              :placeholder="selectedShippingZone?.requiresPhysicalShipping !== false 
                ? 'Full shipping address...' 
                : 'Contact address (optional)...'"
              rows="3"
            />
            <p class="text-xs text-muted-foreground mt-1">
              {{ selectedShippingZone?.requiresPhysicalShipping !== false 
                ? 'Required for physical delivery' 
                : 'Optional for digital items or pickup' }}
            </p>
          </div>

          <div>
            <Label for="message">Message to Merchant (optional)</Label>
            <Textarea 
              id="message"
              v-model="contactData.message"
              placeholder="Any special instructions or notes..."
              rows="3"
            />
          </div>

          <!-- Payment Method Selection -->
          <div>
            <Label>Payment Method</Label>
            <div class="flex gap-3 mt-2">
              <div 
                v-for="method in paymentMethods"
                :key="method.value"
                @click="paymentMethod = method.value"
                :class="[
                  'p-3 border rounded-lg cursor-pointer text-center flex-1 transition-colors',
                  paymentMethod === method.value 
                    ? 'border-primary bg-primary/10' 
                    : 'border-border hover:border-primary/50'
                ]"
              >
                <p class="font-medium">{{ method.label }}</p>
              </div>
            </div>
          </div>

          <!-- Place Order Button -->
          <div class="pt-4 border-t border-border">
            <Button 
              @click="placeOrder"
              :disabled="isPlacingOrder || (selectedShippingZone?.requiresPhysicalShipping !== false && !contactData.address)"
              class="w-full"
              size="lg"
            >
              <span v-if="isPlacingOrder" class="animate-spin mr-2">⚡</span>
              Place Order - {{ formatPrice(orderTotal, checkoutCart.currency) }}
            </Button>
            <p v-if="selectedShippingZone?.requiresPhysicalShipping !== false && !contactData.address" 
               class="text-xs text-destructive mt-2 text-center">
              Shipping address is required for physical delivery
            </p>
          </div>
        </CardContent>
      </Card>

      <!-- Order Placed Success -->
      <Card v-if="orderPlaced">
        <CardContent class="text-center py-8">
          <CheckCircle class="w-16 h-16 text-green-600 mx-auto mb-4" />
          <h3 class="text-xl font-semibold text-foreground mb-2">Order Placed Successfully!</h3>
          <p class="text-muted-foreground mb-6">Your order has been sent to the merchant.</p>
          <div class="flex gap-3 justify-center">
            <Button @click="$router.push('/market')" variant="outline">
              Continue Shopping
            </Button>
            <Button @click="$router.push('/market/dashboard')" variant="default">
              View Orders
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMarketStore } from '@/stores/market'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import { 
  Card, 
  CardHeader, 
  CardTitle, 
  CardDescription, 
  CardContent 
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { 
  Package, 
  CheckCircle 
} from 'lucide-vue-next'

const route = useRoute()
const router = useRouter()
const marketStore = useMarketStore()
const authService = injectService(SERVICE_TOKENS.AUTH_SERVICE) as any

// State
const isLoading = ref(true)
const error = ref<string | null>(null)
const orderConfirmed = ref(false)
const orderPlaced = ref(false)
const isPlacingOrder = ref(false)
const selectedShippingZone = ref<any>(null)
const paymentMethod = ref('ln')

// Form data
const contactData = ref({
  email: '',
  npub: '',
  address: '',
  message: ''
})

// Payment methods
const paymentMethods = [
  { label: 'Lightning Network', value: 'ln' },
  { label: 'BTC Onchain', value: 'btc' },
  { label: 'Cashu', value: 'cashu' }
]

// Computed
const stallId = computed(() => route.params.stallId as string)
const checkoutCart = computed(() => marketStore.checkoutCart)

const stallName = computed(() => {
  if (!checkoutCart.value) return ''
  const stall = marketStore.stalls.find(s => s.id === checkoutCart.value?.id)
  return stall?.name || 'Unknown Stall'
})

const currentStall = computed(() => {
  if (!checkoutCart.value) return null
  return marketStore.stalls.find(s => s.id === checkoutCart.value?.id)
})

const orderSubtotal = computed(() => {
  if (!checkoutCart.value?.products) return 0
  return checkoutCart.value.products.reduce((total, item) => 
    total + (item.product.price * item.quantity), 0
  )
})

const orderTotal = computed(() => {
  const subtotal = orderSubtotal.value
  const shipping = selectedShippingZone.value?.cost || 0
  return subtotal + shipping
})

// Get shipping zones from the current stall
const availableShippingZones = computed(() => {
  if (!currentStall.value) return []
  
  // Check if stall has shipping_zones (LNbits format) or shipping (nostr-market-app format)
  const zones = currentStall.value.shipping_zones || currentStall.value.shipping || []
  
  // Ensure zones have required properties and determine shipping requirements
  return zones.map(zone => {
    const zoneName = zone.name || 'Shipping Zone'
    const lowerName = zoneName.toLowerCase()
    
    // Determine if this zone requires physical shipping
    const requiresPhysicalShipping = zone.requiresPhysicalShipping !== false && 
      !lowerName.includes('digital') && 
      !lowerName.includes('pickup') && 
      !lowerName.includes('download') && 
      zone.cost > 0 // Free usually means digital or pickup
    
    return {
      id: zone.id || zoneName.toLowerCase().replace(/\s+/g, '-'),
      name: zoneName,
      cost: Number(zone.cost) || 0,
      countries: zone.countries || [],
      currency: zone.currency || currentStall.value?.currency || 'sats',
      requiresPhysicalShipping,
      description: zone.description
    }
  })
})

// Methods
const selectShippingZone = (zone: any) => {
  selectedShippingZone.value = zone
}

const confirmOrder = () => {
  // Allow proceeding if no shipping zones are available (e.g., for digital goods)
  if (availableShippingZones.value.length > 0 && !selectedShippingZone.value) {
    error.value = 'Please select a shipping zone'
    return
  }
  orderConfirmed.value = true
}

const placeOrder = async () => {
  // Only require shipping address if selected zone requires physical shipping
  const requiresShippingAddress = selectedShippingZone.value?.requiresPhysicalShipping !== false
  
  if (requiresShippingAddress && !contactData.value.address) {
    error.value = 'Shipping address is required for this delivery method'
    return
  }

  isPlacingOrder.value = true
  error.value = null

  try {
    // Ensure we have the required data
    if (!checkoutCart.value) {
      throw new Error('No checkout cart found')
    }
    if (!currentStall.value) {
      throw new Error('Stall information not available')
    }
    if (!authService.isAuthenticated.value || !authService.user.value?.pubkey) {
      throw new Error('You must be logged in to place an order')
    }

    // Create the order using the market store's order placement functionality
    const orderData = {
      stallId: stallId.value,
      buyerPubkey: authService.user.value?.pubkey || '',
      sellerPubkey: currentStall.value.pubkey,
      status: 'pending' as const,
      items: checkoutCart.value.products.map(item => ({
        productId: item.product.id,
        productName: item.product.name,
        quantity: item.quantity,
        price: item.product.price,
        currency: item.product.currency
      })),
      contactInfo: {
        address: contactData.value.address || undefined,
        email: contactData.value.email || undefined,
        message: contactData.value.message || undefined,
        npub: contactData.value.npub || undefined
      },
      shippingZone: selectedShippingZone.value || {
        id: 'default',
        name: 'Default Shipping',
        cost: 0,
        currency: checkoutCart.value.currency,
        requiresPhysicalShipping: false
      },
      paymentMethod: paymentMethod.value === 'ln' ? 'lightning' as const : 'btc_onchain' as const,
      subtotal: orderSubtotal.value,
      shippingCost: selectedShippingZone.value?.cost || 0,
      total: orderTotal.value,
      currency: checkoutCart.value.currency,
      cartId: checkoutCart.value.id
    }

    console.log('Creating order:', orderData)
    
    // Create and place the order via the market store
    const order = await marketStore.createAndPlaceOrder(orderData)
    
    console.log('Order placed successfully:', order)
    orderPlaced.value = true
    
  } catch (err) {
    console.error('Failed to place order:', err)
    error.value = err instanceof Error ? err.message : 'Failed to place order'
  } finally {
    isPlacingOrder.value = false
  }
}

const formatPrice = (price: number, currency: string) => {
  if (currency === 'sats' || currency === 'sat') {
    return `${price.toLocaleString()} sats`
  }
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency.toUpperCase()
  }).format(price)
}

// Initialize
onMounted(() => {
  // Check if we have a checkout cart for this stall
  const cart = marketStore.checkoutCart
  if (!cart || cart.id !== stallId.value) {
    error.value = 'No checkout data found for this stall'
  }
  
  // Auto-select shipping zone if there's only one
  if (availableShippingZones.value.length === 1) {
    selectedShippingZone.value = availableShippingZones.value[0]
  }
  
  isLoading.value = false
})
</script>