import React, { useState, useMemo, useRef } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
} from "@/components/ui/command";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import {
    Plus,
    Edit,
    Trash2,
    Loader2,
    Users,
    Check,
    ChevronsUpDown,
} from "lucide-react";
import {
    getTeamMembers,
    createTeamMember,
    updateTeamMember,
    deleteTeamMember
} from '../../Member/service';
import type {
    TeamMemberResponse,
    TeamMemberQuery
} from '../../Member/types';
import type { UserResponse } from '@/pages/System/User/List/types';

interface MemberManageDialogProps {
    open: boolean;
    teamId: number;
    teamName: string;
    ownerId?: number;
    users: UserResponse[];
    onOpenChange: (open: boolean) => void;
    onSuccess?: () => void;
}

/**
 * 团队成员管理对话框
 */
const MemberManageDialog: React.FC<MemberManageDialogProps> = ({
    open,
    teamId,
    teamName,
    ownerId,
    users,
    onOpenChange,
    onSuccess
}) => {
    const { toast } = useToast();
    const tableRef = useRef<PaginatedTableRef<TeamMemberResponse>>(null);
    const [memberData, setMemberData] = useState<TeamMemberResponse[]>([]);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [deleteRecord, setDeleteRecord] = useState<TeamMemberResponse | null>(null);
    const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
    const [popoverOpen, setPopoverOpen] = useState(false);
    const [adding, setAdding] = useState(false);
    const [editDialogOpen, setEditDialogOpen] = useState(false);
    const [editRecord, setEditRecord] = useState<TeamMemberResponse | null>(null);
    const [editRole, setEditRole] = useState('');

    // 包装 fetchFn
    const fetchData = async (query: TeamMemberQuery) => {
        const result = await getTeamMembers({
            ...query,
            teamId: teamId,
            userName: searchUserName || undefined,
        });
        setMemberData(result.content || []);
        return result;
    };

    // 切换用户选择
    const toggleUserSelection = (userId: number) => {
        setSelectedUserIds(prev => 
            prev.includes(userId) 
                ? prev.filter(id => id !== userId)
                : [...prev, userId]
        );
    };

    // 批量添加成员
    const handleBatchAdd = async () => {
        if (selectedUserIds.length === 0) {
            toast({
                variant: "destructive",
                title: "请选择成员",
                description: "至少选择一个用户进行添加",
            });
            return;
        }

        setAdding(true);
        try {
            // 并行创建所有成员关联
            await Promise.all(
                selectedUserIds.map(userId => {
                    const user = users.find(u => u.id === userId);
                    return createTeamMember({
                        teamId,
                        userId,
                        userName: user?.nickname || user?.username || '',
                        roleInTeam: '', // 批量添加时角色为空
                    });
                })
            );

            toast({
                title: "添加成功",
                description: `已成功添加 ${selectedUserIds.length} 个成员`,
            });
            
            setSelectedUserIds([]);
            setPopoverOpen(false);
            tableRef.current?.refresh();
            onSuccess?.();
        } catch (error) {
            console.error('批量添加失败:', error);
            toast({
                variant: "destructive",
                title: "添加失败",
                description: error instanceof Error ? error.message : '未知错误',
            });
        } finally {
            setAdding(false);
        }
    };

    // 编辑成员角色
    const handleEditClick = (record: TeamMemberResponse) => {
        setEditRecord(record);
        setEditRole(record.roleInTeam || '');
        setEditDialogOpen(true);
    };

    // 保存角色编辑
    const handleEditSave = async () => {
        if (!editRecord) return;

        try {
            await updateTeamMember(editRecord.id, {
                teamId,
                userId: editRecord.userId,
                userName: editRecord.userName || '',
                roleInTeam: editRole,
            });
            toast({
                title: "更新成功",
                description: `成员 "${editRecord.userName}" 的角色已更新`,
            });
            setEditDialogOpen(false);
            setEditRecord(null);
            setEditRole('');
            tableRef.current?.refresh();
            onSuccess?.();
        } catch (error) {
            console.error('更新失败:', error);
            toast({
                variant: "destructive",
                title: "更新失败",
                description: error instanceof Error ? error.message : '未知错误',
            });
        }
    };

    // 删除成员（打开确认对话框）
    const handleDeleteClick = (record: TeamMemberResponse) => {
        setDeleteRecord(record);
        setDeleteDialogOpen(true);
    };

    // 确认删除
    const handleDeleteConfirm = async () => {
        if (!deleteRecord) return;
        await deleteTeamMember(deleteRecord.id);
    };

    // 过滤出未加入的用户（排除负责人和已加入的成员）
    const availableUsers = users.filter(user => 
        user.id !== ownerId && !memberData.some(member => member.userId === user.id)
    );

    // 搜索状态
    const [searchUserName, setSearchUserName] = useState('');

    // 列定义
    const columns: ColumnDef<TeamMemberResponse>[] = useMemo(() => [
        { key: 'userId', title: '用户ID', dataIndex: 'userId', width: '100px' },
        { key: 'userName', title: '用户名', dataIndex: 'userName', width: '150px' },
        { key: 'roleInTeam', title: '团队角色', dataIndex: 'roleInTeam', width: '150px' },
        { key: 'joinTime', title: '加入时间', dataIndex: 'joinTime', width: '180px' },
        {
            key: 'actions',
            title: '操作',
            width: '120px',
            sticky: true,
            render: (_, record) => (
                <div className="flex items-center justify-end gap-1">
                    <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 w-8 p-0"
                        onClick={() => handleEditClick(record)}
                    >
                        <Edit className="h-3.5 w-3.5" />
                    </Button>
                    <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 w-8 p-0"
                        onClick={() => handleDeleteClick(record)}
                    >
                        <Trash2 className="h-3.5 w-3.5 text-destructive" />
                    </Button>
                </div>
            ),
        },
    ], []);

    return (
        <>
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-4xl max-h-[85vh] flex flex-col p-0">
                <DialogHeader className="px-6 pt-6 pb-4">
                    <DialogTitle className="flex items-center gap-2">
                        <Users className="h-5 w-5" />
                        团队成员管理 - {teamName}
                    </DialogTitle>
                </DialogHeader>

                    <div className="flex-1 overflow-hidden flex flex-col px-6 pb-6">
                        <div className="space-y-4 flex-1 overflow-y-auto">
                        {/* 操作栏 */}
                        <div className="flex items-center gap-2">
                            {/* 搜索框 */}
                            <Input
                                placeholder="搜索成员姓名..."
                                value={searchUserName}
                                onChange={(e) => setSearchUserName(e.target.value)}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        tableRef.current?.refresh();
                                    }
                                }}
                                className="flex-1"
                            />
                            
                            {/* 多选下拉框 */}
                            <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
                                <PopoverTrigger asChild>
                                    <Button
                                        variant="outline"
                                        role="combobox"
                                        aria-expanded={popoverOpen}
                                        className="w-[200px] justify-between"
                                        disabled={availableUsers.length === 0}
                                    >
                                        {selectedUserIds.length > 0 ? (
                                            <span className="flex items-center gap-1">
                                                已选择 <Badge variant="secondary" className="ml-1">{selectedUserIds.length}</Badge>
                                            </span>
                                        ) : (
                                            "选择成员..."
                                        )}
                                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                    </Button>
                                </PopoverTrigger>
                                <PopoverContent className="w-[280px] p-0">
                                    <Command>
                                        <CommandInput placeholder="搜索用户..." />
                                        <CommandEmpty>未找到用户</CommandEmpty>
                                        <CommandGroup className="max-h-[300px] overflow-auto">
                                            {availableUsers.map((user) => (
                                                <CommandItem
                                                    key={user.id}
                                                    onSelect={() => toggleUserSelection(user.id)}
                                                    className="cursor-pointer"
                                                >
                                                    <Checkbox
                                                        checked={selectedUserIds.includes(user.id)}
                                                        className="mr-2"
                                                    />
                                                    <div className="flex flex-col flex-1">
                                                        <span className="font-medium">{user.nickname || user.username}</span>
                                                        <span className="text-xs text-muted-foreground">{user.username}</span>
                                                    </div>
                                                    {selectedUserIds.includes(user.id) && (
                                                        <Check className="ml-auto h-4 w-4" />
                                                    )}
                                                </CommandItem>
                                            ))}
                                        </CommandGroup>
                                    </Command>
                                </PopoverContent>
                            </Popover>

                            {/* 批量添加按钮 */}
                            <Button 
                                onClick={handleBatchAdd} 
                                disabled={selectedUserIds.length === 0 || adding}
                            >
                                {adding ? (
                                    <>
                                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                        添加中...
                                    </>
                                ) : (
                                    <>
                                <Plus className="h-4 w-4 mr-2" />
                                添加成员
                                    </>
                                )}
                            </Button>
                        </div>

                        {/* 表格 */}
                        <div className="border rounded-lg overflow-hidden">
                            <PaginatedTable<TeamMemberResponse, TeamMemberQuery>
                                ref={tableRef}
                                fetchFn={fetchData}
                                columns={columns}
                                rowKey="id"
                                minWidth="680px"
                                pageSize={10}
                            />
                        </div>
                        </div>
                    </div>
            </DialogContent>
        </Dialog>

        {/* 编辑角色对话框 */}
        <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
            <DialogContent className="max-w-md">
                <DialogHeader>
                    <DialogTitle>编辑团队角色</DialogTitle>
                </DialogHeader>
                <div className="space-y-4 py-4">
                    <div className="space-y-2">
                        <label className="text-sm font-medium">成员姓名</label>
                        <Input value={editRecord?.userName || ''} disabled />
                    </div>
                    <div className="space-y-2">
                        <label className="text-sm font-medium">团队角色</label>
                                            <Input
                                                placeholder="请输入团队角色，如：开发、测试、产品经理等"
                            value={editRole}
                            onChange={(e) => setEditRole(e.target.value)}
                        />
                    </div>
                </div>
                <div className="flex justify-end gap-2">
                    <Button variant="outline" onClick={() => setEditDialogOpen(false)}>
                                    取消
                                </Button>
                    <Button onClick={handleEditSave}>
                        保存
                                </Button>
                            </div>
            </DialogContent>
        </Dialog>

        {/* 删除确认对话框 */}
        <ConfirmDialog
            open={deleteDialogOpen}
            onOpenChange={setDeleteDialogOpen}
            title="确认删除"
            description={`确定要将成员 "${deleteRecord?.userName}" 从团队中移除吗？此操作无法撤销。`}
            item={deleteRecord}
            onConfirm={handleDeleteConfirm}
            onSuccess={() => {
                toast({
                    title: "删除成功",
                    description: `成员 "${deleteRecord?.userName}" 已移除`,
                });
                setDeleteRecord(null);
                tableRef.current?.refresh();
                onSuccess?.();
            }}
            variant="destructive"
            confirmText="确认删除"
        />
        </>
    );
};

export default MemberManageDialog;

