import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { CalendarDays, Mail, Phone, User, ShoppingBag, MessageSquare, TrendingUp, Target, Star, Award } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

interface UserDetailDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  userId: string;
  userDisplayName: string;
  userAvatarUrl?: string;
}

interface UserStats {
  totalOrders: number;
  totalSpent: number;
  totalConversations: number;
  totalMessages: number;
}

export function UserDetailDialog({
  isOpen,
  onOpenChange,
  userId,
  userDisplayName,
  userAvatarUrl,
}: UserDetailDialogProps) {
  const [userProfile, setUserProfile] = useState<any>(null);
  const [userStats, setUserStats] = useState<UserStats>({
    totalOrders: 0,
    totalSpent: 0,
    totalConversations: 0,
    totalMessages: 0,
  });
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    if (isOpen && userId) {
      fetchUserDetails();
    }
  }, [isOpen, userId]);

  const fetchUserDetails = async () => {
    try {
      setLoading(true);
      
      // Fetch user profile
      const { data: profile, error: profileError } = await supabase
        .from("profiles")
        .select("*")
        .eq("user_id", userId)
        .single();

      if (profileError) throw profileError;
      setUserProfile(profile);

      // Fetch user statistics
      const [ordersResult, conversationsResult, messagesResult] = await Promise.all([
        supabase
          .from("orders")
          .select("total_amount")
          .eq("user_id", userId),
        supabase
          .from("conversations")
          .select("id")
          .eq("user_id", userId),
        supabase
          .from("messages")
          .select("id")
          .eq("user_id", userId),
      ]);

      const orders = ordersResult.data || [];
      const conversations = conversationsResult.data || [];
      const messages = messagesResult.data || [];

      const totalSpent = orders.reduce((sum, order) => sum + parseFloat(String(order.total_amount || "0")), 0);

      setUserStats({
        totalOrders: orders.length,
        totalSpent,
        totalConversations: conversations.length,
        totalMessages: messages.length,
      });
    } catch (error) {
      console.error("Error fetching user details:", error);
      toast({
        title: "错误",
        description: "获取用户详情失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

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

  const getRoleBadgeVariant = (role: string | null) => {
    switch (role) {
      case "admin":
        return "destructive";
      case "moderator":
        return "default";
      default:
        return "secondary";
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("zh-CN", {
      style: "currency",
      currency: "CNY",
    }).format(amount);
  };

  // Calculate user profile insights
  const getUserLevel = () => {
    if (userStats.totalSpent >= 10000) return { level: "VIP", color: "text-yellow-600", icon: Award };
    if (userStats.totalSpent >= 5000) return { level: "高级会员", color: "text-purple-600", icon: Star };
    if (userStats.totalSpent >= 1000) return { level: "活跃用户", color: "text-blue-600", icon: TrendingUp };
    return { level: "普通用户", color: "text-muted-foreground", icon: User };
  };

  const getActivityLevel = () => {
    const totalActivity = userStats.totalMessages + userStats.totalOrders;
    if (totalActivity >= 100) return { level: "非常活跃", score: 95, color: "bg-green-500" };
    if (totalActivity >= 50) return { level: "活跃", score: 75, color: "bg-blue-500" };
    if (totalActivity >= 20) return { level: "一般", score: 50, color: "bg-yellow-500" };
    return { level: "较少活跃", score: 25, color: "bg-muted-foreground" };
  };

  const getUserTags = () => {
    const tags = [];
    if (userStats.totalOrders > 10) tags.push({ label: "忠实客户", variant: "default" as const });
    if (userStats.totalSpent > 5000) tags.push({ label: "高消费", variant: "default" as const });
    if (userStats.totalMessages > 50) tags.push({ label: "互动活跃", variant: "secondary" as const });
    if (userStats.totalConversations > 20) tags.push({ label: "咨询频繁", variant: "secondary" as const });
    if (userStats.totalOrders === 0) tags.push({ label: "潜在客户", variant: "outline" as const });
    const avgOrderValue = userStats.totalOrders > 0 ? userStats.totalSpent / userStats.totalOrders : 0;
    if (avgOrderValue > 1000) tags.push({ label: "高客单价", variant: "default" as const });
    return tags;
  };

  const userLevel = getUserLevel();
  const activityLevel = getActivityLevel();
  const userTags = getUserTags();

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>用户详情</DialogTitle>
          <DialogDescription>
            查看用户的详细信息和统计数据
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <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>
        ) : (
          <div className="space-y-6">
            {/* User Profile Section */}
            <Card>
              <CardHeader>
                <div className="flex items-center space-x-4">
                  <Avatar className="h-16 w-16">
                    <AvatarImage src={userAvatarUrl || userProfile?.avatar_url} />
                    <AvatarFallback className="text-lg">
                      {userDisplayName?.charAt(0) || "U"}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1">
                    <h3 className="text-xl font-semibold">
                      {userProfile?.display_name || "未设置"}
                    </h3>
                    <p className="text-muted-foreground">
                      用户ID: {userId}
                    </p>
                    <Badge variant={getRoleBadgeVariant(userProfile?.role)} className="mt-2">
                      {userProfile?.role === "admin" ? "管理员" : 
                       userProfile?.role === "moderator" ? "管理员" : "普通用户"}
                    </Badge>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="flex items-center space-x-2">
                    <Phone className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm">
                      {userProfile?.phone || "未设置"}
                    </span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Mail className="w-4 h-4 text-muted-foreground" />
                    <Badge variant={userProfile?.email_verified ? "default" : "secondary"}>
                      {userProfile?.email_verified ? "邮箱已验证" : "邮箱未验证"}
                    </Badge>
                  </div>
                  <div className="flex items-center space-x-2">
                    <CalendarDays className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm">
                      注册时间: {formatDate(userProfile?.created_at)}
                    </span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <User className="w-4 h-4 text-muted-foreground" />
                    <span className="text-sm">
                      最后登录: {userProfile?.last_login ? formatDate(userProfile.last_login) : "从未登录"}
                    </span>
                  </div>
                </div>
                
                {userProfile?.bio && (
                  <>
                    <Separator />
                    <div>
                      <h4 className="text-sm font-medium mb-2">个人简介</h4>
                      <p className="text-sm text-muted-foreground">
                        {userProfile.bio}
                      </p>
                    </div>
                  </>
                )}
              </CardContent>
            </Card>

            {/* User Statistics */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">用户统计</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="text-center p-4 border rounded-lg">
                    <ShoppingBag className="w-8 h-8 mx-auto mb-2 text-primary" />
                    <div className="text-2xl font-bold">{userStats.totalOrders}</div>
                    <div className="text-sm text-muted-foreground">订单数量</div>
                  </div>
                  <div className="text-center p-4 border rounded-lg">
                    <div className="text-2xl font-bold text-green-600">
                      {formatCurrency(userStats.totalSpent)}
                    </div>
                    <div className="text-sm text-muted-foreground">总消费</div>
                  </div>
                  <div className="text-center p-4 border rounded-lg">
                    <MessageSquare className="w-8 h-8 mx-auto mb-2 text-blue-600" />
                    <div className="text-2xl font-bold">{userStats.totalConversations}</div>
                    <div className="text-sm text-muted-foreground">对话数量</div>
                  </div>
                  <div className="text-center p-4 border rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">
                      {userStats.totalMessages}
                    </div>
                    <div className="text-sm text-muted-foreground">消息数量</div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* User Profile Analysis */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <Target className="w-5 h-5 text-primary" />
                  用户画像
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* User Level */}
                <div className="flex items-center justify-between p-4 border rounded-lg bg-muted/30">
                  <div className="flex items-center gap-3">
                    <userLevel.icon className={`w-8 h-8 ${userLevel.color}`} />
                    <div>
                      <div className="font-semibold">用户等级</div>
                      <div className={`text-sm ${userLevel.color}`}>{userLevel.level}</div>
                    </div>
                  </div>
                  <Badge variant="outline" className="text-base">
                    {userStats.totalOrders > 0 
                      ? `平均客单价: ${formatCurrency(userStats.totalSpent / userStats.totalOrders)}`
                      : "暂无订单"}
                  </Badge>
                </div>

                {/* Activity Level */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium">活跃度评分</span>
                    <span className="text-sm text-muted-foreground">{activityLevel.level}</span>
                  </div>
                  <div className="w-full bg-muted rounded-full h-3 overflow-hidden">
                    <div 
                      className={`h-full ${activityLevel.color} transition-all duration-500`}
                      style={{ width: `${activityLevel.score}%` }}
                    />
                  </div>
                  <div className="text-xs text-muted-foreground mt-1">
                    基于消息互动和订单数量综合评估
                  </div>
                </div>

                {/* User Tags */}
                <div>
                  <h4 className="text-sm font-medium mb-3">用户标签</h4>
                  {userTags.length > 0 ? (
                    <div className="flex flex-wrap gap-2">
                      {userTags.map((tag, index) => (
                        <Badge key={index} variant={tag.variant}>
                          {tag.label}
                        </Badge>
                      ))}
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground">暂无标签数据</p>
                  )}
                </div>

                {/* Insights */}
                <div className="pt-4 border-t">
                  <h4 className="text-sm font-medium mb-3">洞察分析</h4>
                  <div className="space-y-2 text-sm">
                    {userStats.totalOrders > 5 && (
                      <div className="flex items-start gap-2">
                        <div className="w-1.5 h-1.5 rounded-full bg-primary mt-1.5" />
                        <p className="text-muted-foreground">
                          已完成 {userStats.totalOrders} 笔订单，展现出良好的购买意愿
                        </p>
                      </div>
                    )}
                    {userStats.totalMessages > 30 && (
                      <div className="flex items-start gap-2">
                        <div className="w-1.5 h-1.5 rounded-full bg-blue-600 mt-1.5" />
                        <p className="text-muted-foreground">
                          互动消息较多，对产品咨询比较积极
                        </p>
                      </div>
                    )}
                    {userStats.totalSpent > 3000 && (
                      <div className="flex items-start gap-2">
                        <div className="w-1.5 h-1.5 rounded-full bg-green-600 mt-1.5" />
                        <p className="text-muted-foreground">
                          累计消费金额较高，属于高价值客户
                        </p>
                      </div>
                    )}
                    {userStats.totalOrders === 0 && userStats.totalMessages > 0 && (
                      <div className="flex items-start gap-2">
                        <div className="w-1.5 h-1.5 rounded-full bg-yellow-600 mt-1.5" />
                        <p className="text-muted-foreground">
                          有咨询互动但尚未下单，可能需要促销激励
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}