import React, { useState, useEffect } 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 {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/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 { DataTablePagination } from '@/components/ui/pagination';
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NUM } from '@/utils/page';
import {
    Plus,
    Trash2,
    Search,
    Loader2,
    Package,
    Check,
    ChevronsUpDown,
} from "lucide-react";
import {
    getTeamApplications,
    createTeamApplication,
    deleteTeamApplication
} from '../../Application/service';
import type {
    TeamApplicationResponse,
    TeamApplicationQuery
} from '../../Application/types';
import type { Page } from '@/types/base';
import type { Application } from '@/pages/Deploy/Application/List/types';

interface ApplicationManageDialogProps {
    open: boolean;
    teamId: number;
    teamName: string;
    applications: Application[];
    onOpenChange: (open: boolean) => void;
    onSuccess?: () => void;
}

/**
 * 团队应用管理对话框
 */
const ApplicationManageDialog: React.FC<ApplicationManageDialogProps> = ({
    open,
    teamId,
    teamName,
    applications,
    onOpenChange,
    onSuccess
}) => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<Page<TeamApplicationResponse> | null>(null);
    const [searchText, setSearchText] = useState('');
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [deleteRecord, setDeleteRecord] = useState<TeamApplicationResponse | null>(null);
    const [selectedAppIds, setSelectedAppIds] = useState<number[]>([]);
    const [popoverOpen, setPopoverOpen] = useState(false);
    const [adding, setAdding] = useState(false);
    
    // 分页状态
    const [pageNum, setPageNum] = useState(DEFAULT_PAGE_NUM);
    const [pageSize] = useState(DEFAULT_PAGE_SIZE);


    // 加载应用列表
    const loadApplications = async () => {
        if (!teamId) return;
        
        setLoading(true);
        try {
            const query: TeamApplicationQuery = {
                teamId: teamId,
                pageNum,
                pageSize,
            };
            const result = await getTeamApplications(query);
            setData(result);
        } catch (error) {
            console.error('加载应用失败:', error);
            toast({
                variant: "destructive",
                title: "加载失败",
                description: error instanceof Error ? error.message : '未知错误',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (open) {
            loadApplications();
        }
    }, [open, pageNum, pageSize]);

    // 搜索
    const handleSearch = () => {
        setPageNum(0);
        loadApplications();
    };

    // 切换应用选择
    const toggleAppSelection = (appId: number) => {
        setSelectedAppIds(prev => 
            prev.includes(appId) 
                ? prev.filter(id => id !== appId)
                : [...prev, appId]
        );
    };

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

        setAdding(true);
        try {
            // 并行创建所有关联
            await Promise.all(
                selectedAppIds.map(appId =>
                    createTeamApplication({
                        teamId,
                        applicationId: appId,
                    })
                )
            );

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

    // 删除应用关联（打开确认对话框）
    const handleDeleteClick = (record: TeamApplicationResponse) => {
        setDeleteRecord(record);
        setDeleteDialogOpen(true);
    };

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

    // 过滤出未关联的应用
    const availableApplications = applications.filter(app => 
        !data?.content?.some(item => item.applicationId === app.id)
    );

    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">
                        <Package 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">
                            <div className="relative flex-1">
                                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                                <Input
                                    placeholder="搜索应用名称..."
                                    value={searchText}
                                    onChange={(e) => setSearchText(e.target.value)}
                                    onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                                    className="pl-10"
                                />
                            </div>

                            {/* 多选下拉框 */}
                            <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
                                <PopoverTrigger asChild>
                                    <Button
                                        variant="outline"
                                        role="combobox"
                                        aria-expanded={popoverOpen}
                                        className="w-[280px] justify-between"
                                        disabled={availableApplications.length === 0}
                                    >
                                        {selectedAppIds.length > 0 ? (
                                            <span className="flex items-center gap-1">
                                                已选择 <Badge variant="secondary" className="ml-1">{selectedAppIds.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">
                                            {availableApplications.map((app) => (
                                                <CommandItem
                                                    key={app.id}
                                                    onSelect={() => toggleAppSelection(app.id)}
                                                    className="cursor-pointer"
                                                >
                                                    <Checkbox
                                                        checked={selectedAppIds.includes(app.id)}
                                                        className="mr-2"
                                                    />
                                                    <div className="flex flex-col flex-1">
                                                        <span className="font-medium">{app.appName}</span>
                                                        <span className="text-xs text-muted-foreground">{app.appCode}</span>
                                                    </div>
                                                    {selectedAppIds.includes(app.id) && (
                                                        <Check className="ml-auto h-4 w-4" />
                                                    )}
                                                </CommandItem>
                                            ))}
                                        </CommandGroup>
                                    </Command>
                                </PopoverContent>
                            </Popover>

                            {/* 批量添加按钮 */}
                            <Button 
                                onClick={handleBatchAdd} 
                                disabled={selectedAppIds.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">
                            <div className="max-h-[50vh] overflow-auto">
                            <Table minWidth="750px">
                                <TableHeader>
                                    <TableRow>
                                        <TableHead width="80px" className="whitespace-nowrap">应用ID</TableHead>
                                        <TableHead width="160px" className="whitespace-nowrap">应用编码</TableHead>
                                        <TableHead width="200px" className="whitespace-nowrap">应用名称</TableHead>
                                        <TableHead width="180px" className="whitespace-nowrap">创建时间</TableHead>
                                        <TableHead width="80px" sticky className="whitespace-nowrap">操作</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {loading ? (
                                        <TableRow>
                                            <TableCell colSpan={5} className="text-center py-8">
                                                <div className="flex items-center justify-center">
                                                    <Loader2 className="h-6 w-6 animate-spin mr-2" />
                                                    <span className="text-sm text-muted-foreground">加载中...</span>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ) : data?.content && data.content.length > 0 ? (
                                        data.content.map((record) => (
                                            <TableRow key={record.id}>
                                                <TableCell width="80px" className="font-medium whitespace-nowrap">
                                                    {record.applicationId}
                                                </TableCell>
                                                <TableCell width="160px" className="whitespace-nowrap">
                                                    {record.applicationCode || '-'}
                                                </TableCell>
                                                <TableCell width="200px" className="whitespace-nowrap">
                                                    {record.applicationName || '-'}
                                                </TableCell>
                                                <TableCell width="180px" className="whitespace-nowrap">
                                                    {record.createTime || '-'}
                                                </TableCell>
                                                <TableCell width="80px" sticky>
                                                    <div className="flex items-center justify-end">
                                                        <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>
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell colSpan={5} className="text-center py-12 text-muted-foreground">
                                                <div className="flex flex-col items-center gap-3">
                                                    <Package className="h-12 w-12 opacity-20" />
                                                    <p className="text-sm">暂无应用</p>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                            </div>

                            {/* 分页 */}
                            {data && data.totalElements > 0 && (
                                <div className="flex justify-end py-3 px-4 border-t bg-muted/40">
                                    <DataTablePagination
                                        pageIndex={pageNum}
                                        pageSize={pageSize}
                                        pageCount={Math.ceil((data.totalElements || 0) / pageSize)}
                                        onPageChange={(newPage) => setPageNum(newPage)}
                                    />
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </DialogContent>
        </Dialog>

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

export default ApplicationManageDialog;

