'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { 
  Package, 
  Search, 
  CheckCircle, 
  XCircle, 
  Clock, 
  AlertCircle,
  Mail,
  Truck,
  MapPin,
  Calendar
} from 'lucide-react'

interface Order {
  id: string
  customerId: string | null
  customerEmail: string
  items: OrderItem[]
  totalAmount: number
  currency: string
  status: 'pending' | 'paid' | 'fulfilled' | 'cancelled' | 'refunded'
  paymentIntentId: string | null
  stripeSessionId: string | null
  createdAt: string
  updatedAt: string
  shippingAddress?: {
    name: string
    address: string
    city: string
    state: string
    zipCode: string
    country: string
  }
  trackingNumber?: string
  estimatedDelivery?: string
}

interface OrderItem {
  productId: string
  productName: string
  price: number
  quantity: number
  priceId: string
}

export function OrderTracking() {
  const [orderId, setOrderId] = useState('')
  const [order, setOrder] = useState<Order | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [isSearching, setIsSearching] = useState(false)
  const [showSuccess, setShowSuccess] = useState(false)

  // Track an order
  const trackOrder = async () => {
    if (!orderId.trim()) {
      setError('Please enter an order ID')
      return
    }

    setIsSearching(true)
    setLoading(true)
    setError(null)
    setOrder(null)

    try {
      // In a real application, you would call your API to fetch the order
      // For demo purposes, we'll simulate API call with timeout
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // Simulate API response
      const mockOrder: Order = {
        id: orderId,
        customerId: null,
        customerEmail: 'customer@example.com',
        items: [
          {
            productId: 'prod_123',
            productName: 'Vending Machine - SEAGA HY900',
            price: 2499.99,
            quantity: 1,
            priceId: 'price_123'
          },
          {
            productId: 'prod_456',
            productName: 'Vending Machine Stand',
            price: 299.99,
            quantity: 1,
            priceId: 'price_456'
          }
        ],
        totalAmount: 2799.98,
        currency: 'usd',
        status: 'paid',
        paymentIntentId: 'pi_123',
        stripeSessionId: 'cs_123',
        createdAt: '2024-01-15T10:30:00Z',
        updatedAt: '2024-01-16T14:20:00Z',
        shippingAddress: {
          name: 'John Doe',
          address: '123 Main Street',
          city: 'Salt Lake City',
          state: 'UT',
          zipCode: '84101',
          country: 'USA'
        },
        trackingNumber: '1Z999AA1234567890',
        estimatedDelivery: '2024-01-20'
      }

      setOrder(mockOrder)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to find order')
    } finally {
      setLoading(false)
      setIsSearching(false)
    }
  }

  // Handle Enter key press
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      trackOrder()
    }
  }

  // Format date
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // Get status badge variant
  const getStatusVariant = (status: Order['status']) => {
    switch (status) {
      case 'pending':
        return 'secondary'
      case 'paid':
        return 'default'
      case 'fulfilled':
        return 'default'
      case 'cancelled':
        return 'destructive'
      case 'refunded':
        return 'destructive'
      default:
        return 'secondary'
    }
  }

  // Get status icon
  const getStatusIcon = (status: Order['status']) => {
    switch (status) {
      case 'pending':
        return <Clock className="h-4 w-4" />
      case 'paid':
        return <CheckCircle className="h-4 w-4" />
      case 'fulfilled':
        return <Truck className="h-4 w-4" />
      case 'cancelled':
        return <XCircle className="h-4 w-4" />
      case 'refunded':
        return <AlertCircle className="h-4 w-4" />
      default:
        return null
    }
  }

  // Get status message
  const getStatusMessage = (status: Order['status']) => {
    switch (status) {
      case 'pending':
        return 'Order is being processed'
      case 'paid':
        return 'Payment received. Preparing for shipment'
      case 'fulfilled':
        return 'Order has been shipped'
      case 'cancelled':
        return 'Order was cancelled'
      case 'refunded':
        return 'Order has been refunded'
      default:
        return 'Unknown status'
    }
  }

  // Clear order after successful display
  useEffect(() => {
    if (order) {
      const timer = setTimeout(() => {
        setShowSuccess(true)
      }, 2000)
      
      return () => clearTimeout(timer)
    }
  }, [order])

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="space-y-6">
        <div className="text-center">
          <h1 className="text-3xl font-bold tracking-tight">Track Your Order</h1>
          <p className="text-muted-foreground mt-2">
            Enter your order ID to track shipment status and delivery information
          </p>
        </div>

        {/* Search Form */}
        <Card>
          <CardHeader>
            <CardTitle>Find Your Order</CardTitle>
            <CardDescription>
              Enter your order ID to track your package
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex gap-2">
              <Input
                placeholder="Enter order ID (e.g., ORD-1234567)"
                value={orderId}
                onChange={(e) => setOrderId(e.target.value)}
                onKeyPress={handleKeyPress}
                className="flex-1"
              />
              <Button onClick={trackOrder} disabled={isSearching}>
                {isSearching ? (
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                ) : (
                  <Search className="h-4 w-4" />
                )}
                {isSearching ? 'Searching...' : 'Track'}
              </Button>
            </div>
            
            {error && (
              <Alert variant="destructive" className="mt-4">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}

            {showSuccess && (
              <Alert className="mt-4">
                <CheckCircle className="h-4 w-4" />
                <AlertDescription>
                  Order found successfully! Scroll down for tracking details.
                </AlertDescription>
              </Alert>
            )}
          </CardContent>
        </Card>

        {/* Order Details */}
        {order && (
          <div className="space-y-6">
            {/* Order Status */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  <span>Order Status</span>
                  <Badge variant={getStatusVariant(order.status)} className="flex items-center gap-1">
                    {getStatusIcon(order.status)}
                    {order.status.charAt(0).toUpperCase() + order.status.slice(1)}
                  </Badge>
                </CardTitle>
                <CardDescription>
                  Order ID: {order.id} • Placed on {formatDate(order.createdAt)}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <p className="text-lg">{getStatusMessage(order.status)}</p>
                
                {order.status === 'fulfilled' && order.trackingNumber && (
                  <div className="mt-4 p-4 bg-muted rounded-lg">
                    <div className="flex items-center gap-2 mb-2">
                      <Package className="h-5 w-5 text-muted-foreground" />
                      <span className="font-medium">Tracking Information</span>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <div className="text-sm text-muted-foreground">Tracking Number</div>
                        <div className="font-mono">{order.trackingNumber}</div>
                      </div>
                      <div>
                        <div className="text-sm text-muted-foreground">Estimated Delivery</div>
                        <div>{new Date(order.estimatedDelivery!).toLocaleDateString()}</div>
                      </div>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* Customer Information */}
            <Card>
              <CardHeader>
                <CardTitle>Customer Information</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <h4 className="font-medium mb-3">Contact Information</h4>
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        <Mail className="h-4 w-4 text-muted-foreground" />
                        <span>{order.customerEmail}</span>
                      </div>
                    </div>
                  </div>
                  
                  {order.shippingAddress && (
                    <div>
                      <h4 className="font-medium mb-3">Shipping Address</h4>
                      <div className="space-y-2">
                        <div className="flex items-start gap-2">
                          <MapPin className="h-4 w-4 text-muted-foreground mt-0.5" />
                          <div>
                            <div className="font-medium">{order.shippingAddress.name}</div>
                            <div>{order.shippingAddress.address}</div>
                            <div>
                              {order.shippingAddress.city}, {order.shippingAddress.state} {order.shippingAddress.zipCode}
                            </div>
                            <div>{order.shippingAddress.country}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* Order Items */}
            <Card>
              <CardHeader>
                <CardTitle>Order Items</CardTitle>
                <CardDescription>
                  {order.items.length} item{order.items.length !== 1 ? 's' : ''} • Total ${order.totalAmount.toFixed(2)}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {order.items.map((item, index) => (
                    <div key={index} className="flex items-center justify-between p-4 border rounded-lg">
                      <div className="flex items-center gap-4">
                        <div className="w-16 h-16 rounded-md bg-muted flex items-center justify-center">
                          <Package className="h-8 w-8 text-muted-foreground" />
                        </div>
                        <div>
                          <h4 className="font-medium">{item.productName}</h4>
                          <p className="text-sm text-muted-foreground">
                            ${item.price.toFixed(2)} • Qty: {item.quantity}
                          </p>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="font-medium">${(item.price * item.quantity).toFixed(2)}</div>
                      </div>
                    </div>
                  ))}
                </div>
                
                <div className="mt-6 pt-6 border-t">
                  <div className="flex justify-between items-center text-lg">
                    <span className="font-medium">Total:</span>
                    <div className="flex items-center gap-1">
                      <span>${order.totalAmount.toFixed(2)}</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Timeline */}
            {order.status !== 'cancelled' && order.status !== 'refunded' && (
              <Card>
                <CardHeader>
                  <CardTitle>Order Timeline</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className="flex gap-4">
                      <div className="flex flex-col items-center">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                          order.status !== 'pending' ? 'bg-primary text-primary-foreground' : 'bg-muted'
                        }`}>
                          <Calendar className="h-4 w-4" />
                        </div>
                        <div className="w-0.5 h-16 bg-border"></div>
                      </div>
                      <div>
                        <h4 className="font-medium">Order Placed</h4>
                        <p className="text-sm text-muted-foreground">
                          {formatDate(order.createdAt)}
                        </p>
                      </div>
                    </div>
                    
                    <div className="flex gap-4">
                      <div className="flex flex-col items-center">
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                          order.status !== 'pending' ? 'bg-primary text-primary-foreground' : 'bg-muted'
                        }`}>
                          <CheckCircle className="h-4 w-4" />
                        </div>
                        <div className="w-0.5 h-16 bg-border"></div>
                      </div>
                      <div>
                        <h4 className="font-medium">Payment Confirmed</h4>
                        <p className="text-sm text-muted-foreground">
                          {formatDate(order.updatedAt)}
                        </p>
                      </div>
                    </div>
                    
                    {order.status === 'fulfilled' && (
                      <div className="flex gap-4">
                        <div className="flex flex-col items-center">
                          <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                            order.status === 'fulfilled' ? 'bg-primary text-primary-foreground' : 'bg-muted'
                          }`}>
                            <Truck className="h-4 w-4" />
                          </div>
                        </div>
                        <div>
                          <h4 className="font-medium">Order Shipped</h4>
                          <p className="text-sm text-muted-foreground">
                            Tracking: {order.trackingNumber}
                          </p>
                          <p className="text-sm text-muted-foreground">
                            Estimated Delivery: {new Date(order.estimatedDelivery!).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        )}

        {!order && !loading && (
          <Card>
            <CardContent className="py-12 text-center">
              <Package className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-medium mb-2">No order found</h3>
              <p className="text-muted-foreground">
                Enter your order ID above to track your shipment status
              </p>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  )
}
