import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import { api } from '@/lib/api/client';
import { toast } from 'sonner';

interface OrderItem {
  id: number;
  name: string;
  quantity: number;
  total: string;
  image?: string;
}

interface ShippingLine {
  id: number;
  method_title: string;
  method_id: string;
  total: string;
}

interface Order {
  id: number;
  order_number: string;
  date: string;
  status: string;
  total: string;
  subtotal: string;
  shipping_total: string;
  tax_total: string;
  items: OrderItem[];
  billing: any;
  shipping: any;
  payment_method_title: string;
  needs_shipping: boolean;
  shipping_lines?: ShippingLine[];
  // Tracking info (may be added by shipping plugins)
  tracking_number?: string;
  tracking_url?: string;
  meta_data?: Array<{ key: string; value: string }>;
}

export default function OrderDetails() {
  const { orderId } = useParams();
  const [loading, setLoading] = useState(true);
  const [order, setOrder] = useState<Order | null>(null);

  useEffect(() => {
    if (orderId) {
      loadOrder();
    }
  }, [orderId]);

  const loadOrder = async () => {
    try {
      const data = await api.get<Order>(`/account/orders/${orderId}`);
      setOrder(data);
    } catch (error) {
      console.error('Load order error:', error);
      toast.error('Failed to load order details');
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'completed': 'bg-green-100 text-green-800',
      'processing': 'bg-blue-100 text-blue-800',
      'pending': 'bg-yellow-100 text-yellow-800',
      'on-hold': 'bg-orange-100 text-orange-800',
      'cancelled': 'bg-red-100 text-red-800',
      'refunded': 'bg-gray-100 text-gray-800',
      'failed': 'bg-red-100 text-red-800',
    };
    return colors[status] || 'bg-gray-100 text-gray-800';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-gray-600">Loading order...</div>
      </div>
    );
  }

  if (!order) {
    return (
      <div>
        <Link to="/my-account/orders" className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
          <ArrowLeft className="w-4 h-4" />
          Back to Orders
        </Link>
        <div className="text-center py-12">
          <p className="text-gray-600">Order not found</p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <Link to="/my-account/orders" className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4">
        <ArrowLeft className="w-4 h-4" />
        Back to Orders
      </Link>

      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Order #{order.order_number}</h1>
        <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(order.status)}`}>
          {order.status.replace('-', ' ').toUpperCase()}
        </span>
      </div>

      <div className="text-sm text-gray-600 mb-6">
        Placed on {formatDate(order.date)}
      </div>

      {/* Order Items */}
      <div className="border rounded-lg mb-6">
        <div className="bg-gray-50 px-4 py-3 border-b">
          <h2 className="text-base font-medium">Order Items</h2>
        </div>
        <div className="divide-y">
          {(order.items || []).map((item) => (
            <div key={item.id} className="p-4 flex items-center gap-4">
              {item.image && (
                <img src={item.image} alt={item.name} className="w-16 h-16 object-cover rounded" />
              )}
              <div className="flex-1">
                <h3 className="font-medium">{item.name}</h3>
                <p className="text-sm text-gray-600">Quantity: {item.quantity}</p>
              </div>
              <div className="font-semibold">{item.total}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Order Summary */}
      <div className="border rounded-lg mb-6">
        <div className="bg-gray-50 px-4 py-3 border-b">
          <h2 className="text-base font-medium">Order Summary</h2>
        </div>
        <div className="p-4 space-y-2">
          <div className="flex justify-between text-sm">
            <span className="text-gray-600">Subtotal</span>
            <span>{order.subtotal}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-600">Shipping</span>
            <span>{order.shipping_total}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-600">Tax</span>
            <span>{order.tax_total}</span>
          </div>
          <div className="flex justify-between font-bold text-lg pt-2 border-t">
            <span>Total</span>
            <span>{order.total}</span>
          </div>
        </div>
      </div>

      {/* Addresses */}
      <div className={`grid grid-cols-1 gap-6 ${order.needs_shipping ? 'md:grid-cols-2' : ''}`}>
        <div className="border rounded-lg">
          <div className="bg-gray-50 px-4 py-3 border-b">
            <h2 className="text-base font-medium">Billing Address</h2>
          </div>
          <div className="p-4 text-sm">
            {order.billing && (
              <div className="space-y-1">
                <p className="font-medium">{order.billing.first_name} {order.billing.last_name}</p>
                {order.billing.company && <p>{order.billing.company}</p>}
                <p>{order.billing.address_1}</p>
                {order.billing.address_2 && <p>{order.billing.address_2}</p>}
                <p>{order.billing.city}, {order.billing.state} {order.billing.postcode}</p>
                <p>{order.billing.country}</p>
                {order.billing.email && <p className="pt-2">Email: {order.billing.email}</p>}
                {order.billing.phone && <p>Phone: {order.billing.phone}</p>}
              </div>
            )}
          </div>
        </div>

        {/* Only show shipping address if order needs shipping (not virtual-only) */}
        {order.needs_shipping && (
          <div className="border rounded-lg">
            <div className="bg-gray-50 px-4 py-3 border-b">
              <h2 className="text-base font-medium">Shipping Address</h2>
            </div>
            <div className="p-4 text-sm">
              {order.shipping && (
                <div className="space-y-1">
                  <p className="font-medium">{order.shipping.first_name} {order.shipping.last_name}</p>
                  {order.shipping.company && <p>{order.shipping.company}</p>}
                  <p>{order.shipping.address_1}</p>
                  {order.shipping.address_2 && <p>{order.shipping.address_2}</p>}
                  <p>{order.shipping.city}, {order.shipping.state} {order.shipping.postcode}</p>
                  <p>{order.shipping.country}</p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Payment Method */}
      <div className="mt-6 border rounded-lg">
        <div className="bg-gray-50 px-4 py-3 border-b">
          <h2 className="text-base font-medium">Payment Method</h2>
        </div>
        <div className="p-4 text-sm">
          {order.payment_method_title || 'Not specified'}
        </div>
      </div>

      {/* Shipping Method - only for physical product orders */}
      {order.needs_shipping && order.shipping_lines && order.shipping_lines.length > 0 && (
        <div className="mt-6 border rounded-lg">
          <div className="bg-gray-50 px-4 py-3 border-b">
            <h2 className="text-base font-medium">Shipping Method</h2>
          </div>
          <div className="p-4">
            {order.shipping_lines.map((line) => (
              <div key={line.id} className="flex justify-between text-sm">
                <span>{line.method_title}</span>
                <span className="font-medium">{line.total}</span>
              </div>
            ))}

            {/* AWB Tracking - show for processing or completed orders */}
            {(order.status === 'processing' || order.status === 'completed') && (
              <div className="mt-4 pt-4 border-t">
                {order.tracking_number ? (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-gray-600">Tracking Number</span>
                      <span className="font-medium font-mono">{order.tracking_number}</span>
                    </div>
                    {order.tracking_url ? (
                      <a
                        href={order.tracking_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground text-sm font-medium rounded-lg hover:bg-primary/90 transition-colors"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                        Track Shipment
                      </a>
                    ) : (
                      <p className="text-sm text-gray-500">
                        Use the tracking number above to track your shipment on your courier's website.
                      </p>
                    )}
                  </div>
                ) : (
                  <div className="text-sm text-gray-500">
                    <p>Your order is being processed. Tracking information will be available once your order has been shipped.</p>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
