import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { 
  User, 
  Mail, 
  Phone, 
  Calendar, 
  Edit3, 
  Save, 
  X, 
  Shield,
  Clock,
  Settings,
  Bell,
  Globe,
  Moon,
  Sun,
  Package,
  ShoppingCart,
  Truck,
  Eye,
  MapPin,
  RotateCcw,
  Ticket,
  CheckCircle,
  XCircle,
  Plus,
  Search,
  Filter,
  AlertCircle,
  MessageSquare,
  Star
} from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { format } from "date-fns";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

interface ProfileData {
  display_name: string;
  bio: string;
  phone: string;
  avatar_url?: string;
}

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 AfterSalesRequest {
  id: string;
  user_id: string;
  order_id: string;
  product_id: string;
  type: 'return' | 'exchange' | 'repair';
  status: 'pending' | 'approved' | 'processing' | 'completed' | 'rejected';
  reason: string;
  description: string;
  images?: string[];
  admin_notes?: string;
  tracking_number?: string;
  refund_amount?: number;
  processed_by?: string;
  processed_at?: string;
  created_at: string;
  updated_at: string;
  orderNumber?: string;
  productName?: string;
  productImage?: string;
}

interface UserCoupon {
  id: string;
  coupon_id: string;
  status: string;
  received_at: string;
  used_at: string | null;
  coupon: {
    code: string;
    name: string;
    description: string;
    type: string;
    discount_value: number;
    min_purchase_amount: number | null;
    max_discount_amount: number | null;
    start_date: string;
    end_date: string;
  };
}

interface ProfileDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultTab?: string;
}

