import { useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { Header } from "@/components/layout/Header";
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 { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Eye, Package, Search, Truck, ArrowLeft } from "lucide-react";
import { Label } from "@/components/ui/label";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import {
  useOrdersList,
  useOrderItems,
  useOrderCoupon,
  type OrderRow,
} from "@/hooks/queries/useOrders";
import { ListSkeleton } from "@/components/ui/section-skeleton";
import { SectionErrorBoundary } from "@/components/SectionErrorBoundary";

export default function OrdersPage() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [selectedOrder, setSelectedOrder] = useState<OrderRow | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const {
    data: orders = [],
    isLoading,
    isError,
    error,
    refetch,
  } = useOrdersList(user?.id);

  const { data: orderItems = [] } = useOrderItems(selectedOrder?.id);
  const { data: orderCoupon } = useOrderCoupon(selectedOrder?.id);

  const handleViewOrder = (order: OrderRow) => {
    setSelectedOrder(order);
    setIsDialogOpen(true);
  };

  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) =>
    new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });

  // 错误态：toast + 内联提示
  if (isError) {
    toast.error("获取订单列表失败", { description: (error as Error)?.message });
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      <main className="container mx-auto p-6">
        <div className="max-w-6xl mx-auto">
          <div className="mb-6">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <div>
                <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-2">我的订单</h1>
                <p className="text-sm sm:text-base text-muted-foreground">查看和管理您的所有订单</p>
              </div>
              <div className="flex items-center">
                <Button
                  onClick={() => navigate(-1)}
                  variant="outline"
                  size="sm"
                  className="flex items-center space-x-1 sm:space-x-2"
                >
                  <ArrowLeft className="h-3 w-3 sm:h-4 sm:w-4" />
                  <span className="text-sm">返回</span>
                </Button>
              </div>
            </div>
          </div>

          <SectionErrorBoundary scope="orders-page-list" title="订单列表渲染失败">
            <Card>
              <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-4">
                    <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"
                        aria-label="搜索订单"
                      />
                    </div>
                    <Select value={statusFilter} onValueChange={setStatusFilter}>
                      <SelectTrigger className="w-32" aria-label="状态筛选">
                        <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>
                </div>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <ListSkeleton rows={4} />
                ) : isError ? (
                  <div className="text-center py-12 space-y-3">
                    <Package className="h-12 w-12 text-muted-foreground mx-auto" />
                    <p className="text-sm text-muted-foreground">加载订单失败</p>
                    <Button variant="outline" size="sm" onClick={() => refetch()}>
                      重试
                    </Button>
                  </div>
                ) : 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"
                              aria-label={`查看订单 ${order.order_number} 详情`}
                            >
                              <Eye className="h-4 w-4" />
                              <span>查看详情</span>
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </SectionErrorBoundary>

          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogContent className="sm:max-w-[600px]">
              <DialogHeader>
                <DialogTitle>订单详情</DialogTitle>
                <DialogDescription>
                  订单号: {selectedOrder?.order_number}
                </DialogDescription>
              </DialogHeader>

              {selectedOrder && (
                <div 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>
                      <Badge variant={getStatusBadgeVariant(selectedOrder.status)} className="ml-0">
                        {getStatusText(selectedOrder.status)}
                      </Badge>
                    </div>
                    <div>
                      <Label>下单时间</Label>
                      <p className="text-sm text-muted-foreground">
                        {formatDate(selectedOrder.created_at)}
                      </p>
                    </div>
                    {selectedOrder.tracking_number && (
                      <div>
                        <Label>快递单号</Label>
                        <p className="text-sm text-muted-foreground">
                          {selectedOrder.tracking_number}
                        </p>
                      </div>
                    )}
                  </div>

                  {selectedOrder.shipping_address && (
                    <div>
                      <Label>收货地址</Label>
                      <p className="text-sm text-muted-foreground">
                        {selectedOrder.shipping_address}
                      </p>
                    </div>
                  )}

                  <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>
                  )}
                </div>
              )}
            </DialogContent>
          </Dialog>
        </div>
      </main>
    </div>
  );
}
