import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { MessageSquare, Eye, Users, UserPlus, TrendingUp, Activity, ShieldPlus, ShieldOff, ShieldCheck } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { UserConversationsDialog } from "./UserConversationsDialog";
import { UserDetailDialog } from "./UserDetailDialog";
import { AdminListDialog } from "./AdminListDialog";

type AdminRole = "admin" | "super_admin";

interface UserProfile {
  id: string;
  user_id: string;
  display_name: string | null;
  avatar_url: string | null;
  bio: string | null;
  phone: string | null;
  role: string | null;
  email_verified: boolean | null;
  last_login: string | null;
  created_at: string;
  updated_at: string;
}

interface UserStats {
  totalUsers: number;
  newUsersToday: number;
  newUsersThisMonth: number;
  activeUsers: number;
}

export function UsersManager() {
  const [users, setUsers] = useState<UserProfile[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
  const [conversationsDialogOpen, setConversationsDialogOpen] = useState(false);
  const [userDetailDialogOpen, setUserDetailDialogOpen] = useState(false);
  const [adminRoles, setAdminRoles] = useState<Record<string, AdminRole[]>>({});
  const [isSuperAdmin, setIsSuperAdmin] = useState(false);
  const [roleActionPending, setRoleActionPending] = useState<string | null>(null);
  const [adminListOpen, setAdminListOpen] = useState(false);
  const [userStats, setUserStats] = useState<UserStats>({
    totalUsers: 0,
    newUsersToday: 0,
    newUsersThisMonth: 0,
    activeUsers: 0,
  });
  const { toast } = useToast();

  useEffect(() => {
    fetchUsers();
    fetchRolesContext();
  }, []);

  const fetchRolesContext = async () => {
    const { data: { user } } = await supabase.auth.getUser();
    const { data: rolesData } = await supabase
      .from("user_roles")
      .select("user_id, role")
      .in("role", ["admin", "super_admin"]);

    const map: Record<string, AdminRole[]> = {};
    (rolesData ?? []).forEach((r: any) => {
      map[r.user_id] = [...(map[r.user_id] ?? []), r.role as AdminRole];
    });
    setAdminRoles(map);
    if (user) setIsSuperAdmin((map[user.id] ?? []).includes("super_admin"));
  };

  const handleGrantAdmin = async (target: UserProfile) => {
    setRoleActionPending(target.user_id);
    try {
      const { data, error } = await supabase.functions.invoke("admin-team", {
        body: { operation: "grant_admin", params: { target_user_id: target.user_id, role: "admin" } },
      });
      if (error || (data as any)?.error) throw new Error((data as any)?.error || error?.message);
      toast({ title: "成功", description: `已将 ${target.display_name || target.phone || "该用户"} 设为管理员` });
      await fetchRolesContext();
    } catch (e) {
      toast({ title: "操作失败", description: e instanceof Error ? e.message : String(e), variant: "destructive" });
    } finally {
      setRoleActionPending(null);
    }
  };

  const handleRevokeAdmin = async (target: UserProfile) => {
    if (!confirm(`确认撤销 ${target.display_name || target.phone || "该用户"} 的管理员权限？`)) return;
    setRoleActionPending(target.user_id);
    try {
      const { data, error } = await supabase.functions.invoke("admin-team", {
        body: { operation: "revoke_admin", params: { target_user_id: target.user_id } },
      });
      if (error || (data as any)?.error) throw new Error((data as any)?.error || error?.message);
      toast({ title: "成功", description: "已撤销管理员权限" });
      await fetchRolesContext();
    } catch (e) {
      toast({ title: "操作失败", description: e instanceof Error ? e.message : String(e), variant: "destructive" });
    } finally {
      setRoleActionPending(null);
    }
  };


  const fetchUsers = async () => {
    try {
      const { data, error } = await supabase
        .from("profiles")
        .select("*")
        .order("created_at", { ascending: false });

      if (error) throw error;
      setUsers(data || []);
      
      // Calculate statistics
      const now = new Date();
      const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

      const stats: UserStats = {
        totalUsers: data?.length || 0,
        newUsersToday: data?.filter(u => new Date(u.created_at) >= todayStart).length || 0,
        newUsersThisMonth: data?.filter(u => new Date(u.created_at) >= monthStart).length || 0,
        activeUsers: data?.filter(u => u.last_login && new Date(u.last_login) >= thirtyDaysAgo).length || 0,
      };
      
      setUserStats(stats);
    } catch (error) {
      console.error("Error fetching users:", error);
      toast({
        title: "错误",
        description: "获取用户列表失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const filteredUsers = users.filter((user) =>
    user.display_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.phone?.includes(searchTerm) ||
    user.role?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "short",
      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 handleViewConversations = (user: UserProfile) => {
    setSelectedUser(user);
    setConversationsDialogOpen(true);
  };

  const handleViewUserDetail = (user: UserProfile) => {
    setSelectedUser(user);
    setUserDetailDialogOpen(true);
  };

  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">
      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总用户数</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{userStats.totalUsers}</div>
            <p className="text-xs text-muted-foreground">
              注册用户总数
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">今日新增</CardTitle>
            <UserPlus className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{userStats.newUsersToday}</div>
            <p className="text-xs text-muted-foreground">
              今天注册的新用户
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">本月新增</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{userStats.newUsersThisMonth}</div>
            <p className="text-xs text-muted-foreground">
              本月注册的新用户
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">活跃用户</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">{userStats.activeUsers}</div>
            <p className="text-xs text-muted-foreground">
              近30天活跃用户
            </p>
          </CardContent>
        </Card>
      </div>

      {/* User Table Card */}
      <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>用户管理</CardTitle>
            <CardDescription>查看和管理所有用户信息</CardDescription>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setAdminListOpen(true)}
              className="flex items-center gap-2"
            >
              <ShieldCheck className="w-4 h-4" />
              管理员列表
            </Button>
            <div className="w-72">
              <Input
                placeholder="搜索用户名、手机号或角色..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>用户</TableHead>
              <TableHead>角色</TableHead>
              <TableHead>手机号</TableHead>
              <TableHead>邮箱验证</TableHead>
              <TableHead>注册时间</TableHead>
              <TableHead>最后登录</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredUsers.map((user) => (
              <TableRow 
                key={user.id} 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleViewUserDetail(user)}
              >
                <TableCell>
                  <div className="flex items-center space-x-3">
                    <Avatar className="h-8 w-8">
                      <AvatarImage src={user.avatar_url || ""} />
                      <AvatarFallback>
                        {user.display_name?.charAt(0) || "U"}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <div className="font-medium">
                        {user.display_name || "未设置"}
                      </div>
                      <div className="text-sm text-muted-foreground">
                        ID: {user.user_id.slice(0, 8)}...
                      </div>
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  {(() => {
                    const roles = adminRoles[user.user_id] ?? [];
                    if (roles.includes("super_admin")) return <Badge variant="destructive">超级管理员</Badge>;
                    if (roles.includes("admin")) return <Badge>管理员</Badge>;
                    return <Badge variant="secondary">普通用户</Badge>;
                  })()}
                </TableCell>
                <TableCell>{user.phone || "-"}</TableCell>
                <TableCell>
                  <Badge variant={user.email_verified ? "default" : "secondary"}>
                    {user.email_verified ? "已验证" : "未验证"}
                  </Badge>
                </TableCell>
                <TableCell>{formatDate(user.created_at)}</TableCell>
                <TableCell>
                  {user.last_login ? formatDate(user.last_login) : "-"}
                </TableCell>
                <TableCell>
                  <div className="flex items-center gap-2 flex-wrap">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={(e) => { e.stopPropagation(); handleViewUserDetail(user); }}
                      className="flex items-center gap-2"
                    >
                      <Eye className="w-4 h-4" />
                      详情
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={(e) => { e.stopPropagation(); handleViewConversations(user); }}
                      className="flex items-center gap-2"
                    >
                      <MessageSquare className="w-4 h-4" />
                      对话
                    </Button>
                    {isSuperAdmin && (() => {
                      const roles = adminRoles[user.user_id] ?? [];
                      const isSuper = roles.includes("super_admin");
                      const isAdmin = roles.includes("admin");
                      if (isSuper) return null;
                      return isAdmin ? (
                        <Button
                          variant="outline"
                          size="sm"
                          disabled={roleActionPending === user.user_id}
                          onClick={(e) => { e.stopPropagation(); handleRevokeAdmin(user); }}
                          className="flex items-center gap-2"
                        >
                          <ShieldOff className="w-4 h-4" />
                          撤销管理员
                        </Button>
                      ) : (
                        <Button
                          variant="default"
                          size="sm"
                          disabled={roleActionPending === user.user_id}
                          onClick={(e) => { e.stopPropagation(); handleGrantAdmin(user); }}
                          className="flex items-center gap-2"
                        >
                          <ShieldPlus className="w-4 h-4" />
                          设为管理员
                        </Button>
                      );
                    })()}
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        
        {filteredUsers.length === 0 && (
          <div className="text-center py-8 text-muted-foreground">
            {searchTerm ? "没有找到匹配的用户" : "暂无用户数据"}
          </div>
        )}
      </CardContent>
    </Card>

      {selectedUser && (
        <>
          <UserConversationsDialog
            isOpen={conversationsDialogOpen}
            onOpenChange={setConversationsDialogOpen}
            userId={selectedUser.user_id}
            userDisplayName={selectedUser.display_name || "未设置"}
            userAvatarUrl={selectedUser.avatar_url || undefined}
          />
          <UserDetailDialog
            isOpen={userDetailDialogOpen}
            onOpenChange={setUserDetailDialogOpen}
            userId={selectedUser.user_id}
            userDisplayName={selectedUser.display_name || "未设置"}
            userAvatarUrl={selectedUser.avatar_url || undefined}
          />
        </>
      )}

      <AdminListDialog
        isOpen={adminListOpen}
        onOpenChange={setAdminListOpen}
        isSuperAdmin={isSuperAdmin}
        onChanged={fetchRolesContext}
      />
    </div>
  );
}