import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { 
  Eye, 
  Truck, 
  Package,
  MapPin,
  Clock,
  CheckCircle2,
  AlertTriangle,
  ArrowUpDown,
  Send,
  User
} from "lucide-react";
import { UserDetailDialog } from "@/components/admin/UserDetailDialog";

interface OrderData {
  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;
  created_at: string;
  updated_at: string;
  profiles?: {
    display_name: string | null;
  } | null;
  order_items: Array<{
    id: string;
    quantity: number;
    unit_price: number;
    products: {
      name: string;
      image_url: string | null;
    } | null;
  }>;
}

export function ServiceOrdersView() {
  const [orders, setOrders] = useState<OrderData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [fulfillmentFilter, setFulfillmentFilter] = useState("all");
  const [selectedOrder, setSelectedOrder] = useState<OrderData | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [trackingNumber, setTrackingNumber] = useState("");
  const [sortConfig, setSortConfig] = useState<{ field: string; direction: 'asc' | 'desc' }>({ 
    field: 'created_at', 
    direction: 'desc' 
  });
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [isUserDetailOpen, setIsUserDetailOpen] = useState(false);
  const { toast } = useToast();

  const handleViewUserProfile = (userId: string) => {
    setSelectedUserId(userId);
    setIsUserDetailOpen(true);
  };

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

  const fetchOrders = async () => {
    try {
      const { data: ordersData, error: ordersError } = await supabase
        .from("orders")
        .select(`
          *,
          order_items (
            id,
            quantity,
            unit_price,
            products (name, image_url)
          )
        `)
        .order("created_at", { ascending: false });

      if (ordersError) throw ordersError;

      const userIds = [...new Set(ordersData?.map(order => order.user_id) || [])];
      const { data: profilesData } = await supabase
        .from("profiles")
        .select("user_id, display_name")
        .in("user_id", userIds);

      const profilesMap = new Map(
        profilesData?.map(profile => [profile.user_id, profile]) || []
      );

      const ordersWithProfiles = ordersData?.map(order => ({
        ...order,
        profiles: profilesMap.get(order.user_id) || null
      })) || [];

      setOrders(ordersWithProfiles);
    } catch (error) {
      console.error("Error fetching orders:", error);
      toast({
        title: "错误",
        description: "获取订单数据失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleShipOrder = async (orderId: string) => {
    if (!trackingNumber.trim()) {
      toast({
        title: "提示",
        description: "请输入快递单号",
        variant: "destructive",
      });
      return;
    }

    try {
      const { error } = await supabase
        .from("orders")
        .update({ 
          status: "shipped",
          tracking_number: trackingNumber,
          shipped_at: new Date().toISOString()
        })
        .eq("id", orderId);

      if (error) throw error;
      
      toast({
        title: "成功",
        description: "订单已发货",
      });
      
      fetchOrders();
      setIsDialogOpen(false);
    } catch (error) {
      console.error("Error shipping order:", error);
      toast({
        title: "错误",
        description: "发货失败",
        variant: "destructive",
      });
    }
  };

  const handleConfirmDelivery = async (orderId: string) => {
    try {
      const { error } = await supabase
        .from("orders")
        .update({ status: "delivered" })
        .eq("id", orderId);

      if (error) throw error;
      
      toast({
        title: "成功",
        description: "已确认送达",
      });
      
      fetchOrders();
      setIsDialogOpen(false);
    } catch (error) {
      console.error("Error confirming delivery:", error);
      toast({
        title: "错误",
        description: "确认失败",
        variant: "destructive",
      });
    }
  };

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

  // 履约视角的状态
  const getFulfillmentStatus = (order: OrderData) => {
    switch (order.status) {
      case "pending":
        return { text: "待确认", variant: "secondary" as const, icon: Clock, priority: "low" };
      case "confirmed":
        return { text: "待发货", variant: "destructive" as const, icon: AlertTriangle, priority: "high" };
      case "shipped":
        return { text: "运输中", variant: "default" as const, icon: Truck, priority: "medium" };
      case "delivered":
        return { text: "已送达", variant: "outline" as const, icon: CheckCircle2, priority: "done" };
      case "cancelled":
        return { text: "已取消", variant: "secondary" as const, icon: Clock, priority: "done" };
      default:
        return { text: order.status, variant: "secondary" as const, icon: Clock, priority: "low" };
    }
  };

  const sortOrders = (ordersToSort: OrderData[]) => {
    return [...ordersToSort].sort((a, b) => {
      let aVal: any = a[sortConfig.field as keyof OrderData];
      let bVal: any = b[sortConfig.field as keyof OrderData];
      
      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());
    
    let matchesFulfillment = true;
    if (fulfillmentFilter === "pending") {
      matchesFulfillment = order.status === "pending";
    } else if (fulfillmentFilter === "to_ship") {
      matchesFulfillment = order.status === "confirmed";
    } else if (fulfillmentFilter === "shipping") {
      matchesFulfillment = order.status === "shipped";
    } else if (fulfillmentFilter === "delivered") {
      matchesFulfillment = order.status === "delivered";
    }
    
    return matchesSearch && matchesFulfillment;
  }));

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

  // 履约统计
  const stats = {
    toConfirm: orders.filter(o => o.status === 'pending').length,
    toShip: orders.filter(o => o.status === 'confirmed').length,
    shipping: orders.filter(o => o.status === 'shipped').length,
    delivered: orders.filter(o => o.status === 'delivered').length,
  };

  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 (
    <div className="space-y-6">
      {/* 履约概览卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className={stats.toConfirm > 0 ? "border-yellow-200 bg-yellow-50/50" : ""}>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">待确认</p>
                <p className="text-2xl font-bold">{stats.toConfirm}</p>
              </div>
              <Clock className="h-8 w-8 text-yellow-500" />
            </div>
          </CardContent>
        </Card>
        <Card className={stats.toShip > 0 ? "border-red-200 bg-red-50/50" : ""}>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">待发货</p>
                <p className="text-2xl font-bold text-red-600">{stats.toShip}</p>
              </div>
              <AlertTriangle className="h-8 w-8 text-red-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">运输中</p>
                <p className="text-2xl font-bold text-blue-600">{stats.shipping}</p>
              </div>
              <Truck className="h-8 w-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">已送达</p>
                <p className="text-2xl font-bold text-green-600">{stats.delivered}</p>
              </div>
              <CheckCircle2 className="h-8 w-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 订单列表 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              订单履约
            </CardTitle>
            <div className="flex items-center gap-4">
              <Input
                placeholder="搜索订单号、客户或快递单号..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-64"
              />
              <Select value={fulfillmentFilter} onValueChange={setFulfillmentFilter}>
                <SelectTrigger className="w-32">
                  <SelectValue placeholder="履约状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="pending">待确认</SelectItem>
                  <SelectItem value="to_ship">待发货</SelectItem>
                  <SelectItem value="shipping">运输中</SelectItem>
                  <SelectItem value="delivered">已送达</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>商品</TableHead>
                <TableHead>履约状态</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>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredOrders.map((order) => {
                const fulfillmentStatus = getFulfillmentStatus(order);
                const StatusIcon = fulfillmentStatus.icon;
                return (
                  <TableRow 
                    key={order.id}
                    className={fulfillmentStatus.priority === 'high' ? 'bg-red-50/50' : ''}
                  >
                    <TableCell className="font-mono text-sm">{order.order_number}</TableCell>
                    <TableCell>
                      <Button 
                        variant="link" 
                        className="p-0 h-auto font-medium text-primary hover:underline"
                        onClick={() => handleViewUserProfile(order.user_id)}
                      >
                        <User className="w-3 h-3 mr-1" />
                        {order.profiles?.display_name || "未知客户"}
                      </Button>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 bg-muted rounded overflow-hidden">
                          {order.order_items[0]?.products?.image_url ? (
                            <img 
                              src={order.order_items[0].products.image_url} 
                              alt=""
                              className="w-full h-full object-cover"
                            />
                          ) : (
                            <Package className="w-full h-full p-1 text-muted-foreground" />
                          )}
                        </div>
                        <div>
                          <p className="text-sm font-medium truncate max-w-[120px]">
                            {order.order_items[0]?.products?.name || "商品"}
                          </p>
                          {order.order_items.length > 1 && (
                            <p className="text-xs text-muted-foreground">
                              等 {order.order_items.length} 件
                            </p>
                          )}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={fulfillmentStatus.variant} className="flex items-center gap-1 w-fit">
                        <StatusIcon className="h-3 w-3" />
                        {fulfillmentStatus.text}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-mono text-sm text-muted-foreground">
                      {order.tracking_number || "-"}
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {formatDate(order.created_at)}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedOrder(order);
                            setTrackingNumber(order.tracking_number || "");
                            setIsDialogOpen(true);
                          }}
                        >
                          <Eye className="w-4 h-4" />
                        </Button>
                        {order.status === "confirmed" && (
                          <Button
                            variant="default"
                            size="sm"
                            onClick={() => {
                              setSelectedOrder(order);
                              setTrackingNumber("");
                              setIsDialogOpen(true);
                            }}
                          >
                            <Send className="w-4 h-4 mr-1" />
                            发货
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>

          {filteredOrders.length === 0 && (
            <div className="text-center py-8 text-muted-foreground">
              暂无订单
            </div>
          )}
        </CardContent>
      </Card>

      {/* 履约详情对话框 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[550px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              订单履约详情
            </DialogTitle>
            <DialogDescription>
              订单号: {selectedOrder?.order_number}
            </DialogDescription>
          </DialogHeader>
          
          {selectedOrder && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground">客户</Label>
                  <p className="font-medium">{selectedOrder.profiles?.display_name || "未知客户"}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">下单时间</Label>
                  <p className="font-medium">{formatDate(selectedOrder.created_at)}</p>
                </div>
              </div>

              {/* 收货地址 */}
              {selectedOrder.shipping_address && (
                <div className="p-3 bg-muted/50 rounded-lg">
                  <div className="flex items-start gap-2">
                    <MapPin className="h-4 w-4 mt-0.5 text-muted-foreground" />
                    <div>
                      <Label className="text-muted-foreground">收货地址</Label>
                      <p className="font-medium">{selectedOrder.shipping_address}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* 商品列表 */}
              <div>
                <Label className="text-muted-foreground">商品清单</Label>
                <div className="mt-2 space-y-2">
                  {selectedOrder.order_items.map((item) => (
                    <div key={item.id} className="flex items-center gap-3 p-2 bg-muted/30 rounded">
                      <div className="w-10 h-10 bg-muted rounded overflow-hidden">
                        {item.products?.image_url ? (
                          <img src={item.products.image_url} alt="" className="w-full h-full object-cover" />
                        ) : (
                          <Package className="w-full h-full p-2 text-muted-foreground" />
                        )}
                      </div>
                      <div className="flex-1">
                        <p className="text-sm font-medium">{item.products?.name || "商品"}</p>
                        <p className="text-xs text-muted-foreground">× {item.quantity}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* 物流信息 */}
              {selectedOrder.status === "confirmed" && (
                <div className="space-y-2">
                  <Label htmlFor="tracking">快递单号</Label>
                  <Input
                    id="tracking"
                    value={trackingNumber}
                    onChange={(e) => setTrackingNumber(e.target.value)}
                    placeholder="请输入快递单号"
                  />
                </div>
              )}

              {selectedOrder.tracking_number && (
                <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-2">
                    <Truck className="h-4 w-4 text-blue-600" />
                    <div>
                      <p className="text-sm text-muted-foreground">快递单号</p>
                      <p className="font-mono font-medium">{selectedOrder.tracking_number}</p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
              关闭
            </Button>
            {selectedOrder?.status === "confirmed" && (
              <Button onClick={() => handleShipOrder(selectedOrder.id)}>
                <Send className="w-4 h-4 mr-2" />
                确认发货
              </Button>
            )}
            {selectedOrder?.status === "shipped" && (
              <Button onClick={() => handleConfirmDelivery(selectedOrder.id)}>
                <CheckCircle2 className="w-4 h-4 mr-2" />
                确认送达
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 用户画像对话框 */}
      {selectedUserId && (
        <UserDetailDialog
          isOpen={isUserDetailOpen}
          onOpenChange={setIsUserDetailOpen}
          userId={selectedUserId}
          userDisplayName=""
        />
      )}
    </div>
  );
}
