import { useState, useEffect } from "react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";
import { Eye, Package, Search, Truck, ShoppingCart, Calendar, MapPin } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";

interface Order {
  id: string;
  order_number: string;
  total_amount: number;
  status: string;
  shipping_address: string | null;
  tracking_number: string | null;
  shipped_at: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

interface OrderItem {
  id: string;
  product_id: string;
  quantity: number;
  unit_price: number;
  products?: {
    name: string;
    image_url: string | null;
  };
}

interface OrderCoupon {
  id: string;
  coupon_id: string;
  coupons?: {
    name: string;
    code: string;
    type: string;
    discount_value: number;
  };
}

interface OrdersDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function OrdersDialog({ open, onOpenChange }: OrdersDialogProps) {
  const { user } = useAuth();
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const [orderCoupon, setOrderCoupon] = useState<OrderCoupon | null>(null);
  const { toast } = useToast();

  useEffect(() => {
    if (user && open) {
      fetchOrders();
    }
  }, [user, open]);

  const fetchOrders = async () => {
    if (!user) return;
    
    try {
      const { data, error } = await supabase
        .from("orders")
        .select("*")
        .eq("user_id", user.id)
        .order("created_at", { ascending: false });

      if (error) throw error;
      setOrders(data || []);
    } catch (error) {
      console.error("Error fetching orders:", error);
      toast({
        title: "错误",
        description: "获取订单列表失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const fetchOrderItems = async (orderId: string) => {
    try {
      const { data, error } = await supabase
        .from("order_items")
        .select(`
          *,
          products (
            name,
            image_url
          )
        `)
        .eq("order_id", orderId);

      if (error) throw error;
      setOrderItems(data || []);

      const { data: couponData, error: couponError } = await supabase
        .from("user_coupons")
        .select(`
          id,
          coupon_id,
          coupons (
            name,
            code,
            type,
            discount_value
          )
        `)
        .eq("order_id", orderId)
        .eq("status", "used")
        .maybeSingle();

      if (couponError) {
        console.error("Error fetching coupon:", couponError);
      } else {
        setOrderCoupon(couponData);
      }
    } catch (error) {
      console.error("Error fetching order items:", error);
      toast({
        title: "错误",
        description: "获取订单详情失败",
        variant: "destructive",
      });
    }
  };

  const handleViewOrder = async (order: Order) => {
    setSelectedOrder(order);
    setOrderCoupon(null);
    await fetchOrderItems(order.id);
  };

  const handleBackToList = () => {
    setSelectedOrder(null);
    setOrderItems([]);
    setOrderCoupon(null);
  };

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "pending":
        return "secondary";
      case "confirmed":
        return "default";
      case "shipped":
        return "outline";
      case "delivered":
        return "default";
      case "cancelled":
        return "destructive";
      default:
        return "secondary";
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case "pending":
        return "待处理";
      case "confirmed":
        return "已确认";
      case "shipped":
        return "已发货";
      case "delivered":
        return "已送达";
      case "cancelled":
        return "已取消";
      default:
        return status;
    }
  };

  const filteredOrders = orders.filter((order) => {
    const matchesSearch = 
      order.order_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.tracking_number?.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = statusFilter === "all" || order.status === statusFilter;
    
    return matchesSearch && matchesStatus;
  });

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const OrdersSummary = () => {
    const totalOrders = orders.length;
    const pendingOrders = orders.filter(o => o.status === 'pending').length;
    const shippedOrders = orders.filter(o => o.status === 'shipped').length;
    const deliveredOrders = orders.filter(o => o.status === 'delivered').length;

    return (
      <Card className="border-border shadow-lg">
        <CardHeader className="text-center pb-4">
          <div className="flex flex-col items-center space-y-4">
            <div className="h-20 w-20 rounded-full bg-primary/10 flex items-center justify-center">
              <ShoppingCart className="h-10 w-10 text-primary" />
            </div>
            <div>
              <h3 className="text-2xl font-bold text-foreground">{totalOrders}</h3>
              <p className="text-sm text-muted-foreground">全部订单</p>
            </div>
          </div>
        </CardHeader>
        
        <CardContent className="space-y-4">
          <div className="grid grid-cols-3 gap-2 text-center">
            <div className="p-2 rounded-lg bg-muted/50">
              <p className="text-lg font-semibold text-foreground">{pendingOrders}</p>
              <p className="text-xs text-muted-foreground">待处理</p>
            </div>
            <div className="p-2 rounded-lg bg-muted/50">
              <p className="text-lg font-semibold text-foreground">{shippedOrders}</p>
              <p className="text-xs text-muted-foreground">已发货</p>
            </div>
            <div className="p-2 rounded-lg bg-muted/50">
              <p className="text-lg font-semibold text-foreground">{deliveredOrders}</p>
              <p className="text-xs text-muted-foreground">已送达</p>
            </div>
          </div>
          
          <Separator />
          
          <div className="space-y-2 text-sm">
            <div className="flex items-center justify-between">
              <span className="text-muted-foreground">订单筛选</span>
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full">
                <SelectValue placeholder="状态筛选" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部</SelectItem>
                <SelectItem value="pending">待处理</SelectItem>
                <SelectItem value="confirmed">已确认</SelectItem>
                <SelectItem value="shipped">已发货</SelectItem>
                <SelectItem value="delivered">已送达</SelectItem>
                <SelectItem value="cancelled">已取消</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>
    );
  };

  if (loading) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-6xl max-h-[90vh] p-0 overflow-hidden">
          <div className="flex items-center justify-center p-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
          </div>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl max-h-[90vh] p-0 overflow-hidden">
        <div className="grid grid-cols-12 gap-0 h-full bg-background">
          {/* 左侧订单统计 */}
          <div className="col-span-3 bg-muted/30 p-6 border-r overflow-y-auto max-h-[90vh]">
            <OrdersSummary />
          </div>

          {/* 右侧订单列表或详情 */}
          <div className="col-span-9 p-6 overflow-y-auto max-h-[90vh]">
            {!selectedOrder ? (
              <div className="space-y-6">
                <Card className="border-border shadow-lg">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle className="flex items-center gap-2">
                          <Package className="h-5 w-5" />
                          我的订单
                        </CardTitle>
                        <CardDescription>查看和管理您的所有订单</CardDescription>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Search className="h-4 w-4 text-muted-foreground" />
                        <Input
                          placeholder="搜索订单号或快递单号..."
                          value={searchTerm}
                          onChange={(e) => setSearchTerm(e.target.value)}
                          className="w-64"
                        />
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    {filteredOrders.length === 0 ? (
                      <div className="text-center py-12">
                        <Package className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                        <h3 className="text-lg font-medium text-foreground mb-2">
                          {searchTerm || statusFilter !== "all" ? "没有找到匹配的订单" : "暂无订单"}
                        </h3>
                        <p className="text-muted-foreground">
                          {searchTerm || statusFilter !== "all" ? "尝试调整搜索条件" : "开始购物，创建您的第一个订单"}
                        </p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {filteredOrders.map((order) => (
                          <Card key={order.id} className="border border-border hover:shadow-md transition-shadow">
                            <CardContent className="p-6">
                              <div className="flex items-center justify-between">
                                <div className="space-y-1">
                                  <div className="flex items-center space-x-2">
                                    <span className="text-sm font-medium text-foreground">
                                      订单号: {order.order_number}
                                    </span>
                                    <Badge variant={getStatusBadgeVariant(order.status)}>
                                      {getStatusText(order.status)}
                                    </Badge>
                                  </div>
                                  <p className="text-sm text-muted-foreground">
                                    下单时间: {formatDate(order.created_at)}
                                  </p>
                                  <p className="text-lg font-semibold text-foreground">
                                    ¥{order.total_amount}
                                  </p>
                                  {order.tracking_number && (
                                    <div className="flex items-center space-x-1 text-sm text-muted-foreground">
                                      <Truck className="h-4 w-4" />
                                      <span>快递单号: {order.tracking_number}</span>
                                    </div>
                                  )}
                                </div>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleViewOrder(order)}
                                  className="flex items-center space-x-2"
                                >
                                  <Eye className="h-4 w-4" />
                                  <span>查看详情</span>
                                </Button>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            ) : (
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <Button variant="outline" size="sm" onClick={handleBackToList}>
                    返回订单列表
                  </Button>
                </div>

                <Card className="border-border shadow-lg">
                  <CardHeader>
                    <CardTitle>订单详情</CardTitle>
                    <CardDescription>订单号: {selectedOrder.order_number}</CardDescription>
                  </CardHeader>
                  
                  <CardContent className="space-y-6">
                    {/* 订单基本信息 */}
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label>订单金额</Label>
                        <p className="text-sm text-muted-foreground">¥{selectedOrder.total_amount}</p>
                      </div>
                      <div>
                        <Label>当前状态</Label>
                        <div className="mt-1">
                          <Badge variant={getStatusBadgeVariant(selectedOrder.status)}>
                            {getStatusText(selectedOrder.status)}
                          </Badge>
                        </div>
                      </div>
                      <div>
                        <Label className="flex items-center gap-2">
                          <Calendar className="h-4 w-4" />
                          下单时间
                        </Label>
                        <p className="text-sm text-muted-foreground">
                          {formatDate(selectedOrder.created_at)}
                        </p>
                      </div>
                      {selectedOrder.tracking_number && (
                        <div>
                          <Label className="flex items-center gap-2">
                            <Truck className="h-4 w-4" />
                            快递单号
                          </Label>
                          <p className="text-sm text-muted-foreground">
                            {selectedOrder.tracking_number}
                          </p>
                        </div>
                      )}
                    </div>

                    {/* 收货地址 */}
                    {selectedOrder.shipping_address && (
                      <div>
                        <Label className="flex items-center gap-2">
                          <MapPin className="h-4 w-4" />
                          收货地址
                        </Label>
                        <p className="text-sm text-muted-foreground">
                          {selectedOrder.shipping_address}
                        </p>
                      </div>
                    )}

                    <Separator />

                    {/* 订单商品 */}
                    <div>
                      <Label>订单商品</Label>
                      <div className="mt-2 space-y-2">
                        {orderItems.map((item) => (
                          <div key={item.id} className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                            <div className="flex items-center space-x-3">
                              <div className="w-12 h-12 bg-muted rounded-lg flex items-center justify-center">
                                <Package className="h-6 w-6 text-muted-foreground" />
                              </div>
                              <div>
                                <p className="text-sm font-medium">
                                  {item.products?.name || "未知商品"}
                                </p>
                                <p className="text-xs text-muted-foreground">
                                  数量: {item.quantity} × ¥{item.unit_price}
                                </p>
                              </div>
                            </div>
                            <p className="text-sm font-medium">
                              ¥{(item.quantity * item.unit_price).toFixed(2)}
                            </p>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* 使用的优惠券 */}
                    {orderCoupon && orderCoupon.coupons && (
                      <div>
                        <Label>使用的优惠券</Label>
                        <div className="mt-2 p-3 bg-primary/10 border border-primary/20 rounded-lg">
                          <div className="flex items-center justify-between">
                            <div>
                              <p className="text-sm font-medium text-foreground">
                                {orderCoupon.coupons.name}
                              </p>
                              <p className="text-xs text-muted-foreground">
                                优惠码: {orderCoupon.coupons.code}
                              </p>
                            </div>
                            <Badge variant="default">
                              {orderCoupon.coupons.type === 'percentage' 
                                ? `-${orderCoupon.coupons.discount_value}%` 
                                : `-¥${orderCoupon.coupons.discount_value}`}
                            </Badge>
                          </div>
                        </div>
                      </div>
                    )}

                    {/* 备注信息 */}
                    {selectedOrder.notes && (
                      <div>
                        <Label>备注</Label>
                        <p className="text-sm text-muted-foreground">
                          {selectedOrder.notes}
                        </p>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
