import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
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 { ScrollArea } from "@/components/ui/scroll-area";
import {
    GitBranch,
    GitFork,
    RefreshCw,
    Link2,
    FolderGit2
} from "lucide-react";
import { message } from 'antd';
import type { GitInstance, GitInstanceInfo, RepositoryGroup, RepositoryProject } from './types';
import {
    getGitInstances,
    getGitInstanceInfo,
    syncAllGitData,
    syncGitGroups,
    syncGitProjects,
    syncGitBranches
} from './service';

const GitManager: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [instances, setInstances] = useState<GitInstance[]>([]);
    const [selectedInstance, setSelectedInstance] = useState<number>();
    const [instanceInfo, setInstanceInfo] = useState<GitInstanceInfo>();

    // 加载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) {
            message.error('加载Git实例失败');
        }
    };

    // 加载实例信息
    const loadInstanceInfo = async () => {
        if (!selectedInstance) return;
        setLoading(true);
        try {
            const data = await getGitInstanceInfo(selectedInstance);
            setInstanceInfo(data);
        } catch (error) {
            message.error('加载实例信息失败');
        } finally {
            setLoading(false);
        }
    };

    // 同步所有数据
    const handleSyncAll = async () => {
        if (!selectedInstance) return;
        try {
            await syncAllGitData(selectedInstance);
            message.success('同步任务已启动');
            loadInstanceInfo();
        } catch (error) {
            message.error('同步失败');
        }
    };

    // 同步仓库组
    const handleSyncGroups = async () => {
        if (!selectedInstance) return;
        try {
            await syncGitGroups(selectedInstance);
            message.success('仓库组同步任务已启动');
            loadInstanceInfo();
        } catch (error) {
            message.error('同步失败');
        }
    };

    // 同步项目
    const handleSyncProjects = async () => {
        if (!selectedInstance) return;
        try {
            await syncGitProjects(selectedInstance);
            message.success('项目同步任务已启动');
            loadInstanceInfo();
        } catch (error) {
            message.error('同步失败');
        }
    };

    // 同步分支
    const handleSyncBranches = async () => {
        if (!selectedInstance) return;
        try {
            await syncGitBranches(selectedInstance);
            message.success('分支同步任务已启动');
            loadInstanceInfo();
        } catch (error) {
            message.error('同步失败');
        }
    };

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

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

    return (
        <PageContainer
            header={{
                title: 'Git 仓库管理',
                extra: [
                    <Button key="sync" onClick={handleSyncAll}>
                        <RefreshCw className="mr-2 h-4 w-4" />
                        同步所有数据
                    </Button>,
                    <Select 
                        key="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>
                ],
            }}
        >
            {selectedInstance && instances.find(i => i.id === selectedInstance) && (
                <Card className="mb-6">
                    <CardHeader className="pb-2">
                        <CardTitle>{instances.find(i => i.id === selectedInstance)?.name}</CardTitle>
                        <CardDescription className="text-sm text-muted-foreground">
                            {instances.find(i => i.id === selectedInstance)?.url}
                        </CardDescription>
                    </CardHeader>
                </Card>
            )}

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                <Card className="col-span-1">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-xl font-bold">
                            <div className="flex items-center">
                                <FolderGit2 className="mr-2 h-5 w-5" />
                                {instanceInfo?.totalGroups || 0}
                            </div>
                            <div className="text-sm font-normal text-muted-foreground mt-1">仓库组</div>
                        </CardTitle>
                        <Button variant="ghost" size="sm" onClick={handleSyncGroups}>
                            <RefreshCw className="h-4 w-4" />
                        </Button>
                    </CardHeader>
                    <CardContent>
                        <p className="text-sm text-muted-foreground">
                            Last sync: {instanceInfo?.lastSyncGroupsTime ? new Date(instanceInfo.lastSyncGroupsTime).toLocaleString() : 'Never'}
                        </p>
                    </CardContent>
                </Card>

                <Card className="col-span-1">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-xl font-bold">
                            <div className="flex items-center">
                                <GitFork className="mr-2 h-5 w-5" />
                                {instanceInfo?.totalProjects || 0}
                            </div>
                            <div className="text-sm font-normal text-muted-foreground mt-1">项目</div>
                        </CardTitle>
                        <Button variant="ghost" size="sm" onClick={handleSyncProjects}>
                            <RefreshCw className="h-4 w-4" />
                        </Button>
                    </CardHeader>
                    <CardContent>
                        <p className="text-sm text-muted-foreground">
                            Last sync: {instanceInfo?.lastSyncProjectsTime ? new Date(instanceInfo.lastSyncProjectsTime).toLocaleString() : 'Never'}
                        </p>
                    </CardContent>
                </Card>

                <Card className="col-span-1">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-xl font-bold">
                            <div className="flex items-center">
                                <GitBranch className="mr-2 h-5 w-5" />
                                {instanceInfo?.totalBranches || 0}
                            </div>
                            <div className="text-sm font-normal text-muted-foreground mt-1">分支</div>
                        </CardTitle>
                        <Button variant="ghost" size="sm" onClick={handleSyncBranches}>
                            <RefreshCw className="h-4 w-4" />
                        </Button>
                    </CardHeader>
                    <CardContent>
                        <p className="text-sm text-muted-foreground">
                            Last sync: {instanceInfo?.lastSyncBranchesTime ? new Date(instanceInfo.lastSyncBranchesTime).toLocaleString() : 'Never'}
                        </p>
                    </CardContent>
                </Card>
            </div>

            <Tabs defaultValue="groups" className="space-y-4">
                <TabsList>
                    <TabsTrigger value="groups">仓库组</TabsTrigger>
                    <TabsTrigger value="projects">项目</TabsTrigger>
                </TabsList>

                <TabsContent value="groups">
                    <Card>
                        <CardContent className="p-4">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead className="w-[200px]">名称</TableHead>
                                        <TableHead className="w-[200px]">路径</TableHead>
                                        <TableHead className="w-[100px]">可见性</TableHead>
                                        <TableHead>描述</TableHead>
                                        <TableHead className="w-[150px]">操作</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {instanceInfo?.repositoryGroupList?.map((group) => (
                                        <TableRow key={group.id}>
                                            <TableCell className="font-medium">{group.name}</TableCell>
                                            <TableCell>{group.path}</TableCell>
                                            <TableCell>
                                                <Badge variant={group.visibility === 'private' ? 'secondary' : 'default'}>
                                                    {group.visibility}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>{group.description}</TableCell>
                                            <TableCell>
                                                <Button variant="ghost" size="sm" onClick={handleSyncProjects}>
                                                    <RefreshCw className="mr-2 h-4 w-4" />
                                                    同步项目
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>
                </TabsContent>

                <TabsContent value="projects">
                    <Card>
                        <CardContent className="p-4">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead className="w-[200px]">名称</TableHead>
                                        <TableHead className="w-[200px]">路径</TableHead>
                                        <TableHead className="w-[120px]">默认分支</TableHead>
                                        <TableHead>最后活动时间</TableHead>
                                        <TableHead className="w-[200px]">操作</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {instanceInfo?.repositoryProjectList?.map((project) => (
                                        <TableRow key={project.id}>
                                            <TableCell className="font-medium">{project.name}</TableCell>
                                            <TableCell>{project.path}</TableCell>
                                            <TableCell>{project.isDefaultBranch}</TableCell>
                                            <TableCell>{new Date(project.lastActivityAt).toLocaleString()}</TableCell>
                                            <TableCell>
                                                <div className="flex gap-2">
                                                    <Button variant="ghost" size="sm" onClick={handleSyncBranches}>
                                                        <RefreshCw className="mr-2 h-4 w-4" />
                                                        同步分支
                                                    </Button>
                                                    <Button variant="ghost" size="sm" asChild>
                                                        <a href={project.webUrl} target="_blank" rel="noopener noreferrer">
                                                            <Link2 className="mr-2 h-4 w-4" />
                                                            查看
                                                        </a>
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </PageContainer>
    );
};

export default GitManager;
