import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { Package, ShoppingBag, Clock, Eye, ChevronRight } from 'lucide-react';
import { Button } from '../components/ui/button';
import { Badge } from '../components/ui/badge';
import { Separator } from '../components/ui/separator';
import { useAuth } from '../context/AuthContext';

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

const statusColors = {
  pending: 'bg-yellow-500',
  processing: 'bg-blue-500',
  layaway: 'bg-purple-500',
  shipped: 'bg-cyan-500',
  delivered: 'bg-green-500',
  cancelled: 'bg-red-500',
  refunded: 'bg-orange-500',
  on_hold: 'bg-gray-500'
};

const statusLabels = {
  pending: 'Pending',
  processing: 'Processing',
  layaway: 'Layaway',
  shipped: 'Shipped',
  delivered: 'Delivered',
  cancelled: 'Cancelled',
  refunded: 'Refunded',
  on_hold: 'On Hold'
};

const OrderHistory = () => {
  const { token, isAuthenticated } = useAuth();
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState(null);

  useEffect(() => {
    if (isAuthenticated) {
      fetchOrders();
    }
  }, [isAuthenticated, token]);

  const fetchOrders = async () => {
    try {
      const response = await axios.get(`${API}/orders`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setOrders(response.data);
    } catch (error) {
      console.error('Failed to fetch orders:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen py-12 md:py-16">
        <div className="max-w-4xl mx-auto px-4 md:px-8 text-center py-16">
          <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-muted flex items-center justify-center">
            <ShoppingBag className="h-10 w-10 text-muted-foreground" />
          </div>
          <h2 className="text-2xl font-bold mb-4 font-['Outfit']">Please Sign In</h2>
          <p className="text-muted-foreground mb-8">You need to be logged in to view your orders</p>
          <Link to="/login">
            <Button className="rounded-full">Sign In</Button>
          </Link>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen py-12 md:py-16">
        <div className="max-w-4xl mx-auto px-4 md:px-8">
          <div className="animate-pulse space-y-4">
            {[...Array(3)].map((_, i) => (
              <div key={i} className="h-32 bg-muted rounded-xl" />
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen py-12 md:py-16">
      <div className="max-w-4xl mx-auto px-4 md:px-8">
        <h1 className="text-3xl font-bold font-['Outfit'] mb-8">Order History</h1>

        {orders.length === 0 ? (
          <div className="text-center py-16">
            <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-muted flex items-center justify-center">
              <Package className="h-10 w-10 text-muted-foreground" />
            </div>
            <h2 className="text-xl font-bold mb-4 font-['Outfit']">No Orders Yet</h2>
            <p className="text-muted-foreground mb-8">Start shopping to see your orders here</p>
            <Link to="/products">
              <Button className="rounded-full">Browse Products</Button>
            </Link>
          </div>
        ) : (
          <div className="space-y-4">
            {orders.map((order) => (
              <div
                key={order.id}
                className="border border-border rounded-xl bg-card overflow-hidden"
                data-testid={`order-${order.id}`}
              >
                {/* Order Header */}
                <div className="p-4 md:p-6 flex flex-col md:flex-row md:items-center justify-between gap-4 bg-muted/30">
                  <div className="flex flex-wrap gap-4 md:gap-8">
                    <div>
                      <p className="text-xs text-muted-foreground mb-1">Order ID</p>
                      <p className="font-mono text-sm">{order.id.slice(0, 8)}...</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground mb-1">Date</p>
                      <p className="text-sm">{new Date(order.created_at).toLocaleDateString()}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground mb-1">Total</p>
                      <p className="font-semibold font-['Outfit']">${order.total.toFixed(2)}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <Badge className={`${statusColors[order.status]} text-white`}>
                      {statusLabels[order.status]}
                    </Badge>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setSelectedOrder(selectedOrder === order.id ? null : order.id)}
                      data-testid={`toggle-order-${order.id}`}
                    >
                      {selectedOrder === order.id ? 'Hide' : 'Details'}
                      <ChevronRight className={`h-4 w-4 ml-1 transition-transform ${selectedOrder === order.id ? 'rotate-90' : ''}`} />
                    </Button>
                  </div>
                </div>

                {/* Order Details */}
                {selectedOrder === order.id && (
                  <div className="p-4 md:p-6 border-t border-border">
                    {/* Items */}
                    <h4 className="font-semibold mb-4 font-['Outfit']">Items</h4>
                    <div className="space-y-3 mb-6">
                      {order.items.map((item) => (
                        <div key={item.id} className="flex items-center gap-4">
                          <div className="w-16 h-16 rounded-lg overflow-hidden bg-muted flex-shrink-0">
                            <img
                              src={item.product_image}
                              alt={item.product_name}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="font-medium truncate">{item.product_name}</p>
                            <p className="text-sm text-muted-foreground">Qty: {item.quantity}</p>
                          </div>
                          <p className="font-semibold">${(item.price * item.quantity).toFixed(2)}</p>
                        </div>
                      ))}
                    </div>

                    <Separator className="my-4" />

                    {/* Order Summary */}
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <p className="text-muted-foreground">Subtotal</p>
                        <p className="font-medium">${order.subtotal.toFixed(2)}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">Tax</p>
                        <p className="font-medium">${order.tax.toFixed(2)}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">Shipping</p>
                        <p className="font-medium">${order.shipping.toFixed(2)}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">Total</p>
                        <p className="font-bold text-lg font-['Outfit']">${order.total.toFixed(2)}</p>
                      </div>
                    </div>

                    {/* Tracking */}
                    {order.tracking_number && (
                      <div className="mt-4 p-3 bg-muted rounded-lg">
                        <p className="text-sm text-muted-foreground">Tracking Number</p>
                        <p className="font-mono">{order.tracking_number}</p>
                      </div>
                    )}

                    {/* Status History */}
                    {order.status_history && order.status_history.length > 0 && (
                      <div className="mt-6">
                        <h4 className="font-semibold mb-3 font-['Outfit']">Order Timeline</h4>
                        <div className="space-y-3">
                          {order.status_history.map((history, idx) => (
                            <div key={history.id} className="flex items-start gap-3">
                              <div className="relative">
                                <div className={`w-3 h-3 rounded-full ${statusColors[history.status]}`} />
                                {idx < order.status_history.length - 1 && (
                                  <div className="absolute top-3 left-1.5 w-0.5 h-6 bg-border -translate-x-1/2" />
                                )}
                              </div>
                              <div>
                                <p className="font-medium text-sm">{statusLabels[history.status]}</p>
                                <p className="text-xs text-muted-foreground">
                                  {new Date(history.created_at).toLocaleString()}
                                </p>
                                {history.notes && (
                                  <p className="text-xs text-muted-foreground mt-1">{history.notes}</p>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default OrderHistory;
