import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { ShieldOff, RefreshCw } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

interface AdminListDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  isSuperAdmin: boolean;
  onChanged?: () => void;
}

interface AdminRow {
  user_id: string;
  role: "admin" | "super_admin";
  display_name: string | null;
  phone: string | null;
  avatar_url: string | null;
  created_at: string | null;
}

export function AdminListDialog({ isOpen, onOpenChange, isSuperAdmin, onChanged }: AdminListDialogProps) {
  const [loading, setLoading] = useState(false);
  const [rows, setRows] = useState<AdminRow[]>([]);
  const [pendingId, setPendingId] = useState<string | null>(null);
  const { toast } = useToast();

  const fetchAdmins = async () => {
    setLoading(true);
    try {
      const { data: roles, error } = await supabase
        .from("user_roles")
        .select("user_id, role")
        .in("role", ["admin", "super_admin"]);
      if (error) throw error;

      const ids = Array.from(new Set((roles ?? []).map((r) => r.user_id)));
      const { data: profiles } = ids.length
        ? await supabase
            .from("profiles")
            .select("user_id, display_name, phone, avatar_url, created_at")
            .in("user_id", ids)
        : { data: [] as any[] };

      const profileMap: Record<string, any> = {};
      (profiles ?? []).forEach((p: any) => (profileMap[p.user_id] = p));

      // 优先 super_admin，再 admin；同 user 多角色取最高
      const merged: Record<string, AdminRow> = {};
      (roles ?? []).forEach((r: any) => {
        const existing = merged[r.user_id];
        const role = r.role as "admin" | "super_admin";
        if (!existing || role === "super_admin") {
          const p = profileMap[r.user_id] || {};
          merged[r.user_id] = {
            user_id: r.user_id,
            role,
            display_name: p.display_name ?? null,
            phone: p.phone ?? null,
            avatar_url: p.avatar_url ?? null,
            created_at: p.created_at ?? null,
          };
        }
      });

      const list = Object.values(merged).sort((a, b) => {
        if (a.role !== b.role) return a.role === "super_admin" ? -1 : 1;
        return (a.display_name || "").localeCompare(b.display_name || "");
      });
      setRows(list);
    } catch (e) {
      toast({
        title: "加载失败",
        description: e instanceof Error ? e.message : String(e),
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (isOpen) fetchAdmins();
  }, [isOpen]);

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

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <span>管理员列表</span>
            <Button variant="ghost" size="sm" onClick={fetchAdmins} disabled={loading}>
              <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
            </Button>
          </DialogTitle>
          <DialogDescription>
            当前系统所有管理员与超级管理员账号
            {isSuperAdmin ? "，超级管理员可一键撤销普通管理员权限。" : "。"}
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center p-8">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
          </div>
        ) : rows.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">暂无管理员数据</div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>用户</TableHead>
                <TableHead>角色</TableHead>
                <TableHead>手机号</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((row) => (
                <TableRow key={row.user_id}>
                  <TableCell>
                    <div className="flex items-center space-x-3">
                      <Avatar className="h-8 w-8">
                        <AvatarImage src={row.avatar_url || ""} />
                        <AvatarFallback>{row.display_name?.charAt(0) || "A"}</AvatarFallback>
                      </Avatar>
                      <div>
                        <div className="font-medium">{row.display_name || "未设置"}</div>
                        <div className="text-xs text-muted-foreground">
                          ID: {row.user_id.slice(0, 8)}...
                        </div>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    {row.role === "super_admin" ? (
                      <Badge variant="destructive">超级管理员</Badge>
                    ) : (
                      <Badge>管理员</Badge>
                    )}
                  </TableCell>
                  <TableCell>{row.phone || "-"}</TableCell>
                  <TableCell className="text-right">
                    {isSuperAdmin && row.role !== "super_admin" ? (
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={pendingId === row.user_id}
                        onClick={() => handleRevoke(row)}
                        className="flex items-center gap-2 ml-auto"
                      >
                        <ShieldOff className="w-4 h-4" />
                        撤销
                      </Button>
                    ) : (
                      <span className="text-xs text-muted-foreground">
                        {row.role === "super_admin" ? "受保护" : "无权限"}
                      </span>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </DialogContent>
    </Dialog>
  );
}
