import { useLocation } from "wouter";
import { useAuth } from "@/hooks/use-auth";
import { useQuery, useMutation } from "@tanstack/react-query";
import { ordersApi } from "@/lib/api";
import { apiRequest, queryClient } from "@/lib/queryClient";
import Header from "@/components/layout/header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { useToast } from "@/hooks/use-toast";
import { Package, ArrowLeft, Eye, RotateCcw, X } from "lucide-react";
import { useState } from "react";

export default function Orders() {
  const [, setLocation] = useLocation();
  const { user } = useAuth();
  const [searchQuery, setSearchQuery] = useState("");
  const { toast } = useToast();

  // Redirect if not authenticated
  if (!user) {
    setLocation('/auth');
    return null;
  }

  const { data: orders = [], isLoading } = useQuery({
    queryKey: ['/api/orders'],
    queryFn: async () => {
      const response = await ordersApi.get();
      return response.json();
    },
  });

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'delivered':
        return 'default';
      case 'shipped':
        return 'secondary';
      case 'pending':
        return 'outline';
      case 'cancelled':
        return 'destructive';
      default:
        return 'outline';
    }
  };

  const handleTrackOrder = (orderId: string) => {
    // For now, just show an alert - in a real app you'd open a tracking modal or page
    alert(`Tracking order ${orderId.slice(0, 8)}...`);
  };

  const handleReorder = (order: any) => {
    // For now, just navigate to home - in a real app you'd add items to cart
    alert('Items added to cart!');
    setLocation('/');
  };

  const cancelOrderMutation = useMutation({
    mutationFn: async (orderId: string) => {
      const response = await apiRequest('PATCH', `/api/orders/${orderId}/cancel`);
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
      toast({
        title: "Order Cancelled",
        description: "Your order has been successfully cancelled.",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Failed to Cancel Order",
        description: error.message || "Something went wrong. Please try again.",
        variant: "destructive",
      });
    },
  });

  const handleCancelOrder = (orderId: string) => {
    if (confirm('Are you sure you want to cancel this order? This action cannot be undone.')) {
      cancelOrderMutation.mutate(orderId);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Header searchQuery={searchQuery} setSearchQuery={setSearchQuery} />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8" data-testid="orders-page">
        {/* Back Button */}
        <div className="mb-6">
          <Button
            variant="ghost"
            onClick={() => setLocation('/profile')}
            className="text-gray-600 hover:text-gray-900"
            data-testid="back-to-profile"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Profile
          </Button>
        </div>

        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900" data-testid="orders-title">
            My Orders
          </h1>
          <p className="text-gray-600 mt-2">Track and manage your order history</p>
        </div>

        {/* Orders List */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Package className="h-5 w-5 mr-2" />
              Order History
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="space-y-4">
                {[...Array(3)].map((_, i) => (
                  <div key={i} className="border rounded-lg p-4">
                    <Skeleton className="h-6 w-48 mb-2" />
                    <Skeleton className="h-4 w-32 mb-4" />
                    <div className="space-y-2">
                      <Skeleton className="h-12 w-full" />
                      <Skeleton className="h-12 w-full" />
                    </div>
                  </div>
                ))}
              </div>
            ) : orders.length > 0 ? (
              <div className="space-y-6" data-testid="orders-list">
                {orders.map((order: any) => (
                  <div key={order.id} className="border border-gray-200 rounded-lg p-4 sm:p-6 hover:shadow-md transition-shadow" data-testid={`order-${order.id}`}>
                    {/* Order Header */}
                    <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-3 mb-4">
                      <div className="flex-1 min-w-0">
                        <h3 className="text-lg font-semibold text-gray-900 truncate" data-testid={`order-id-${order.id}`}>
                          Order #{order.id.slice(0, 8).toUpperCase()}
                        </h3>
                        <p className="text-sm text-gray-500" data-testid={`order-date-${order.id}`}>
                          Placed on {new Date(order.createdAt).toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                          })}
                        </p>
                      </div>
                      <Badge variant={getStatusColor(order.status)} className="text-sm w-fit" data-testid={`order-status-${order.id}`}>
                        {order.status.charAt(0).toUpperCase() + order.status.slice(1)}
                      </Badge>
                    </div>

                    {/* Order Items */}
                    {order.items && order.items.length > 0 && (
                      <div className="space-y-3 mb-4">
                        {order.items.map((item: any) => (
                          <div key={item.id} className="flex items-start space-x-3 p-3 bg-gray-50 rounded-lg" data-testid={`order-item-${item.id}`}>
                            <div className="w-12 h-12 sm:w-16 sm:h-16 bg-white rounded-md overflow-hidden border flex-shrink-0">
                              {item.product?.images && item.product.images.length > 0 ? (
                                <img
                                  src={item.product.images[0]}
                                  alt={item.product.title}
                                  className="w-full h-full object-cover"
                                />
                              ) : (
                                <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                                  <Package className="h-4 w-4 sm:h-6 sm:w-6 text-gray-400" />
                                </div>
                              )}
                            </div>
                            <div className="flex-1 min-w-0">
                              <h4 className="font-medium text-gray-900 text-sm sm:text-base truncate" data-testid={`order-item-title-${item.id}`}>
                                {item.product?.title || 'Unknown Product'}
                              </h4>
                              <p className="text-xs sm:text-sm text-gray-500 mb-1" data-testid={`order-item-seller-${item.id}`}>
                                Sold by {item.product?.store?.name || 'Unknown Seller'}
                              </p>
                              <div className="flex items-center justify-between">
                                <p className="text-xs sm:text-sm text-gray-500" data-testid={`order-item-quantity-${item.id}`}>
                                  Qty: {item.quantity}
                                </p>
                                <p className="font-semibold text-gray-900 text-sm sm:text-base" data-testid={`order-item-price-${item.id}`}>
                                  ₹{parseFloat(item.price).toFixed(2)}
                                </p>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}

                    {/* Order Summary */}
                    <div className="pt-4 border-t border-gray-200 space-y-3">
                      <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3">
                        <div>
                          <span className="text-lg font-bold text-gray-900 block" data-testid={`order-total-${order.id}`}>
                            Total: ₹{parseFloat(order.total).toFixed(2)}
                          </span>
                          <p className="text-sm text-gray-500">
                            Payment: {order.paymentMethod === 'cod' ? 'Cash on Delivery' : 'UPI'}
                          </p>
                        </div>
                        <div className="flex flex-col sm:flex-row gap-2 sm:gap-3">
                          <Button 
                            variant="outline" 
                            size="sm" 
                            onClick={() => handleTrackOrder(order.id)}
                            data-testid={`track-order-${order.id}`}
                            className="w-full sm:w-auto"
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Track Order
                          </Button>
                          {order.status === 'pending' && (
                            <Button 
                              variant="outline" 
                              size="sm"
                              onClick={() => handleCancelOrder(order.id)}
                              disabled={cancelOrderMutation.isPending}
                              data-testid={`cancel-order-${order.id}`}
                              className="text-red-600 hover:text-red-700 hover:border-red-300 w-full sm:w-auto"
                            >
                              <X className="h-4 w-4 mr-2" />
                              {cancelOrderMutation.isPending ? 'Cancelling...' : 'Cancel Order'}
                            </Button>
                          )}
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={() => handleReorder(order)}
                            data-testid={`reorder-${order.id}`}
                            className="w-full sm:w-auto"
                          >
                            <RotateCcw className="h-4 w-4 mr-2" />
                            Reorder
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-12" data-testid="no-orders">
                <Package className="h-16 w-16 text-gray-400 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">No orders yet</h3>
                <p className="text-gray-500 mb-6">You haven't placed any orders yet. Start shopping to see your orders here!</p>
                <Button
                  onClick={() => setLocation('/')}
                  className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                  data-testid="start-shopping"
                >
                  Start Shopping
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

    </div>
  );
}