import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { Eye, Truck, Package, Search, ArrowUpDown } from "lucide-react";
import { subscribeToPageState, PageState } from "./AdminAIAssistant";
import { cn } from "@/lib/utils";

interface Order {
  id: string;
  order_number: string;
  user_id: 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;
  profiles?: {
    display_name: string | null;
  } | null;
}

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;
  };
}

export function OrdersManager() {
  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 [isDialogOpen, setIsDialogOpen] = useState(false);
  const [trackingNumber, setTrackingNumber] = useState("");
  const [highlightIds, setHighlightIds] = useState<string[]>([]);
  const [sortConfig, setSortConfig] = useState<{ field: string; direction: 'asc' | 'desc' }>({ field: 'created_at', direction: 'desc' });
  const { toast } = useToast();

  // 订阅AI页面状态变化
  useEffect(() => {
    const unsubscribe = subscribeToPageState((state) => {
      if (state.tab !== 'orders') return;
      
      console.log('OrdersManager received page state:', state);
      
      // 应用过滤条件
      if (state.filters) {
        if (state.filters.status) {
          setStatusFilter(state.filters.status);
        }
      }
      
      // 应用搜索
      if (state.search !== undefined) {
        setSearchTerm(state.search);
      }
      
      // 应用排序
      if (state.sort) {
        setSortConfig(state.sort);
      }
      
      // 高亮特定数据
      if (state.highlightIds) {
        setHighlightIds(state.highlightIds);
        // 5秒后清除高亮
        setTimeout(() => setHighlightIds([]), 5000);
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);

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

  const fetchOrders = async () => {
    try {
      // 先获取订单数据
      const { data: ordersData, error: ordersError } = await supabase
        .from("orders")
        .select("*")
        .order("created_at", { ascending: false });

      if (ordersError) throw ordersError;

      // 获取所有用户的profile信息
      const { data: profilesData, error: profilesError } = await supabase
        .from("profiles")
        .select("user_id, display_name");

      if (profilesError) throw profilesError;

      // 手动关联数据
      const ordersWithProfiles = (ordersData || []).map(order => {
        const profile = profilesData?.find(p => p.user_id === order.user_id);
        return {
          ...order,
          profiles: profile ? { display_name: profile.display_name } : null
        };
      });

      setOrders(ordersWithProfiles);
    } 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);
    setTrackingNumber(order.tracking_number || "");
    setOrderCoupon(null); // 重置优惠券
    await fetchOrderItems(order.id);
    setIsDialogOpen(true);
  };

  const handleUpdateOrderStatus = async (orderId: string, newStatus: string) => {
    try {
      const updateData: any = { status: newStatus };
      
      if (newStatus === "shipped" && trackingNumber) {
        updateData.tracking_number = trackingNumber;
        updateData.shipped_at = new Date().toISOString();
      }

      const { error } = await supabase
        .from("orders")
        .update(updateData)
        .eq("id", orderId);

      if (error) throw error;
      
      toast({
        title: "成功",
        description: "订单状态更新成功",
      });
      
      fetchOrders();
      if (selectedOrder?.id === orderId) {
        setSelectedOrder({ ...selectedOrder, status: newStatus, tracking_number: trackingNumber });
      }
    } catch (error) {
      console.error("Error updating order status:", error);
      toast({
        title: "错误",
        description: "更新订单状态失败",
        variant: "destructive",
      });
    }
  };

  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 sortOrders = (ordersToSort: Order[]) => {
    return [...ordersToSort].sort((a, b) => {
      let aVal: any = a[sortConfig.field as keyof Order];
      let bVal: any = b[sortConfig.field as keyof Order];
      
      if (sortConfig.field === 'created_at') {
        aVal = new Date(aVal).getTime();
        bVal = new Date(bVal).getTime();
      }
      
      if (aVal < bVal) return sortConfig.direction === 'asc' ? -1 : 1;
      if (aVal > bVal) return sortConfig.direction === 'asc' ? 1 : -1;
      return 0;
    });
  };

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

  const handleSort = (field: string) => {
    setSortConfig(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'desc' ? 'asc' : 'desc'
    }));
  };

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

  if (loading) {
    return <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>;
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>订单管理</CardTitle>
            <CardDescription>管理所有订单和物流信息</CardDescription>
          </div>
          <div className="flex items-center space-x-4">
            <div className="w-64">
              <Input
                placeholder="搜索订单号、用户名或快递单号..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32">
                <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>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleSort('order_number')}
              >
                订单号 {sortConfig.field === 'order_number' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
              </TableHead>
              <TableHead>用户</TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleSort('total_amount')}
              >
                金额 {sortConfig.field === 'total_amount' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
              </TableHead>
              <TableHead>状态</TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleSort('created_at')}
              >
                创建时间 {sortConfig.field === 'created_at' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
              </TableHead>
              <TableHead>快递单号</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredOrders.map((order) => (
              <TableRow 
                key={order.id}
                className={cn(
                  highlightIds.includes(order.id) && "bg-primary/10 animate-pulse"
                )}
              >
                <TableCell className="font-medium">{order.order_number}</TableCell>
                <TableCell>{order.profiles?.display_name || "未知用户"}</TableCell>
                <TableCell>¥{order.total_amount}</TableCell>
                <TableCell>
                  <Badge variant={getStatusBadgeVariant(order.status)}>
                    {getStatusText(order.status)}
                  </Badge>
                </TableCell>
                <TableCell>{formatDate(order.created_at)}</TableCell>
                <TableCell>{order.tracking_number || "-"}</TableCell>
                <TableCell>
                  <div className="flex items-center space-x-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewOrder(order)}
                    >
                      <Eye className="w-4 h-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>

        {filteredOrders.length === 0 && (
          <div className="text-center py-8 text-muted-foreground">
            {searchTerm || statusFilter !== "all" ? "没有找到匹配的订单" : "暂无订单数据"}
          </div>
        )}

        <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.profiles?.display_name || "未知用户"}
                    </p>
                  </div>
                  <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>
                </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-2 bg-muted/50 rounded">
                        <div className="flex items-center space-x-2">
                          <div className="w-8 h-8 bg-muted rounded"></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>
                )}

                {/* 物流信息 */}
                <div className="space-y-4">
                  <Label>物流管理</Label>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="tracking">快递单号</Label>
                      <Input
                        id="tracking"
                        value={trackingNumber}
                        onChange={(e) => setTrackingNumber(e.target.value)}
                        placeholder="输入快递单号"
                      />
                    </div>
                    <div>
                      <Label>更新状态</Label>
                      <Select
                        value={selectedOrder.status}
                        onValueChange={(value) => handleUpdateOrderStatus(selectedOrder.id, value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="pending">待处理</SelectItem>
                          <SelectItem value="confirmed">已确认</SelectItem>
                          <SelectItem value="shipped">已发货</SelectItem>
                          <SelectItem value="delivered">已送达</SelectItem>
                          <SelectItem value="cancelled">已取消</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

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

            <DialogFooter>
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                关闭
              </Button>
              {selectedOrder && selectedOrder.status !== "shipped" && (
                <Button 
                  onClick={() => handleUpdateOrderStatus(selectedOrder.id, "shipped")}
                  disabled={!trackingNumber}
                >
                  <Truck className="w-4 h-4 mr-2" />
                  标记为已发货
                </Button>
              )}
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </CardContent>
    </Card>
  );
}