export function ProfileDialog({ open, onOpenChange, defaultTab = "profile" }: ProfileDialogProps) {
  const { user, profile, refreshProfile, isAdmin } = useAuth();
  const { toast } = useToast();
  const navigate = useNavigate();
  
  const [isEditing, setIsEditing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState(defaultTab);

  // 邮箱修改
  const [isChangingEmail, setIsChangingEmail] = useState(false);
  const [newEmail, setNewEmail] = useState("");
  const [emailLoading, setEmailLoading] = useState(false);
  const [formData, setFormData] = useState<ProfileData>({
    display_name: "",
    bio: "",
    phone: "",
    avatar_url: ""
  });

  // Orders state
  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const [orderCoupon, setOrderCoupon] = useState<OrderCoupon | null>(null);
  const [orderSearchTerm, setOrderSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  // After-sales state
  const [afterSalesRequests, setAfterSalesRequests] = useState<AfterSalesRequest[]>([]);
  const [afterSalesSearchTerm, setAfterSalesSearchTerm] = useState("");
  const [afterSalesFilter, setAfterSalesFilter] = useState("all");

  // Coupons state
  const [coupons, setCoupons] = useState<UserCoupon[]>([]);
  const [couponTab, setCouponTab] = useState("unused");

  useEffect(() => {
    if (profile) {
      setFormData({
        display_name: profile.display_name || "",
        bio: profile.bio || "",
        phone: profile.phone || "",
        avatar_url: profile.avatar_url || ""
      });
    }
  }, [profile]);

  useEffect(() => {
    if (defaultTab) {
      setActiveTab(defaultTab);
    }
  }, [defaultTab]);

  useEffect(() => {
    if (user && open) {
      if (activeTab === 'orders') {
        fetchOrders();
      } else if (activeTab === 'after-sales') {
        fetchAfterSalesRequests();
      } else if (activeTab === 'coupons') {
        fetchUserCoupons();
      }
    }
  }, [user, open, activeTab]);

  const handleSave = async () => {
    if (!user) return;
    
    setIsLoading(true);
    try {
      const { error } = await supabase
        .from('profiles')
        .update({
          display_name: formData.display_name,
          bio: formData.bio,
          phone: formData.phone,
        })
        .eq('user_id', user.id);

      if (error) throw error;

      toast({
        title: "个人资料更新成功",
        description: "您的个人信息已保存"
      });

      setIsEditing(false);
      refreshProfile();
    } catch (error: any) {
      toast({
        title: "更新失败",
        description: error.message || "请稍后重试",
        variant: "destructive"
      });
    }
    setIsLoading(false);
  };

  const handleCancel = () => {
    if (profile) {
      setFormData({
        display_name: profile.display_name || "",
        bio: profile.bio || "",
        phone: profile.phone || "",
        avatar_url: profile.avatar_url || ""
      });
    }
    setIsEditing(false);
  };

  const handleChangeEmail = async () => {
    if (!newEmail || !user) return;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(newEmail)) {
      toast({ title: "邮箱格式不正确", description: "请输入有效的邮箱地址", variant: "destructive" });
      return;
    }
    if (newEmail === user.email) {
      toast({ title: "邮箱未改变", description: "新邮箱地址与当前邮箱相同" });
      return;
    }
    setEmailLoading(true);
    try {
      const { error } = await supabase.auth.updateUser({ email: newEmail });
      if (error) throw error;
      toast({
        title: "验证邮件已发送",
        description: `请前往 ${newEmail} 查收验证邮件，点击链接后邮箱即可生效`,
      });
      setIsChangingEmail(false);
      setNewEmail("");
    } catch (error: any) {
      toast({
        title: "修改失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    }
    setEmailLoading(false);
  };

  // Orders functions
  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);
    }
  };

  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) {
        setOrderCoupon(couponData);
      }
    } catch (error) {
      console.error("Error fetching order items:", error);
    }
  };

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

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

  // After-sales functions
  const fetchAfterSalesRequests = async () => {
    if (!user) return;
    
    try {
      const { data, error } = await supabase
        .from('after_sales_requests')
        .select('*')
        .eq('user_id', user.id)
        .order('created_at', { ascending: false });

      if (error) throw error;
      
      const requestsWithDetails = await Promise.all((data || []).map(async (request) => {
        const { data: orderData } = await supabase
          .from('orders')
          .select('order_number')
          .eq('id', request.order_id)
          .single();

        const { data: productData } = await supabase
          .from('products')
          .select('name, image_url')
          .eq('id', request.product_id)
          .single();

        return {
          ...request,
          orderNumber: orderData?.order_number || '',
          productName: productData?.name || '',
          productImage: productData?.image_url || '',
        };
      }));
      
      setAfterSalesRequests(requestsWithDetails as AfterSalesRequest[]);
    } catch (error) {
      console.error('获取售后申请失败:', error);
    }
  };

  // Coupons functions
  const fetchUserCoupons = async () => {
    if (!user) return;

    try {
      const { data, error } = await supabase
        .from('user_coupons')
        .select(`
          id,
          coupon_id,
          status,
          received_at,
          used_at,
          coupons (
            code,
            name,
            description,
            type,
            discount_value,
            min_purchase_amount,
            max_discount_amount,
            start_date,
            end_date
          )
        `)
        .eq('user_id', user.id)
        .order('received_at', { ascending: false });

      if (error) throw error;

      const formattedCoupons = (data || []).map((item: any) => ({
        id: item.id,
        coupon_id: item.coupon_id,
        status: item.status,
        received_at: item.received_at,
        used_at: item.used_at,
        coupon: item.coupons
      }));

      setCoupons(formattedCoupons);
    } catch (error: any) {
      console.error('获取优惠券失败:', error);
    }
  };

  // Helper functions
  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 getAfterSalesStatusText = (status: string) => {
    switch (status) {
      case "pending": return "待审核";
      case "approved": return "已审核";
      case "processing": return "处理中";
      case "completed": return "已完成";
      case "rejected": return "已拒绝";
      default: return status;
    }
  };

  const getAfterSalesTypeText = (type: string) => {
    switch (type) {
      case "return": return "退货";
      case "exchange": return "换货";
      case "repair": return "维修";
      default: return type;
    }
  };

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

  const formatDiscount = (type: string, value: number) => {
    if (type === 'percentage') {
      return `${value}折`;
    }
    return `¥${value}`;
  };

  const isExpired = (endDate: string) => {
    return new Date(endDate) < new Date();
  };

  const getCouponStatusBadge = (status: string, endDate: string) => {
    if (isExpired(endDate)) {
      return <Badge variant="secondary" className="bg-muted text-muted-foreground">已过期</Badge>;
    }
    
    switch (status) {
      case 'unused':
        return <Badge variant="default" className="bg-success text-success-foreground">未使用</Badge>;
      case 'used':
        return <Badge variant="secondary">已使用</Badge>;
      case 'expired':
        return <Badge variant="secondary" className="bg-muted text-muted-foreground">已过期</Badge>;
      default:
        return <Badge variant="secondary">{status}</Badge>;
    }
  };

  if (!user) {
    return null;
  }

  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]">
            <Card className="border-border shadow-lg">
              <CardHeader className="text-center pb-4">
                <div className="flex flex-col items-center space-y-4">
                  <Avatar className="h-24 w-24">
                    <AvatarFallback className="bg-primary text-primary-foreground text-2xl font-bold">
                      {profile?.display_name?.[0]?.toUpperCase() || user?.email?.[0]?.toUpperCase() || "U"}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <h3 className="text-xl font-semibold text-foreground">
                      {profile?.display_name || "未设置昵称"}
                    </h3>
                    <p className="text-sm text-muted-foreground">{user.email}</p>
                  </div>
                  <div className="flex items-center space-x-2">
                    <div className="w-2 h-2 bg-success rounded-full"></div>
                    <span className="text-sm text-success font-medium">在线</span>
                  </div>
                </div>
              </CardHeader>
              
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">角色</span>
                  <Badge variant="secondary">{profile?.role || "用户"}</Badge>
                </div>
                
                <Separator />
                
                <div className="space-y-3">
                  <div className="flex items-center space-x-3 text-sm">
                    <Calendar className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <p className="text-muted-foreground">注册时间</p>
                      <p className="font-medium text-xs">
                        {profile?.created_at ? format(new Date(profile.created_at), "yyyy年MM月dd日") : "未知"}
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex items-center space-x-3 text-sm">
                    <Clock className="h-4 w-4 text-muted-foreground" />
                    <div>
                      <p className="text-muted-foreground">最后登录</p>
                      <p className="font-medium text-xs">
                        {profile?.last_login ? format(new Date(profile.last_login), "yyyy年MM月dd日") : "未记录"}
                      </p>
                    </div>
                  </div>
                </div>
                
                {isAdmin && (
                  <>
                    <Separator />
                    <Button 
                      onClick={() => {
                        onOpenChange(false);
                        navigate('/admin');
                      }} 
                      variant="outline" 
                      size="sm"
                      className="w-full flex items-center space-x-2"
                    >
                      <Settings className="h-4 w-4" />
                      <span>管理后台</span>
                    </Button>
                  </>
                )}
              </CardContent>
            </Card>
          </div>

          {/* 右侧详细内容 */}
          <div className="col-span-9 p-6 overflow-y-auto max-h-[90vh]">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
              <TabsList className="grid w-full grid-cols-6">
                <TabsTrigger value="profile">个人信息</TabsTrigger>
                <TabsTrigger value="security">安全设置</TabsTrigger>
                <TabsTrigger value="preferences">偏好设置</TabsTrigger>
                <TabsTrigger value="orders">我的订单</TabsTrigger>
                <TabsTrigger value="after-sales">售后服务</TabsTrigger>
                <TabsTrigger value="coupons">我的优惠券</TabsTrigger>
              </TabsList>

              <TabsContent value="profile">
                <Card className="border-border shadow-lg">
                  <CardHeader className="flex flex-row items-center justify-between">
                    <CardTitle className="text-xl">个人信息</CardTitle>
                    {!isEditing ? (
                      <Button onClick={() => setIsEditing(true)} variant="outline" size="sm">
                        <Edit3 className="h-4 w-4 mr-2" />
                        编辑
                      </Button>
                    ) : (
                      <div className="flex space-x-2">
                        <Button onClick={handleSave} size="sm" disabled={isLoading}>
                          <Save className="h-4 w-4 mr-2" />
                          {isLoading ? "保存中..." : "保存"}
                        </Button>
                        <Button onClick={handleCancel} variant="outline" size="sm">
                          <X className="h-4 w-4 mr-2" />
                          取消
                        </Button>
                      </div>
                    )}
                  </CardHeader>
                  
                  <CardContent className="space-y-6">
                    <div className="grid grid-cols-2 gap-6">
                      <div className="space-y-2">
                        <Label htmlFor="display_name">显示名称</Label>
                        <div className="relative">
                          <User className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                          <Input
                            id="display_name"
                            value={formData.display_name}
                            onChange={(e) => setFormData({...formData, display_name: e.target.value})}
                            className="pl-10"
                            placeholder="请输入您的昵称"
                            disabled={!isEditing}
                          />
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="email" className="flex items-center justify-between">
                          <span>邮箱地址</span>
                          {!isChangingEmail && (
                            <Button
                              variant="link"
                              size="sm"
                              className="h-auto p-0 text-xs"
                              onClick={() => {
                                setNewEmail("");
                                setIsChangingEmail(true);
                              }}
                            >
                              修改
                            </Button>
                          )}
                        </Label>
                        {isChangingEmail ? (
                          <div className="space-y-2">
                            <div className="relative">
                              <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                              <Input
                                id="new_email"
                                type="email"
                                value={newEmail}
                                onChange={(e) => setNewEmail(e.target.value)}
                                className="pl-10"
                                placeholder="请输入新邮箱地址"
                                autoFocus
                              />
                            </div>
                            <p className="text-xs text-muted-foreground flex items-center gap-1">
                              <AlertCircle className="h-3 w-3" />
                              修改后需前往新邮箱验证才能生效
                            </p>
                            <div className="flex gap-2">
                              <Button size="sm" onClick={handleChangeEmail} disabled={emailLoading}>
                                确认修改
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => {
                                  setIsChangingEmail(false);
                                  setNewEmail("");
                                }}
                              >
                                取消
                              </Button>
                            </div>
                          </div>
                        ) : (
                          <div className="relative">
                            <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                            <Input
                              id="email"
                              value={user.email || ""}
                              className="pl-10 bg-muted"
                              disabled
                            />
                          </div>
                        )}
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="phone">手机号码</Label>
                        <div className="relative">
                          <Phone className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                          <Input
                            id="phone"
                            value={formData.phone}
                            onChange={(e) => setFormData({...formData, phone: e.target.value})}
                            className="pl-10"
                            placeholder="请输入手机号码"
                            disabled={!isEditing}
                          />
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label>邮箱验证状态</Label>
                        <div className="flex items-center space-x-2">
                          <Badge variant={profile?.email_verified ? "default" : "secondary"}>
                            {profile?.email_verified ? "已验证" : "未验证"}
                          </Badge>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="bio">个人简介</Label>
                      <Textarea
                        id="bio"
                        value={formData.bio}
                        onChange={(e) => setFormData({...formData, bio: e.target.value})}
                        placeholder="介绍一下您自己..."
                        rows={4}
                        disabled={!isEditing}
                        className="resize-none"
                      />
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="security">
                <Card className="border-border shadow-lg">
                  <CardHeader>
                    <CardTitle className="text-xl flex items-center space-x-2">
                      <Shield className="h-5 w-5" />
                      <span>安全设置</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <Alert>
                      <Shield className="h-4 w-4" />
                      <AlertDescription>
                        保护您的账户安全，定期更新密码和验证方式
                      </AlertDescription>
                    </Alert>

                    <div className="space-y-4">
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <h4 className="font-medium">修改密码</h4>
                          <p className="text-sm text-muted-foreground">定期更新密码以保护账户安全</p>
                        </div>
                        <Button variant="outline">修改</Button>
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <h4 className="font-medium">两步验证</h4>
                          <p className="text-sm text-muted-foreground">为账户添加额外的安全保护</p>
                        </div>
                        <Badge variant="secondary">未启用</Badge>
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <h4 className="font-medium">登录设备管理</h4>
                          <p className="text-sm text-muted-foreground">查看和管理所有登录设备</p>
                        </div>
                        <Button variant="outline">管理</Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="preferences">
                <Card className="border-border shadow-lg">
                  <CardHeader>
                    <CardTitle className="text-xl">偏好设置</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="space-y-4">
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Bell className="h-5 w-5 text-muted-foreground" />
                          <div>
                            <h4 className="font-medium">消息通知</h4>
                            <p className="text-sm text-muted-foreground">接收订单和系统消息通知</p>
                          </div>
                        </div>
                        <Badge variant="default">已开启</Badge>
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Mail className="h-5 w-5 text-muted-foreground" />
                          <div>
                            <h4 className="font-medium">邮件通知</h4>
                            <p className="text-sm text-muted-foreground">接收促销和活动信息邮件</p>
                          </div>
                        </div>
                        <Badge variant="secondary">已关闭</Badge>
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Globe className="h-5 w-5 text-muted-foreground" />
                          <div>
                            <h4 className="font-medium">语言设置</h4>
                            <p className="text-sm text-muted-foreground">选择您的首选语言</p>
                          </div>
                        </div>
                        <Badge variant="outline">简体中文</Badge>
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Moon className="h-5 w-5 text-muted-foreground" />
                          <div>
                            <h4 className="font-medium">主题模式</h4>
                            <p className="text-sm text-muted-foreground">自动跟随系统或手动选择</p>
                          </div>
                        </div>
                        <Badge variant="outline">跟随系统</Badge>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* 我的订单 Tab */}
              <TabsContent value="orders">
                {!selectedOrder ? (
                  <Card className="border-border shadow-lg">
                    <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 space-x-2">
                          <Search className="h-4 w-4 text-muted-foreground" />
                          <Input
                            placeholder="搜索订单号或快递单号..."
                            value={orderSearchTerm}
                            onChange={(e) => setOrderSearchTerm(e.target.value)}
                            className="w-64"
                          />
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-4 mb-4">
                        <Select value={statusFilter} onValueChange={setStatusFilter}>
                          <SelectTrigger className="w-[200px]">
                            <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>

                      {orders.filter(order => {
                        const matchesSearch = 
                          order.order_number.toLowerCase().includes(orderSearchTerm.toLowerCase()) ||
                          order.tracking_number?.toLowerCase().includes(orderSearchTerm.toLowerCase());
                        const matchesStatus = statusFilter === "all" || order.status === statusFilter;
                        return matchesSearch && matchesStatus;
                      }).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">暂无订单</h3>
                          <p className="text-muted-foreground">开始购物，创建您的第一个订单</p>
                        </div>
                      ) : (
                        <div className="space-y-4">
                          {orders.filter(order => {
                            const matchesSearch = 
                              order.order_number.toLowerCase().includes(orderSearchTerm.toLowerCase()) ||
                              order.tracking_number?.toLowerCase().includes(orderSearchTerm.toLowerCase());
                            const matchesStatus = statusFilter === "all" || order.status === statusFilter;
                            return matchesSearch && matchesStatus;
                          }).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 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>
                        <p className="text-sm text-muted-foreground">订单号: {selectedOrder.order_number}</p>
                      </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 className="flex items-center gap-2 mb-2">
                              <Ticket className="h-4 w-4" />
                              使用的优惠券
                            </Label>
                            <div className="p-3 bg-primary/5 rounded-lg border border-primary/20">
                              <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="secondary">
                                  {orderCoupon.coupons.type === 'percentage' 
                                    ? `${orderCoupon.coupons.discount_value}折` 
                                    : `¥${orderCoupon.coupons.discount_value}`}
                                </Badge>
                              </div>
                            </div>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  </div>
                )}
              </TabsContent>

              {/* 售后服务 Tab */}
              <TabsContent value="after-sales">
                <Card className="border-border shadow-lg">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="flex items-center gap-2">
                        <RotateCcw className="h-5 w-5" />
                        售后服务
                      </CardTitle>
                      <div className="flex items-center space-x-2">
                        <Search className="h-4 w-4 text-muted-foreground" />
                        <Input
                          placeholder="搜索订单号或商品名称..."
                          value={afterSalesSearchTerm}
                          onChange={(e) => setAfterSalesSearchTerm(e.target.value)}
                          className="w-64"
                        />
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-center gap-4 mb-4">
                      <Select value={afterSalesFilter} onValueChange={setAfterSalesFilter}>
                        <SelectTrigger className="w-[200px]">
                          <Filter className="w-4 h-4 mr-2" />
                          <SelectValue placeholder="状态筛选" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="all">全部状态</SelectItem>
                          <SelectItem value="pending">待审核</SelectItem>
                          <SelectItem value="processing">处理中</SelectItem>
                          <SelectItem value="completed">已完成</SelectItem>
                          <SelectItem value="rejected">已拒绝</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    {afterSalesRequests.filter(request => {
                      const matchesSearch = (request.orderNumber || '').toLowerCase().includes(afterSalesSearchTerm.toLowerCase()) ||
                                           (request.productName || '').toLowerCase().includes(afterSalesSearchTerm.toLowerCase());
                      const matchesFilter = afterSalesFilter === "all" || request.status === afterSalesFilter;
                      return matchesSearch && matchesFilter;
                    }).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">暂无售后申请</h3>
                        <p className="text-muted-foreground">您还没有提交过售后申请</p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {afterSalesRequests.filter(request => {
                          const matchesSearch = (request.orderNumber || '').toLowerCase().includes(afterSalesSearchTerm.toLowerCase()) ||
                                               (request.productName || '').toLowerCase().includes(afterSalesSearchTerm.toLowerCase());
                          const matchesFilter = afterSalesFilter === "all" || request.status === afterSalesFilter;
                          return matchesSearch && matchesFilter;
                        }).map((request) => (
                          <Card key={request.id} className="border border-border">
                            <CardContent className="p-6">
                              <div className="flex flex-col lg:flex-row gap-6">
                                <div className="flex gap-4">
                                  <div className="w-20 h-20 bg-muted rounded-lg flex items-center justify-center">
                                    <Package className="h-10 w-10 text-muted-foreground" />
                                  </div>
                                  <div className="flex-1">
                                    <h3 className="font-semibold text-foreground">{request.productName}</h3>
                                    <p className="text-sm text-muted-foreground">订单号: {request.orderNumber}</p>
                                    <p className="text-sm text-muted-foreground">
                                      金额: ¥{request.refund_amount?.toFixed(2) || '0.00'}
                                    </p>
                                  </div>
                                </div>

                                <div className="flex-1 space-y-3">
                                  <div className="flex flex-wrap gap-2">
                                    <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
                                      {getAfterSalesTypeText(request.type)}
                                    </Badge>
                                    <Badge variant="secondary">
                                      {getAfterSalesStatusText(request.status)}
                                    </Badge>
                                  </div>
                                  
                                  <div>
                                    <p className="text-sm font-medium">申请原因: {request.reason}</p>
                                    <p className="text-sm text-muted-foreground mt-1">{request.description}</p>
                                  </div>

                                  <div className="flex justify-between text-xs text-muted-foreground">
                                    <span>申请时间: {formatDate(request.created_at)}</span>
                                    <span>更新时间: {formatDate(request.updated_at)}</span>
                                  </div>
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    )}
                  </CardContent>
                </Card>
              </TabsContent>

              {/* 我的优惠券 Tab */}
              <TabsContent value="coupons">
                <Card className="border-border shadow-lg">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Ticket className="h-5 w-5" />
                      我的优惠券
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Tabs value={couponTab} onValueChange={setCouponTab}>
                      <TabsList className="grid w-full grid-cols-3 mb-6">
                        <TabsTrigger value="unused">
                          未使用 ({coupons.filter(c => c.status === 'unused' && !isExpired(c.coupon.end_date)).length})
                        </TabsTrigger>
                        <TabsTrigger value="used">
                          已使用 ({coupons.filter(c => c.status === 'used').length})
                        </TabsTrigger>
                        <TabsTrigger value="expired">
                          已过期 ({coupons.filter(c => c.status === 'expired' || (c.status === 'unused' && isExpired(c.coupon.end_date))).length})
                        </TabsTrigger>
                      </TabsList>

                      <TabsContent value="unused" className="space-y-4">
                        {coupons.filter(c => c.status === 'unused' && !isExpired(c.coupon.end_date)).length === 0 ? (
                          <div className="text-center py-12 text-muted-foreground">暂无可用优惠券</div>
                        ) : (
                          coupons.filter(c => c.status === 'unused' && !isExpired(c.coupon.end_date)).map(userCoupon => (
                            <Card key={userCoupon.id} className="border-border transition-all hover:shadow-md">
                              <CardContent className="p-6">
                                <div className="flex flex-col sm:flex-row gap-4">
                                  <div className="flex items-center justify-center sm:justify-start p-4 bg-gradient-to-br from-primary/10 to-primary/5 rounded-lg min-w-[120px]">
                                    <div className="text-center">
                                      <div className="text-3xl font-bold text-primary mb-1">
                                        {formatDiscount(userCoupon.coupon.type, userCoupon.coupon.discount_value)}
                                      </div>
                                      <div className="text-xs text-muted-foreground">
                                        {userCoupon.coupon.type === 'percentage' ? '折扣' : '立减'}
                                      </div>
                                    </div>
                                  </div>

                                  <div className="flex-1 space-y-2">
                                    <div className="flex items-start justify-between gap-2">
                                      <div>
                                        <h3 className="font-semibold text-lg text-foreground">{userCoupon.coupon.name}</h3>
                                        {userCoupon.coupon.description && (
                                          <p className="text-sm text-muted-foreground mt-1">{userCoupon.coupon.description}</p>
                                        )}
                                      </div>
                                      {getCouponStatusBadge(userCoupon.status, userCoupon.coupon.end_date)}
                                    </div>

                                    <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                                      {userCoupon.coupon.min_purchase_amount && (
                                        <div>满 ¥{userCoupon.coupon.min_purchase_amount} 可用</div>
                                      )}
                                      {userCoupon.coupon.max_discount_amount && userCoupon.coupon.type === 'percentage' && (
                                        <div>最高优惠 ¥{userCoupon.coupon.max_discount_amount}</div>
                                      )}
                                    </div>

                                    <div className="flex flex-col sm:flex-row sm:items-center gap-2 text-xs text-muted-foreground pt-2 border-t border-border">
                                      <div className="flex items-center gap-1">
                                        <Ticket className="h-3 w-3" />
                                        <span>优惠码: {userCoupon.coupon.code}</span>
                                      </div>
                                      <div className="flex items-center gap-1">
                                        <Clock className="h-3 w-3" />
                                        <span>有效期至: {format(new Date(userCoupon.coupon.end_date), 'yyyy-MM-dd')}</span>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          ))
                        )}
                      </TabsContent>

                      <TabsContent value="used" className="space-y-4">
                        {coupons.filter(c => c.status === 'used').length === 0 ? (
                          <div className="text-center py-12 text-muted-foreground">暂无已使用优惠券</div>
                        ) : (
                          coupons.filter(c => c.status === 'used').map(userCoupon => (
                            <Card key={userCoupon.id} className="border-border">
                              <CardContent className="p-6">
                                <div className="flex flex-col sm:flex-row gap-4 opacity-75">
                                  <div className="flex items-center justify-center sm:justify-start p-4 bg-gradient-to-br from-muted to-muted/50 rounded-lg min-w-[120px]">
                                    <div className="text-center">
                                      <div className="text-3xl font-bold text-muted-foreground mb-1">
                                        {formatDiscount(userCoupon.coupon.type, userCoupon.coupon.discount_value)}
                                      </div>
                                      <div className="text-xs text-muted-foreground">已使用</div>
                                    </div>
                                  </div>

                                  <div className="flex-1 space-y-2">
                                    <h3 className="font-semibold text-lg text-foreground">{userCoupon.coupon.name}</h3>
                                    {userCoupon.used_at && (
                                      <div className="text-xs text-muted-foreground flex items-center gap-1">
                                        <CheckCircle className="h-3 w-3" />
                                        <span>使用时间: {format(new Date(userCoupon.used_at), 'yyyy-MM-dd HH:mm')}</span>
                                      </div>
                                    )}
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          ))
                        )}
                      </TabsContent>

                      <TabsContent value="expired" className="space-y-4">
                        {coupons.filter(c => c.status === 'expired' || (c.status === 'unused' && isExpired(c.coupon.end_date))).length === 0 ? (
                          <div className="text-center py-12 text-muted-foreground">暂无已过期优惠券</div>
                        ) : (
                          coupons.filter(c => c.status === 'expired' || (c.status === 'unused' && isExpired(c.coupon.end_date))).map(userCoupon => (
                            <Card key={userCoupon.id} className="border-border opacity-60">
                              <CardContent className="p-6">
                                <div className="flex flex-col sm:flex-row gap-4">
                                  <div className="flex items-center justify-center sm:justify-start p-4 bg-muted rounded-lg min-w-[120px]">
                                    <div className="text-center">
                                      <div className="text-3xl font-bold text-muted-foreground mb-1">
                                        {formatDiscount(userCoupon.coupon.type, userCoupon.coupon.discount_value)}
                                      </div>
                                      <div className="text-xs text-muted-foreground">已过期</div>
                                    </div>
                                  </div>

                                  <div className="flex-1 space-y-2">
                                    <h3 className="font-semibold text-lg text-muted-foreground">{userCoupon.coupon.name}</h3>
                                    <div className="text-xs text-muted-foreground flex items-center gap-1">
                                      <XCircle className="h-3 w-3" />
                                      <span>过期时间: {format(new Date(userCoupon.coupon.end_date), 'yyyy-MM-dd')}</span>
                                    </div>
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          ))
                        )}
                      </TabsContent>
                    </Tabs>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}