import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { InfiniteScrollList } from '@/components/ui/infinite-scroll-list';
import {
    Card,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,

} from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/components/ui/use-toast';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import {
    GitBranch,

    FolderGit2,
    RefreshCw,
    Globe,
    Lock,
    Users,

    Search,
    Loader2,
    ChevronRight,
    ChevronDown,
    ExternalLink,

    Code2,
    Calendar,
    User,
    GitCommit,
    RotateCw,
} from 'lucide-react';
import type {
    RepositoryGroupResponse,
    RepositoryProjectResponse,
    RepositoryBranchResponse,
} from './types';
import {
    getGitInstances,

    getRepositoryGroups,
    getRepositoryProjects,
    getRepositoryBranches,
    syncAllGitData,

    syncRepositoryGroups,
    syncRepositoryProjects,
    syncRepositoryBranches,
} from './service';

import type { ExternalSystemResponse } from '@/pages/Resource/External/List/types';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';

dayjs.extend(relativeTime);
dayjs.locale('zh-cn');


// 可见性配置
const VISIBILITY_CONFIG = {
    public: { label: '公开', variant: 'default' as const, icon: Globe, color: 'text-green-600' },

    private: { label: '私有', variant: 'secondary' as const, icon: Lock, color: 'text-red-600' },
    internal: { label: '内部', variant: 'outline' as const, icon: Users, color: 'text-yellow-600' },
};

