import React, { useState, useEffect, useMemo } from 'react';
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/components/ui/use-toast";
import {
    GitBranch,
    GitFork,
    RefreshCw,
    FolderGit2,
    Globe,
    Lock,
    Users,
    Copy,
    ExternalLink,
    Search,
    Loader2
} from "lucide-react";
import type { GitInstance, GitInstanceInfo } from './types';
import {
    getGitInstances,
    getGitInstanceInfo,
    syncAllGitData,
    syncGitGroups,
    syncGitProjects,
    syncGitBranches
} from './service';
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: 'destructive' as const, icon: Lock, color: 'text-red-600' },
    internal: { label: '内部', variant: 'secondary' as const, icon: Users, color: 'text-yellow-600' },
};

const GitManager: React.FC = () => {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);
    const [instances, setInstances] = useState<GitInstance[]>([]);
    const [selectedInstance, setSelectedInstance] = useState<number>();
    const [instanceInfo, setInstanceInfo] = useState<GitInstanceInfo>();
    
    // 同步状态
    const [syncing, setSyncing] = useState({
        all: false,
        groups: false,
        projects: false,
        branches: false,
    });

    // 搜索和过滤状态
    const [groupSearch, setGroupSearch] = useState('');
    const [groupVisibility, setGroupVisibility] = useState<string>('all');
    const [projectSearch, setProjectSearch] = useState('');
    const [projectVisibility, setProjectVisibility] = useState<string>('all');
    const [projectGroup, setProjectGroup] = useState<string>('all');
    const [activeTab, setActiveTab] = useState<string>('groups');

    // 加载Git实例列表
    const loadInstances = async () => {
        try {
            const response = await getGitInstances();
            if (response && Array.isArray(response)) {
                setInstances(response);
                if (response.length > 0) {
                    setSelectedInstance(response[0].id);
                }
            }
        } catch (error) {
            toast({
                variant: "destructive",
                title: "加载失败",
                description: "加载 Git 实例列表失败",
            });
        }
    };

    // 加载实例信息
    const loadInstanceInfo = async () => {
        if (!selectedInstance) return;
        setLoading(true);
        try {
            const data = await getGitInstanceInfo(selectedInstance);
            setInstanceInfo(data);
        } catch (error) {
            toast({
                variant: "destructive",
                title: "加载失败",
                description: "加载实例信息失败",
            });
        } finally {
            setLoading(false);
        }
    };

    // 同步所有数据
    const handleSyncAll = async () => {
        if (!selectedInstance) return;
        setSyncing(prev => ({ ...prev, all: true }));
        try {
            await syncAllGitData(selectedInstance);
            toast({
                title: "同步成功",
                description: "同步任务已启动",
            });
            loadInstanceInfo();
        } catch (error) {
            toast({
                variant: "destructive",
                title: "同步失败",
                description: "同步任务启动失败",
            });
        } finally {
            setSyncing(prev => ({ ...prev, all: false }));
        }
    };

    // 同步仓库组
    const handleSyncGroups = async () => {
        if (!selectedInstance) return;
        setSyncing(prev => ({ ...prev, groups: true }));
        try {
            await syncGitGroups(selectedInstance);
            toast({
                title: "同步成功",
                description: "仓库组同步任务已启动",
            });
            loadInstanceInfo();
        } catch (error) {
            toast({
                variant: "destructive",
                title: "同步失败",
                description: "仓库组同步任务启动失败",
            });
        } finally {
            setSyncing(prev => ({ ...prev, groups: false }));
        }
    };

    // 同步项目
    const handleSyncProjects = async () => {
        if (!selectedInstance) return;
        setSyncing(prev => ({ ...prev, projects: true }));
        try {
            await syncGitProjects(selectedInstance);
            toast({
                title: "同步成功",
                description: "项目同步任务已启动",
            });
            loadInstanceInfo();
        } catch (error) {
            toast({
                variant: "destructive",
                title: "同步失败",
                description: "项目同步任务启动失败",
            });
        } finally {
            setSyncing(prev => ({ ...prev, projects: false }));
        }
    };

    // 同步分支
    const handleSyncBranches = async () => {
        if (!selectedInstance) return;
        setSyncing(prev => ({ ...prev, branches: true }));
        try {
            await syncGitBranches(selectedInstance);
            toast({
                title: "同步成功",
                description: "分支同步任务已启动",
            });
            loadInstanceInfo();
        } catch (error) {
            toast({
                variant: "destructive",
                title: "同步失败",
                description: "分支同步任务启动失败",
            });
        } finally {
            setSyncing(prev => ({ ...prev, branches: false }));
        }
    };

    // 复制路径
    const handleCopyPath = (path: string) => {
        navigator.clipboard.writeText(path);
        toast({
            title: "复制成功",
            description: `已复制路径: ${path}`,
        });
    };

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

    // 过滤仓库组
    const filteredGroups = useMemo(() => {
        if (!instanceInfo?.repositoryGroupList) return [];
        return instanceInfo.repositoryGroupList.filter(group => {
            const matchSearch = !groupSearch || 
                group.name.toLowerCase().includes(groupSearch.toLowerCase()) ||
                group.path.toLowerCase().includes(groupSearch.toLowerCase());
            const matchVisibility = groupVisibility === 'all' || group.visibility === groupVisibility;
            return matchSearch && matchVisibility;
        });
    }, [instanceInfo?.repositoryGroupList, groupSearch, groupVisibility]);

    // 过滤项目
    const filteredProjects = useMemo(() => {
        if (!instanceInfo?.repositoryProjectList) return [];
        return instanceInfo.repositoryProjectList.filter(project => {
            const matchSearch = !projectSearch ||
                project.name.toLowerCase().includes(projectSearch.toLowerCase()) ||
                project.path.toLowerCase().includes(projectSearch.toLowerCase());
            const matchVisibility = projectVisibility === 'all' || project.visibility === projectVisibility;
            const matchGroup = projectGroup === 'all' || (project.groupId || project.id).toString() === projectGroup;
            return matchSearch && matchVisibility && matchGroup;
        });
    }, [instanceInfo?.repositoryProjectList, projectSearch, projectVisibility, projectGroup]);

    useEffect(() => {
        loadInstances();
    }, []);

    useEffect(() => {
        if (selectedInstance) {
            loadInstanceInfo();
        }
    }, [selectedInstance]);

    // 渲染可见性 Badge
    const renderVisibilityBadge = (visibility: string) => {
        const config = VISIBILITY_CONFIG[visibility.toLowerCase() as keyof typeof VISIBILITY_CONFIG] || VISIBILITY_CONFIG.public;
        const Icon = config.icon;
        return (
            <Badge variant={config.variant} className="inline-flex items-center gap-1">
                <Icon className="h-3 w-3" />
                {config.label}
            </Badge>
        );
    };

    // 点击仓库组，跳转到项目列表
    const handleGroupClick = (groupId: number) => {
        // 清空项目搜索和可见性过滤
        setProjectSearch('');
        setProjectVisibility('all');
        // 设置仓库组过滤
        setProjectGroup((groupId || '').toString());
        // 切换到项目 Tab
        setActiveTab('projects');
    };

    return (
        <div className="p-6 space-y-6">
            {/* 页面标题栏 */}
            <div className="flex items-center justify-between">
                <h1 className="text-3xl font-bold">Git 仓库管理</h1>
                <div className="flex items-center gap-3">
                    <Select 
                        value={selectedInstance?.toString()} 
                        onValueChange={(value) => setSelectedInstance(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 || selectedInstance === undefined}>
                        {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="grid grid-cols-1 md:grid-cols-3 gap-6">
                {/* 仓库组卡片 */}
                <Card className="relative overflow-hidden min-h-[140px]">
                    <div className="absolute right-0 top-0 h-full w-32 bg-gradient-to-br from-blue-500/20 to-blue-600/20 -z-10" />
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">
                            仓库组
                        </CardTitle>
                        <div className="flex items-center gap-2 relative z-10">
                            <FolderGit2 className="h-4 w-4 text-muted-foreground" />
                            <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-6 w-6"
                                onClick={handleSyncGroups}
                                disabled={syncing.groups || selectedInstance === undefined}
                            >
                                <RefreshCw className={`h-3 w-3 ${syncing.groups ? 'animate-spin' : ''}`} />
                            </Button>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{instanceInfo?.totalGroups || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">
                            最后同步: {formatTime(instanceInfo?.lastSyncGroupsTime)}
                        </p>
                    </CardContent>
                </Card>

                {/* 项目卡片 */}
                <Card className="relative overflow-hidden min-h-[140px]">
                    <div className="absolute right-0 top-0 h-full w-32 bg-gradient-to-br from-purple-500/20 to-purple-600/20 -z-10" />
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">
                            项目
                        </CardTitle>
                        <div className="flex items-center gap-2 relative z-10">
                            <GitFork className="h-4 w-4 text-muted-foreground" />
                            <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-6 w-6"
                                onClick={handleSyncProjects}
                                disabled={syncing.projects || selectedInstance === undefined}
                            >
                                <RefreshCw className={`h-3 w-3 ${syncing.projects ? 'animate-spin' : ''}`} />
                            </Button>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{instanceInfo?.totalProjects || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">
                            最后同步: {formatTime(instanceInfo?.lastSyncProjectsTime)}
                        </p>
                    </CardContent>
                </Card>

                {/* 分支卡片 */}
                <Card className="relative overflow-hidden min-h-[140px]">
                    <div className="absolute right-0 top-0 h-full w-32 bg-gradient-to-br from-green-500/20 to-green-600/20 -z-10" />
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">
                            分支
                        </CardTitle>
                        <div className="flex items-center gap-2 relative z-10">
                            <GitBranch className="h-4 w-4 text-muted-foreground" />
                            <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-6 w-6"
                                onClick={handleSyncBranches}
                                disabled={syncing.branches || selectedInstance === undefined}
                            >
                                <RefreshCw className={`h-3 w-3 ${syncing.branches ? 'animate-spin' : ''}`} />
                            </Button>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{instanceInfo?.totalBranches || 0}</div>
                        <p className="text-xs text-muted-foreground mt-1">
                            最后同步: {formatTime(instanceInfo?.lastSyncBranchesTime)}
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* Tabs 区域 */}
            <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
                <TabsList>
                    <TabsTrigger value="groups">仓库组 ({filteredGroups.length})</TabsTrigger>
                    <TabsTrigger value="projects">项目 ({filteredProjects.length})</TabsTrigger>
                </TabsList>

                {/* 仓库组 Tab */}
                <TabsContent value="groups">
                    <Card className="mb-4">
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-4">
                                <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={groupSearch}
                                        onChange={(e) => setGroupSearch(e.target.value)}
                                        className="pl-10"
                                    />
                                </div>
                                <Select value={groupVisibility} onValueChange={setGroupVisibility}>
                                    <SelectTrigger className="w-[150px]">
                                        <SelectValue placeholder="可见性" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">全部</SelectItem>
                                        <SelectItem value="public">公开</SelectItem>
                                        <SelectItem value="private">私有</SelectItem>
                                        <SelectItem value="internal">内部</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Button 
                                    variant="outline" 
                                    onClick={() => {
                                        setGroupSearch('');
                                        setGroupVisibility('all');
                                    }}
                                >
                                    重置
                                </Button>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="p-0">
                            {loading ? (
                                <div className="flex items-center justify-center h-64">
                                    <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                                </div>
                            ) : filteredGroups.length === 0 ? (
                                <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                                    <FolderGit2 className="h-16 w-16 mb-4 opacity-20" />
                                    <p className="text-lg font-medium">暂无仓库组</p>
                                    <p className="text-sm">请同步 Git 实例数据</p>
                                </div>
                            ) : (
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead className="w-[200px]">名称</TableHead>
                                            <TableHead className="w-[200px]">路径</TableHead>
                                            <TableHead className="w-[100px]">可见性</TableHead>
                                            <TableHead>描述</TableHead>
                                            <TableHead className="w-[200px]">操作</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredGroups.map((group) => (
                                            <TableRow key={group.id}>
                                                <TableCell className="font-medium">
                                                    <Button
                                                        variant="link"
                                                        className="p-0 h-auto font-medium text-base hover:underline"
                                                        onClick={() => handleGroupClick(group.groupId || group.id)}
                                                    >
                                                        {group.name}
                                                    </Button>
                                                </TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        <code className="text-xs bg-muted px-2 py-1 rounded">
                                                            {group.path}
                                                        </code>
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            onClick={() => handleCopyPath(group.path)}
                                                        >
                                                            <Copy className="h-3 w-3" />
                                                        </Button>
                                                    </div>
                                                </TableCell>
                                                <TableCell>
                                                    {renderVisibilityBadge(group.visibility)}
                                                </TableCell>
                                                <TableCell className="max-w-xs truncate" title={group.description}>
                                                    {group.description || '-'}
                                                </TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        <Button variant="ghost" size="sm" onClick={handleSyncProjects}>
                                                            <RefreshCw className="mr-1 h-3 w-3" />
                                                            同步项目
                                                        </Button>
                                                        {group.webUrl && (
                                                            <a
                                                                href={group.webUrl}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                            >
                                                                <Button variant="ghost" size="sm">
                                                                    <ExternalLink className="h-3 w-3" />
                                                                </Button>
                                                            </a>
                                                        )}
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* 项目 Tab */}
                <TabsContent value="projects">
                    <Card className="mb-4">
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-4">
                                <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={projectSearch}
                                        onChange={(e) => setProjectSearch(e.target.value)}
                                        className="pl-10"
                                    />
                                </div>
                                <Select value={projectVisibility} onValueChange={setProjectVisibility}>
                                    <SelectTrigger className="w-[150px]">
                                        <SelectValue placeholder="可见性" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">全部</SelectItem>
                                        <SelectItem value="public">公开</SelectItem>
                                        <SelectItem value="private">私有</SelectItem>
                                        <SelectItem value="internal">内部</SelectItem>
                                    </SelectContent>
                                </Select>
                                <Select value={projectGroup} onValueChange={setProjectGroup}>
                                    <SelectTrigger className="w-[180px]">
                                        <SelectValue placeholder="仓库组" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">全部仓库组</SelectItem>
                                        {instanceInfo?.repositoryGroupList?.map((group) => (
                                            <SelectItem key={group.id} value={(group.groupId || group.id).toString()}>
                                                {group.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <Button 
                                    variant="outline" 
                                    onClick={() => {
                                        setProjectSearch('');
                                        setProjectVisibility('all');
                                        setProjectGroup('all');
                                    }}
                                >
                                    重置
                                </Button>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="p-0">
                            {loading ? (
                                <div className="flex items-center justify-center h-64">
                                    <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                                </div>
                            ) : filteredProjects.length === 0 ? (
                                <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                                    <GitFork className="h-16 w-16 mb-4 opacity-20" />
                                    <p className="text-lg font-medium">暂无项目</p>
                                    <p className="text-sm">请同步 Git 实例数据</p>
                                </div>
                            ) : (
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead className="w-[200px]">名称</TableHead>
                                            <TableHead className="w-[200px]">路径</TableHead>
                                            <TableHead className="w-[100px]">可见性</TableHead>
                                            <TableHead className="w-[120px]">默认分支</TableHead>
                                            <TableHead>最后活动时间</TableHead>
                                            <TableHead className="w-[220px]">操作</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {filteredProjects.map((project) => (
                                            <TableRow key={project.id}>
                                                <TableCell className="font-medium">{project.name}</TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        <code className="text-xs bg-muted px-2 py-1 rounded">
                                                            {project.path}
                                                        </code>
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            onClick={() => handleCopyPath(project.path)}
                                                        >
                                                            <Copy className="h-3 w-3" />
                                                        </Button>
                                                    </div>
                                                </TableCell>
                                                <TableCell>
                                                    {renderVisibilityBadge(project.visibility)}
                                                </TableCell>
                                                <TableCell>
                                                    <Badge variant="outline" className="inline-flex items-center gap-1">
                                                        <GitBranch className="h-3 w-3" />
                                                        {project.isDefaultBranch}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="text-sm text-muted-foreground">
                                                    {formatTime(project.lastActivityAt)}
                                                </TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        <Button variant="ghost" size="sm" onClick={handleSyncBranches}>
                                                            <RefreshCw className="mr-1 h-3 w-3" />
                                                            同步分支
                                                        </Button>
                                                        {project.webUrl && (
                                                            <a
                                                                href={project.webUrl}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                            >
                                                                <Button variant="ghost" size="sm">
                                                                    <ExternalLink className="mr-1 h-3 w-3" />
                                                                    查看
                                                                </Button>
                                                            </a>
                                                        )}
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    );
};

export default GitManager;
