<template>
  <div class="container mx-auto px-4 py-8">
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-3xl font-bold text-foreground">Order History</h1>
      <p class="text-muted-foreground mt-2">
        View and track all your market orders
      </p>
      <!-- Order Events Status -->
      <div class="mt-3 flex items-center gap-2">
        <div class="flex items-center gap-2">
          <div 
            class="w-2 h-2 rounded-full"
            :class="orderEvents.isSubscribed ? 'bg-green-500' : 'bg-yellow-500'"
          ></div>
          <span class="text-sm text-muted-foreground">
            {{ orderEvents.isSubscribed ? 'Listening for order updates' : 'Connecting to order events...' }}
          </span>
        </div>
        <div v-if="orderEvents.lastEventTimestamp.value > 0" class="text-xs text-muted-foreground">
          Last update: {{ formatDate(orderEvents.lastEventTimestamp.value) }}
        </div>
      </div>
    </div>

    <!-- Filters and Stats -->
    <div class="mb-6 flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
      <!-- Order Stats -->
      <div class="flex gap-4 text-sm">
        <div class="flex items-center gap-2">
          <span class="text-muted-foreground">Total Orders:</span>
          <Badge variant="secondary">{{ totalOrders }}</Badge>
        </div>
        <div class="flex items-center gap-2">
          <span class="text-muted-foreground">Pending:</span>
          <Badge variant="outline" class="text-yellow-600">{{ pendingOrders }}</Badge>
        </div>
        <div class="flex items-center gap-2">
          <span class="text-muted-foreground">Completed:</span>
          <Badge variant="outline" class="text-green-600">{{ completedOrders }}</Badge>
        </div>
      </div>

      <!-- Filter Controls -->
      <div class="flex gap-2">
        <select v-model="statusFilter" class="w-40 px-3 py-2 border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring bg-background text-foreground">
          <option value="">All Statuses</option>
          <option value="pending">Pending</option>
          <option value="paid">Paid</option>
          <option value="processing">Processing</option>
          <option value="shipped">Shipped</option>
          <option value="delivered">Delivered</option>
          <option value="cancelled">Cancelled</option>
        </select>
        <select v-model="sortBy" class="w-40 px-3 py-2 border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring bg-background text-foreground">
          <option value="createdAt">Date Created</option>
          <option value="total">Order Total</option>
          <option value="status">Status</option>
        </select>
      </div>
    </div>

    <!-- Orders List -->
    <div v-if="filteredOrders.length > 0" class="space-y-4">
      <div
        v-for="order in sortedOrders"
        :key="order.id"
        class="bg-card border rounded-lg p-6 hover:shadow-md transition-shadow"
      >
        <!-- Order Header -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center">
              <Package class="w-5 h-5 text-primary" />
            </div>
            <div>
              <h3 class="font-semibold text-foreground">Order #{{ order.id.slice(-8) }}</h3>
              <p class="text-sm text-muted-foreground">
                {{ formatDate(order.createdAt) }}
              </p>
              <!-- Nostr Status -->
              <div v-if="order.sentViaNostr !== undefined" class="flex items-center gap-2 mt-1">
                <div v-if="order.sentViaNostr" class="flex items-center gap-1 text-xs text-green-600">
                  <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                  Sent via Nostr
                </div>
                <div v-else class="flex items-center gap-1 text-xs text-red-600">
                  <div class="w-2 h-2 bg-red-500 rounded-full"></div>
                  Nostr failed
                </div>
              </div>
            </div>
          </div>
          
          <div class="flex items-center gap-3">
            <Badge :variant="getStatusVariant(order.status)">
              {{ formatStatus(order.status) }}
            </Badge>
            <!-- Payment Status Indicator -->
            <div v-if="order.lightningInvoice" class="flex items-center gap-2">
              <Badge 
                :variant="order.paymentStatus === 'paid' ? 'default' : 'secondary'"
                class="text-xs"
              >
                <div class="flex items-center gap-1">
                  <div v-if="order.paymentStatus === 'paid'" class="w-2 h-2 bg-green-500 rounded-full"></div>
                  <div v-else class="w-2 h-2 bg-yellow-500 rounded-full animate-pulse"></div>
                  {{ order.paymentStatus === 'paid' ? 'Paid' : 'Payment Pending' }}
                </div>
              </Badge>
            </div>
            <div class="text-right">
              <p class="text-lg font-semibold text-foreground">
                {{ formatPrice(order.total, order.currency) }}
              </p>
              <p class="text-sm text-muted-foreground">{{ order.currency.toUpperCase() }}</p>
            </div>
          </div>
        </div>

        <!-- Order Details -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
          <!-- Items -->
          <div>
            <h4 class="font-medium text-foreground mb-2">Items</h4>
            <div class="space-y-2">
              <div
                v-for="item in order.items"
                :key="item.productId"
                class="flex justify-between text-sm"
              >
                <span class="text-muted-foreground">
                  {{ item.productName }} × {{ item.quantity }}
                </span>
                <span class="font-medium">
                  {{ formatPrice(item.price * item.quantity, item.currency) }}
                </span>
              </div>
            </div>
          </div>

          <!-- Order Info -->
          <div>
            <h4 class="font-medium text-foreground mb-2">Order Details</h4>
            <div class="space-y-2 text-sm">
              <div class="flex justify-between">
                <span class="text-muted-foreground">Subtotal:</span>
                <span>{{ formatPrice(order.subtotal, order.currency) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-muted-foreground">Shipping:</span>
                <span>{{ formatPrice(order.shippingCost, order.currency) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-muted-foreground">Payment Method:</span>
                <span class="capitalize">{{ order.paymentMethod.replace('_', ' ') }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Contact & Shipping -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
          <!-- Contact Info -->
          <div v-if="order.contactInfo.email || order.contactInfo.message">
            <h4 class="font-medium text-foreground mb-2">Contact Information</h4>
            <div class="space-y-1 text-sm text-muted-foreground">
              <p v-if="order.contactInfo.email">
                <span class="font-medium">Email:</span> {{ order.contactInfo.email }}
              </p>
              <p v-if="order.contactInfo.message">
                <span class="font-medium">Message:</span> {{ order.contactInfo.message }}
              </p>
            </div>
          </div>

          <!-- Shipping Info -->
          <div v-if="order.shippingZone">
            <h4 class="font-medium text-foreground mb-2">Shipping</h4>
            <div class="space-y-1 text-sm text-muted-foreground">
              <p>
                <span class="font-medium">Zone:</span> {{ order.shippingZone.name }}
              </p>
              <p v-if="order.shippingZone.estimatedDays">
                <span class="font-medium">Est. Delivery:</span> {{ order.shippingZone.estimatedDays }}
              </p>
              <p v-if="order.contactInfo.address">
                <span class="font-medium">Address:</span> {{ order.contactInfo.address }}
              </p>
            </div>
          </div>
        </div>

        <!-- Nostr Event Details -->
        <div v-if="order.sentViaNostr !== undefined" class="mb-4 p-4 bg-muted rounded-lg">
          <h4 class="font-medium text-foreground mb-2">Nostr Network Status</h4>
          <div class="space-y-2 text-sm">
            <div v-if="order.sentViaNostr" class="space-y-1">
              <p v-if="order.nostrEventId" class="text-muted-foreground">
                <span class="font-medium">Event ID:</span> 
                <code class="bg-background px-2 py-1 rounded text-xs">{{ order.nostrEventId.slice(0, 16) }}...</code>
              </p>
              <p v-if="order.nostrEventSig" class="text-muted-foreground">
                <span class="font-medium">Signature:</span> 
                <code class="bg-background px-2 py-1 rounded text-xs">{{ order.nostrEventSig.slice(0, 16) }}...</code>
              </p>
              <p class="text-green-600">
                <span class="font-medium">✓</span> Order successfully transmitted to merchant via Nostr network
              </p>
            </div>
            <div v-else class="space-y-1">
              <p v-if="order.nostrError" class="text-red-600">
                <span class="font-medium">✗</span> Failed to send via Nostr: {{ order.nostrError }}
              </p>
              <p class="text-yellow-600">
                <span class="font-medium">⚠</span> Order stored locally only - merchant may not receive it
              </p>
            </div>
          </div>
        </div>

        <!-- Payment Status & Actions -->
        <div v-if="order.status === 'pending'" class="mb-4 p-4 bg-muted/50 border border-border rounded-lg">
          <div class="flex-1">
            <h4 class="font-medium text-foreground mb-2">Payment Required</h4>
            <div v-if="order.lightningInvoice" class="space-y-2">
              <p class="text-sm text-muted-foreground">
                <span class="font-medium text-green-600">✓</span> Lightning invoice received from merchant
              </p>
              <p class="text-sm text-muted-foreground">
                Amount: <span class="font-medium text-foreground">{{ formatPrice(order.total, order.currency) }}</span>
              </p>
              <p class="text-sm text-muted-foreground">
                Status: <span class="font-medium text-foreground">{{ order.paymentStatus === 'paid' ? 'Paid' : 'Pending Payment' }}</span>
              </p>
            </div>
            <div v-else class="space-y-2">
              <p class="text-sm text-muted-foreground">
                <span class="font-medium text-amber-600">⏳</span> Waiting for merchant to generate payment invoice
              </p>
              <p class="text-sm text-muted-foreground">
                The merchant will send you a Lightning invoice via Nostr once they process your order
              </p>
            </div>
          </div>
        </div>

        <!-- Actions -->
        <div class="flex justify-end gap-2 pt-4 border-t border-border">
          <Button
            v-if="order.status === 'pending'"
            variant="outline"
            size="sm"
            @click="cancelOrder(order.id)"
          >
            Cancel Order
          </Button>
          <Button
            v-if="order.lightningInvoice"
            variant="default"
            size="sm"
            @click="togglePaymentDisplay(order.id)"
          >
            <Wallet class="w-4 h-4 mr-2" />
            {{ expandedPayments.has(order.id) ? 'Hide' : 'Show' }} Payment
          </Button>
          <Button
            variant="outline"
            size="sm"
            @click="copyOrderId(order.id)"
          >
            Copy Order ID
          </Button>
        </div>

        <!-- Payment Display (Expandable) -->
        <div v-if="expandedPayments.has(order.id) && order.lightningInvoice" class="mt-4 pt-4 border-t border-border">
          <PaymentDisplay 
            :order-id="order.id" 
          />
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-else class="text-center py-12">
      <div class="w-16 h-16 bg-muted rounded-full flex items-center justify-center mx-auto mb-4">
        <Package class="w-8 h-8 text-muted-foreground/50" />
      </div>
      <h3 class="text-lg font-medium text-foreground mb-2">No orders yet</h3>
      <p class="text-muted-foreground mb-6">
        Start shopping in the market to see your order history here
      </p>
      <Button @click="router.push('/market')" variant="default">
        Browse Market
      </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMarketStore } from '@/stores/market'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Package, Wallet } from 'lucide-vue-next'
import type { OrderStatus } from '@/stores/market'
import PaymentDisplay from '@/components/market/PaymentDisplay.vue'
import { useOrderEvents } from '@/composables/useOrderEvents'

const router = useRouter()
const marketStore = useMarketStore()
const orderEvents = useOrderEvents()

// Local state
const statusFilter = ref('')
const sortBy = ref('createdAt')
const expandedPayments = ref(new Set<string>())

// Computed properties
const allOrders = computed(() => Object.values(marketStore.orders))

const filteredOrders = computed(() => {
  if (!statusFilter.value) return allOrders.value
  return allOrders.value.filter(order => order.status === statusFilter.value)
})

const sortedOrders = computed(() => {
  const orders = [...filteredOrders.value]
  
  switch (sortBy.value) {
    case 'total':
      return orders.sort((a, b) => b.total - a.total)
    case 'status':
      return orders.sort((a, b) => a.status.localeCompare(b.status))
    case 'createdAt':
    default:
      return orders.sort((a, b) => b.createdAt - a.createdAt)
  }
})

const totalOrders = computed(() => allOrders.value.length)
const pendingOrders = computed(() => allOrders.value.filter(o => o.status === 'pending').length)
const completedOrders = computed(() => 
  allOrders.value.filter(o => ['delivered', 'shipped'].includes(o.status)).length
)

// Methods
const formatDate = (timestamp: number) => {
  return new Date(timestamp * 1000).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatStatus = (status: OrderStatus) => {
  const statusMap: Record<OrderStatus, string> = {
    pending: 'Pending',
    paid: 'Paid',
    processing: 'Processing',
    shipped: 'Shipped',
    delivered: 'Delivered',
    cancelled: 'Cancelled'
  }
  return statusMap[status] || status
}

const getStatusVariant = (status: OrderStatus) => {
  const variantMap: Record<OrderStatus, 'default' | 'secondary' | 'outline' | 'destructive'> = {
    pending: 'outline',
    paid: 'secondary',
    processing: 'secondary',
    shipped: 'default',
    delivered: 'default',
    cancelled: 'destructive'
  }
  return variantMap[status] || 'outline'
}

const formatPrice = (price: number, currency: string) => {
  return marketStore.formatPrice(price, currency)
}

const cancelOrder = (orderId: string) => {
  // TODO: Implement order cancellation
  console.log('Cancelling order:', orderId)
}

// const viewPayment = (_order: any) => {
//   // TODO: Implement payment viewing
//   console.log('Viewing payment for order:', _order.id)
// }

const copyOrderId = async (orderId: string) => {
  try {
    await navigator.clipboard.writeText(orderId)
    // TODO: Show toast notification
    console.log('Order ID copied to clipboard')
  } catch (err) {
    console.error('Failed to copy order ID:', err)
  }
}

const togglePaymentDisplay = (orderId: string) => {
  if (expandedPayments.value.has(orderId)) {
    expandedPayments.value.delete(orderId)
  } else {
    expandedPayments.value.add(orderId)
  }
}

// Load orders on mount
onMounted(() => {
  // Orders are already loaded in the market store
  console.log('Order History page loaded with', allOrders.value.length, 'orders')
  
  // Start listening for order events if not already listening
  if (!orderEvents.isSubscribed.value) {
    orderEvents.initialize()
  }
})
</script>