const GitManager: React.FC = () => {
    const { toast } = useToast();

    
    // Git 实例选择
    const [instances, setInstances] = useState<ExternalSystemResponse[]>([]);
    const [selectedInstanceId, setSelectedInstanceId] = useState<number>();
    
    // 数据状态 - 项目和分支由 InfiniteScrollList 管理
    const [groupTree, setGroupTree] = useState<RepositoryGroupResponse[]>([]);
    
    // 选中状态
    const [selectedGroup, setSelectedGroup] = useState<RepositoryGroupResponse>();
    const [selectedProject, setSelectedProject] = useState<RepositoryProjectResponse>();
    const [expandedGroupIds, setExpandedGroupIds] = useState<Set<number>>(new Set());
    
    // 加载状态
    const [loading, setLoading] = useState({
        groups: false,
        projects: false,
        branches: false,
    });
    
    // 同步状态
    const [syncing, setSyncing] = useState({
        all: false,
        groups: false,
        projects: false,
        branches: false,
    });

    // 数量统计
    const [projectCount, setProjectCount] = useState(0);
    const [branchCount, setBranchCount] = useState(0);

    // 刷新触发器
    const [projectRefreshKey, setProjectRefreshKey] = useState(0);
    const [branchRefreshKey, setBranchRefreshKey] = useState(0);

    // 搜索过滤 - 仅保留仓库组搜索
    const [groupSearch, setGroupSearch] = useState('');

    // 防抖搜索值 - 优化大量数据过滤性能
    const [debouncedGroupSearch, setDebouncedGroupSearch] = useState('');

    // 使用 ref 跟踪初始化状态，避免重复请求
    const isInitializedRef = useRef(false);
    const groupsLoadedRef = useRef(false);
    const projectsLoadedRef = useRef(false);

    // 仓库组搜索防抖
    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedGroupSearch(groupSearch);
        }, 300);
        return () => clearTimeout(timer);
    }, [groupSearch]);

    // 构建树形结构
    const buildTree = useCallback((groups: RepositoryGroupResponse[]): RepositoryGroupResponse[] => {
        // 使用 repoGroupId 作为 key，因为 parentId 对应的是 Git 系统中的 repoGroupId
        const map = new Map<number, RepositoryGroupResponse>();
        const roots: RepositoryGroupResponse[] = [];

        // 首先将所有节点放入 map，使用 repoGroupId 作为 key
        groups.forEach((group) => {
            const key = group.repoGroupId || group.id;
            map.set(key, { ...group, children: [] });
        });

        // 然后构建树形结构
        groups.forEach((group) => {
            const key = group.repoGroupId || group.id;
            const node = map.get(key)!;
            
            if (group.parentId) {
                // parentId 对应的是父节点的 repoGroupId
                const parent = map.get(group.parentId);
                if (parent) {
                    if (!parent.children) {
                        parent.children = [];
                    }
                    parent.children.push(node);
                } else {
                    // 如果找不到父节点，作为根节点
                    roots.push(node);
                }
            } else {
                // parentId 为 null，作为根节点
                roots.push(node);
            }
        });

        return roots;
    }, []);

    // 加载仓库组列表并构建树
    const loadGroupTree = useCallback(async () => {
        if (!selectedInstanceId) return;
        
        setLoading((prev) => ({ ...prev, groups: true }));
        try {
            const data = await getRepositoryGroups({
                externalSystemId: selectedInstanceId,
            });
            // 构建树形结构
            const tree = buildTree(data || []);
            setGroupTree(tree);
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '加载仓库组失败',
            });
            setGroupTree([]);
        } finally {
            setLoading((prev) => ({ ...prev, groups: false }));
        }
    }, [selectedInstanceId, buildTree, toast]);

    // 同步所有数据（异步任务）
    const handleSyncAll = useCallback(async () => {
        if (!selectedInstanceId) return;
        
        setSyncing((prev) => ({ ...prev, all: true }));
        try {
            await syncAllGitData(selectedInstanceId);
            toast({
                title: '同步任务已启动',
                description: '正在后台同步所有数据，请稍后手动刷新查看结果',
            });
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '同步任务启动失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, all: false }));
        }
    }, [selectedInstanceId, toast]);

    // 同步仓库组（异步任务）
    const handleSyncGroups = useCallback(async () => {
        if (!selectedInstanceId) return;
        
        setSyncing((prev) => ({ ...prev, groups: true }));
        try {
            await syncRepositoryGroups(selectedInstanceId);
            toast({
                title: '同步任务已启动',
                description: '正在后台同步仓库组，请稍后手动刷新查看结果',
            });
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '仓库组同步任务启动失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, groups: false }));
        }
    }, [selectedInstanceId, toast]);

    // 同步项目（异步任务，支持未选择组时同步所有项目）
    const handleSyncProjects = useCallback(async () => {
        if (!selectedInstanceId) return;
        
        setSyncing((prev) => ({ ...prev, projects: true }));
        try {
            // 传递 repoGroupId (Git系统中的ID) 和 externalSystemId
            await syncRepositoryProjects(
                selectedInstanceId,
                selectedGroup?.repoGroupId
            );
            
            const description = selectedGroup
                ? `正在后台同步仓库组"${selectedGroup.name}"的项目，请稍后手动刷新查看结果`
                : '正在后台同步所有项目，请稍后手动刷新查看结果';
            
            toast({
                title: '同步任务已启动',
                description,
            });
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '项目同步任务启动失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, projects: false }));
        }
    }, [selectedInstanceId, selectedGroup, toast]);

    // 同步分支（异步任务）
    const handleSyncBranches = useCallback(async () => {
        if (!selectedInstanceId) return;
        
        setSyncing((prev) => ({ ...prev, branches: true }));
        try {
            // 如果选择了项目，只同步该项目的分支；否则同步该组下所有项目的分支
            await syncRepositoryBranches(
                selectedInstanceId,
                selectedProject?.repoProjectId,
                selectedGroup?.repoGroupId
            );
            
            let description = '正在后台同步所有分支，请稍后手动刷新查看结果';
            if (selectedProject) {
                description = `正在后台同步项目"${selectedProject.name}"的分支，请稍后手动刷新查看结果`;
            } else if (selectedGroup) {
                description = `正在后台同步组"${selectedGroup.name}"下所有项目的分支，请稍后手动刷新查看结果`;
            }
            
            toast({
                title: '同步任务已启动',
                description,
            });
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '分支同步任务启动失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, branches: false }));
        }
    }, [selectedInstanceId, selectedGroup, selectedProject, toast]);

    // 切换仓库组展开/折叠
    const toggleGroupExpand = useCallback((groupId: number) => {
        setExpandedGroupIds((prev) => {
            const next = new Set(prev);
            if (next.has(groupId)) {
                next.delete(groupId);
            } else {
                next.add(groupId);
            }
            return next;
        });
    }, []);

    // 选中仓库组（支持反选取消）
    const handleSelectGroup = useCallback((group: RepositoryGroupResponse) => {
        // 如果点击的是已选中的组，则取消选择
        setSelectedGroup((prev) => prev?.id === group.id ? undefined : group);
    }, []);

    // 选中项目（支持反选取消）
    const handleSelectProject = useCallback((project: RepositoryProjectResponse) => {
        // 如果点击的是已选中的项目，则取消选择
        setSelectedProject((prev) => prev?.id === project.id ? undefined : project);
    }, []);

    // 格式化时间
    const formatTime = useCallback((time?: string) => {
        if (!time) return '-';
        const diff = dayjs().diff(dayjs(time), 'day');
        if (diff > 7) {
            return dayjs(time).format('YYYY-MM-DD HH:mm');
        }
        return dayjs(time).fromNow();
    }, []);

    // 渲染可见性图标（带 Tooltip）
    const renderVisibilityIcon = useCallback((visibility: string) => {
        const config =
            VISIBILITY_CONFIG[visibility.toLowerCase() as keyof typeof VISIBILITY_CONFIG] ||
            VISIBILITY_CONFIG.public;
        const Icon = config.icon;
        return (
            <Tooltip>
                <TooltipTrigger asChild>
                    <div className="cursor-help">
                        <Icon className={`h-3.5 w-3.5 ${config.color}`} />
                    </div>
                </TooltipTrigger>
                <TooltipContent>
                    <p>{config.label}仓库</p>
                </TooltipContent>
            </Tooltip>
        );
    }, []);

    // 过滤仓库组树（使用防抖搜索值）
    const filterGroupTree = useCallback((groups: RepositoryGroupResponse[]): RepositoryGroupResponse[] => {
        if (!debouncedGroupSearch) return groups;
        
        return groups.filter((group) => {
            const matchesSearch =
                group.name.toLowerCase().includes(debouncedGroupSearch.toLowerCase()) ||
                (group.path && group.path.toLowerCase().includes(debouncedGroupSearch.toLowerCase()));
            
            const filteredChildren = group.children
                ? filterGroupTree(group.children)
                : [];
            
            return matchesSearch || filteredChildren.length > 0;
        }).map((group) => ({
            ...group,
            children: group.children ? filterGroupTree(group.children) : [],
        }));
    }, [debouncedGroupSearch]);

    // 渲染仓库组树节点
    const renderGroupTreeNode = (
        group: RepositoryGroupResponse,
        level: number = 0
    ): React.ReactNode => {
        const hasChildren = group.children && group.children.length > 0;
        const isExpanded = expandedGroupIds.has(group.id);

        return (
            <React.Fragment key={group.id}>
                <div
                    className={`group flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-accent rounded-md transition-colors ${
                        selectedGroup?.id === group.id ? 'bg-accent border-l-2 border-primary' : ''
                    }`}
                    style={{ paddingLeft: `${level * 16 + 12}px` }}
                    onClick={() => handleSelectGroup(group)}
                >
                    {hasChildren ? (
                        <button
                            onClick={(e) => {
                                e.stopPropagation();
                                toggleGroupExpand(group.id);
                            }}
                            className="hover:bg-accent-foreground/10 rounded p-0.5"
                        >
                            {isExpanded ? (
                                <ChevronDown className="h-4 w-4" />
                            ) : (
                                <ChevronRight className="h-4 w-4" />
                            )}
                        </button>
                    ) : (
                        <span className="w-5" />
                    )}
                    
                    <FolderGit2 className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                    {renderVisibilityIcon(group.visibility)}
                    
                    <span className="flex-1 truncate text-sm font-medium">
                        {group.name}
                    </span>
                    
                    {group.projectCount !== undefined && group.projectCount > 0 && (
                        <Badge variant="secondary" className="text-xs px-1.5 py-0 h-5">
                            {group.projectCount}
            </Badge>
                    )}
                    
                    {group.webUrl && (
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <a
                                    href={group.webUrl}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    onClick={(e) => e.stopPropagation()}
                                    className="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"
                                >
                                    <Button variant="ghost" size="icon" className="h-5 w-5">
                                        <ExternalLink className="h-3 w-3" />
                                    </Button>
                                </a>
                            </TooltipTrigger>
                            <TooltipContent>
                                <p>在 GitLab 中查看</p>
                            </TooltipContent>
                        </Tooltip>
                    )}
                </div>

                {hasChildren && isExpanded && (
                    <div>
                        {group.children!.map((child) =>
                            renderGroupTreeNode(child, level + 1)
                        )}
                    </div>
                )}
            </React.Fragment>
        );
    };

    // 加载 Git 实例列表（只在组件挂载时执行一次）
    useEffect(() => {
        const loadInstancesEffect = async () => {
            try {
                const data = await getGitInstances();
                if (data && Array.isArray(data)) {
                    setInstances(data);
                    if (data.length > 0 && !selectedInstanceId) {
                        setSelectedInstanceId(data[0].id);
                    }
                }
            } catch (error) {
                toast({
                    variant: 'destructive',
                    title: '加载失败',
                    description: '加载 Git 实例列表失败',
                });
            }
        };
        loadInstancesEffect();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []); // 只在组件挂载时执行一次

    // 实例变化时 - 重置状态并加载仓库组
    useEffect(() => {
        if (!selectedInstanceId) return;
        
        // 重置所有状态和标志
        isInitializedRef.current = false;
        groupsLoadedRef.current = false;
        projectsLoadedRef.current = false;
        
        setSelectedGroup(undefined);
        setSelectedProject(undefined);
        // 项目和分支列表由 InfiniteScrollList 自动重置
        
        // 加载仓库组列表
        loadGroupTree();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedInstanceId]); // 只监听 selectedInstanceId，避免重复请求

    // 仓库组选择变化 - 清除下级选择（InfiniteScrollList 会自动重新加载）
    useEffect(() => {
        setSelectedProject(undefined);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedGroup?.repoGroupId, selectedGroup?.id]); // 只监听选择的组ID

    const filteredGroupTree = useMemo(() => filterGroupTree(groupTree), [groupTree, filterGroupTree]);

    // 缓存 resetTrigger 避免不必要的重置
    const projectResetTrigger = React.useMemo(
        () => [selectedInstanceId, selectedGroup?.id, projectRefreshKey],
        [selectedInstanceId, selectedGroup?.id, projectRefreshKey]
    );

    const branchResetTrigger = React.useMemo(
        () => [selectedInstanceId, selectedProject?.id, branchRefreshKey],
        [selectedInstanceId, selectedProject?.id, branchRefreshKey]
    );

    return (

        <TooltipProvider>
        <div className="flex flex-col h-full p-6 gap-4">
            {/* 顶部标题栏 */}
            <div className="flex items-center justify-between flex-shrink-0">

                <div>
                <h1 className="text-3xl font-bold">Git 仓库管理</h1>

                    <p className="text-sm text-muted-foreground mt-1">
                        管理和浏览 Git 仓库、项目和分支
                    </p>
                </div>
                <div className="flex items-center gap-3">
                    <Select 

                        value={selectedInstanceId?.toString()}
                        onValueChange={(value) => setSelectedInstanceId(Number(value))}
                    >
                        <SelectTrigger className="w-[200px]">

                            <SelectValue placeholder="选择GIT实例" />
                        </SelectTrigger>
                        <SelectContent>

                            {instances.map((instance) => (
                                <SelectItem key={instance.id} value={instance.id.toString()}>
                                    {instance.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>

                    <Button
                        onClick={handleSyncAll}
                        disabled={syncing.all || !selectedInstanceId}
                        variant="default"
                    >
                        {syncing.all ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                            <RefreshCw className="mr-2 h-4 w-4" />
                        )}
                        同步所有数据
                    </Button>
                </div>
            </div>

            {/* 三栏布局 */}
            <div className="flex-1 grid grid-cols-12 gap-4 min-h-0 overflow-hidden">
                {/* 左栏：仓库组树 */}
                <Card className="col-span-3 flex flex-col min-h-0">
                    <CardHeader className="border-b flex-shrink-0">
                        <div className="flex items-center justify-between">
                            <CardTitle className="text-base">仓库组</CardTitle>
                            <div className="flex items-center gap-1">
                            <Button 
                                variant="ghost" 
                                size="icon"
                                    className="h-7 w-7"
                                    onClick={loadGroupTree}
                                    disabled={loading.groups || !selectedInstanceId}
                                    title="刷新列表"
                                >
                                    <RefreshCw
                                        className={`h-4 w-4 ${loading.groups ? 'animate-spin' : ''}`}
                                    />
                            </Button>
                            <Button 
                                variant="ghost" 
                                size="icon"
                                    className="h-7 w-7"
                                onClick={handleSyncGroups}
                                    disabled={syncing.groups || !selectedInstanceId}
                                    title="从Git同步"
                            >
                                    <RotateCw
                                        className={`h-4 w-4 ${syncing.groups ? 'animate-spin' : ''}`}
                                    />
                            </Button>
                        </div>
            </div>

                        <div className="relative mt-2">
                            <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                                    <Input

                                placeholder="搜索仓库组..."
                                        value={groupSearch}
                                        onChange={(e) => setGroupSearch(e.target.value)}

                                className="pl-8 h-8"
                                    />
                                </div>

                    </CardHeader>
                    <ScrollArea className="flex-1">
                        <div className="p-2 space-y-1 min-h-[calc(100vh-280px)]">
                            {loading.groups ? (
                                <div className="flex items-center justify-center h-full min-h-[400px]">
                                    <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                                </div>
                            ) : filteredGroupTree.length === 0 ? (
                                <div className="flex flex-col items-center justify-center h-full min-h-[400px] text-muted-foreground">
                                    <FolderGit2 className="h-12 w-12 mb-2 opacity-20" />
                                    <p className="text-sm">暂无仓库组</p>
                                </div>
                            ) : (
                                filteredGroupTree.map((group) => renderGroupTreeNode(group))
                            )}
                            </div>

                    </ScrollArea>
                </Card>


                {/* 中栏：项目列表 */}
                <Card className="col-span-5 flex flex-col min-h-0">
                    <CardHeader className="border-b flex-shrink-0">
                        <div className="flex items-center justify-between">
                            <CardTitle className="text-base flex items-center gap-2">
                                项目 ({projectCount}){selectedGroup && ` - ${selectedGroup.name}`}
                        </CardTitle>
                            <div className="flex items-center gap-1">
                                <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={() => setProjectRefreshKey(prev => prev + 1)}
                                    disabled={!selectedInstanceId}
                                    title="刷新列表"
                                >
                                    <RefreshCw className="h-4 w-4" />
                                </Button>
                                <Button
                                    variant="ghost"
                                size="icon"
                                    className="h-7 w-7"
                                    onClick={handleSyncProjects}
                                    disabled={syncing.projects || !selectedInstanceId}
                                    title="从Git同步"
                                >
                                    <RotateCw
                                        className={`h-4 w-4 ${syncing.projects ? 'animate-spin' : ''}`}
                                    />
                                </Button>
                            </div>
            </div>
                    </CardHeader>
                    <div 
                        id="projectScrollableDiv"
                        className="flex-1 overflow-auto"
                    >
                        <InfiniteScrollList
                            loadData={(pageNum, size) =>
                                getRepositoryProjects({
                                    externalSystemId: selectedInstanceId!,
                                    repoGroupId: selectedGroup?.repoGroupId || selectedGroup?.id,
                                    pageNum,
                                    size,
                                })
                            }
                            onDataChange={(data, total) => setProjectCount(data.length)}
                            renderItem={(project) => (
                                <div
                                    key={project.id}
                                    className={`p-3 border rounded-lg cursor-pointer hover:bg-accent transition-colors ${
                                        selectedProject?.id === project.id
                                            ? 'bg-accent border-primary'
                                            : ''
                                    }`}
                                    onClick={() => handleSelectProject(project)}
                                >
                                    <div className="flex items-start justify-between gap-2">
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2 mb-1">
                                                <Code2 className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
                                                {renderVisibilityIcon(project.visibility)}
                                                <span className="font-medium truncate">
                                                    {project.name}
                                                </span>
                            </div>

                                            {project.description && (
                                                <p className="text-xs text-muted-foreground line-clamp-2">
                                                    {project.description}
                                                </p>
                                            )}
                                            <div className="flex items-center gap-3 mt-2 text-xs text-muted-foreground">
                                                {project.isDefaultBranch && (
                                                    <span className="flex items-center gap-1">
                                                        <GitBranch className="h-3 w-3" />
                                                        {project.isDefaultBranch}
                                                    </span>
                                                )}
                                                {project.branchCount !== undefined && project.branchCount > 0 && (
                                                    <span className="flex items-center gap-1">
                                                        <GitBranch className="h-3 w-3" />
                                                        {project.branchCount} 分支
                                                    </span>
                                                )}
                                                {project.lastActivityAt && (
                                                    <span className="flex items-center gap-1">
                                                        <Calendar className="h-3 w-3" />
                                                        {formatTime(project.lastActivityAt)}
                                                    </span>
                                                )}
                                </div>
                                </div>
                                        {project.webUrl && (
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <a
                                                        href={project.webUrl}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                        onClick={(e) => e.stopPropagation()}
                                                        className="flex-shrink-0"
                                                            >
                                                        <Button variant="ghost" size="icon" className="h-6 w-6">
                                                                    <ExternalLink className="h-3 w-3" />
                                                                </Button>
                                                            </a>
                                                </TooltipTrigger>
                                                <TooltipContent>
                                                    <p>在 GitLab 中查看</p>
                                                </TooltipContent>
                                            </Tooltip>
                                                        )}
                                                    </div>
                                </div>
                            )}
                            scrollableTarget="projectScrollableDiv"
                            pageSize={20}
                            resetTrigger={projectResetTrigger}
                            emptyText={selectedGroup ? '当前仓库组暂无项目' : '暂无项目'}
                            className="p-2 space-y-2"
                                    />
                                </div>
                    </Card>

                {/* 右栏：分支列表 */}
                <Card className="col-span-4 flex flex-col min-h-0">
                    <CardHeader className="border-b flex-shrink-0">
                        <div className="flex items-center justify-between">
                            <CardTitle className="text-base flex items-center gap-2">
                                分支 ({branchCount}){selectedProject && ` - ${selectedProject.name}`}
                            </CardTitle>
                            <div className="flex items-center gap-1">
                                <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={() => setBranchRefreshKey(prev => prev + 1)}
                                    disabled={!selectedInstanceId}
                                    title="刷新列表"
                                >
                                    <RefreshCw className="h-4 w-4" />
                                </Button>
                                <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={handleSyncBranches}
                                    disabled={syncing.branches || !selectedInstanceId}
                                    title="从Git同步"
                                >
                                    <RotateCw
                                        className={`h-4 w-4 ${syncing.branches ? 'animate-spin' : ''}`}
                                    />
                                </Button>
                            </div>
                        </div>
                    </CardHeader>
                    <div 
                        id="branchScrollableDiv"
                        className="flex-1 overflow-auto"
                    >
                        <InfiniteScrollList
                            loadData={(pageNum, size) =>
                                getRepositoryBranches({
                                    externalSystemId: selectedInstanceId!,
                                    repoProjectId: selectedProject?.repoProjectId || selectedProject?.id,
                                    pageNum,
                                    size,
                                })
                            }
                            onDataChange={(data, total) => setBranchCount(data.length)}
                            renderItem={(branch) => (
                                <div key={branch.id} className="p-3 hover:bg-accent transition-colors border-b">
                                    <div className="flex items-start gap-2">
                                        <GitBranch className="h-4 w-4 mt-0.5 flex-shrink-0 text-muted-foreground" />
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2 flex-wrap">
                                                <span className="font-medium font-mono text-sm truncate">
                                                    {branch.name}
                                                </span>
                                                {branch.isDefaultBranch && (
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <Badge variant="default" className="text-xs cursor-help">
                                                                默认
                                                    </Badge>
                                                        </TooltipTrigger>
                                                        <TooltipContent>
                                                            <p>仓库的默认分支</p>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                )}
                                            </div>
                                            {branch.commitMessage && (
                                                <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
                                                    <GitCommit className="h-3 w-3 inline mr-1" />
                                                    {branch.commitMessage}
                                                </p>
                                            )}
                                            {(branch.commitAuthor || branch.commitDate) && (
                                                <div className="flex items-center gap-3 mt-2 text-xs text-muted-foreground">
                                                    {branch.commitAuthor && (
                                                        <span className="flex items-center gap-1">
                                                            <User className="h-3 w-3" />
                                                            {branch.commitAuthor}
                                                        </span>
                                                    )}
                                                    {branch.commitDate && (
                                                        <span className="flex items-center gap-1">
                                                            <Calendar className="h-3 w-3" />
                                                            {formatTime(branch.commitDate)}
                                                        </span>
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                        {branch.webUrl && (
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <a
                                                        href={branch.webUrl}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                        className="flex-shrink-0"
                                                            >
                                                        <Button variant="ghost" size="icon" className="h-6 w-6">
                                                            <ExternalLink className="h-3 w-3" />
                                                                </Button>
                                                            </a>
                                                </TooltipTrigger>
                                                <TooltipContent>
                                                    <p>在 GitLab 中查看</p>
                                                </TooltipContent>
                                            </Tooltip>
                                                        )}
                                                    </div>
                                </div>
                            )}
                            scrollableTarget="branchScrollableDiv"
                            pageSize={20}
                            resetTrigger={branchResetTrigger}
                            emptyText={selectedProject ? '当前项目暂无分支' : '暂无分支'}
                            className=""
                        />
                    </div>
                    </Card>
            </div>
        </div>

        </TooltipProvider>
    );
};

export default GitManager;
