import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import { RefreshCw, ChevronLeft, ChevronRight } from 'lucide-react';
import {
    Card,
    CardContent,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import {
    Tabs,
    TabsContent,
    TabsList,
    TabsTrigger,
} from "@/components/ui/tabs";
import type { JenkinsInstance, JenkinsInstanceDTO } from './types';
import { getJenkinsInstances, getJenkinsInstance, syncViews, syncJobs, syncBuilds } from './service';

const JenkinsManagerList: React.FC = () => {
    const [jenkinsList, setJenkinsList] = useState<JenkinsInstance[]>([]);
    const [currentJenkinsId, setCurrentJenkinsId] = useState<string>();
    const [currentJenkins, setCurrentJenkins] = useState<JenkinsInstance>();
    const [instanceDetails, setInstanceDetails] = useState<JenkinsInstanceDTO>();
    const [loading, setLoading] = useState(false);
    const [currentView, setCurrentView] = useState<string>();
    const [syncing, setSyncing] = useState<Record<string, boolean>>({
        views: false,
        jobs: false,
        builds: false
    });
    const tabsRef = useRef<HTMLDivElement>(null);
    const { toast } = useToast();

    // 获取 Jenkins 实例列表
    const loadJenkinsList = async () => {
        try {
            const data = await getJenkinsInstances();
            setJenkinsList(data);
            // 如果没有选中的实例，默认选择第一个
            if (!currentJenkinsId && data.length > 0) {
                setCurrentJenkinsId(String(data[0].id));
                setCurrentJenkins(data[0]);
            }
        } catch (error) {
            toast({
                variant: "destructive",
                title: "获取 Jenkins 实例列表失败",
                duration: 3000,
            });
        }
    };

    // 获取 Jenkins 实例详情
    const loadInstanceDetails = async () => {
        if (!currentJenkinsId) return;
        setLoading(true);
        try {
            const data = await getJenkinsInstance(currentJenkinsId);
            setInstanceDetails(data);
        } catch (error) {
            toast({
                variant: "destructive",
                title: "获取实例详情失败",
                duration: 3000,
            });
        } finally {
            setLoading(false);
        }
    };

    // 切换 Jenkins 实例
    const handleJenkinsChange = (id: string) => {
        setCurrentJenkinsId(id);
        const jenkins = jenkinsList.find(j => String(j.id) === id);
        setCurrentJenkins(jenkins);
        setInstanceDetails(undefined);
    };

    // 同步数据
    const handleSync = async (type: 'views' | 'jobs' | 'builds') => {
        if (!currentJenkinsId) return;
        setSyncing(prev => ({ ...prev, [type]: true }));
        try {
            switch (type) {
                case 'views':
                    await syncViews(currentJenkinsId);
                    break;
                case 'jobs':
                    await syncJobs(currentJenkinsId);
                    break;
                case 'builds':
                    await syncBuilds(currentJenkinsId);
                    break;
            }
            await loadInstanceDetails();  // 重新加载实例详情
            toast({
                title: "同步成功",
                duration: 3000,
            });
        } catch (error) {
            toast({
                variant: "destructive",
                title: "同步失败",
                duration: 3000,
            });
        } finally {
            setSyncing(prev => ({ ...prev, [type]: false }));
        }
    };

    // 在获取实例详情后设置默认视图
    useEffect(() => {
        if (instanceDetails?.jenkinsViewList.length > 0) {
            setCurrentView(String(instanceDetails.jenkinsViewList[0].id));
        }
    }, [instanceDetails]);

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

    useEffect(() => {
        if (currentJenkinsId) {
            loadInstanceDetails();
        }
    }, [currentJenkinsId]);

    const formatTime = (time: string | null | undefined) => {
        if (!time) return 'Never';
        return time;
    };

    const handleScroll = (direction: 'left' | 'right') => {
        if (tabsRef.current) {
            const scrollAmount = 200; // 每次滚动的距离
            const newScrollLeft = direction === 'left' 
                ? tabsRef.current.scrollLeft - scrollAmount
                : tabsRef.current.scrollLeft + scrollAmount;
            tabsRef.current.scrollTo({
                left: newScrollLeft,
                behavior: 'smooth'
            });
        }
    };

    return (
        <PageContainer>
            <div className="flex items-center justify-between mb-6">
                <h2 className="text-3xl font-bold tracking-tight">Jenkins 三方管理</h2>
                <Select
                    value={currentJenkinsId}
                    onValueChange={handleJenkinsChange}
                >
                    <SelectTrigger className="w-[300px]">
                        <SelectValue placeholder="选择 Jenkins 实例"/>
                    </SelectTrigger>
                    <SelectContent>
                        {jenkinsList.map(jenkins => (
                            <SelectItem key={jenkins.id} value={String(jenkins.id)}>
                                {jenkins.name}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>

            {currentJenkins && (
                <Card className="mb-6">
                    <CardContent className="pt-6">
                        <div className="space-y-4">
                            <div>
                                <h3 className="text-lg font-semibold">{currentJenkins.name}</h3>
                                <p className="text-sm text-muted-foreground">{currentJenkins.url}</p>
                            </div>

                            <div className="grid grid-cols-3 gap-4">
                                <div className="space-y-2">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium">Views</span>
                                        <span className="text-2xl font-bold">{instanceDetails?.totalViews || 0}</span>
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm text-muted-foreground">Last sync: {formatTime(instanceDetails?.lastSyncViewsTime)}</span>
                                        <Button 
                                            variant="ghost" 
                                            size="sm"
                                            onClick={() => handleSync('views')}
                                            disabled={syncing.views}
                                        >
                                            <RefreshCw className={`h-4 w-4 ${syncing.views ? 'animate-spin' : ''}`} />
                                            <span className="ml-2">同步视图</span>
                                        </Button>
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium">Jobs</span>
                                        <span className="text-2xl font-bold">{instanceDetails?.totalJobs || 0}</span>
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm text-muted-foreground">Last sync: {formatTime(instanceDetails?.lastSyncJobsTime)}</span>
                                        <Button 
                                            variant="ghost" 
                                            size="sm"
                                            onClick={() => handleSync('jobs')}
                                            disabled={syncing.jobs}
                                        >
                                            <RefreshCw className={`h-4 w-4 ${syncing.jobs ? 'animate-spin' : ''}`} />
                                            <span className="ml-2">同步任务</span>
                                        </Button>
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium">Builds</span>
                                        <span className="text-2xl font-bold">{instanceDetails?.totalBuilds || 0}</span>
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-sm text-muted-foreground">Last sync: {formatTime(instanceDetails?.lastSyncBuildsTime)}</span>
                                        <Button 
                                            variant="ghost" 
                                            size="sm"
                                            onClick={() => handleSync('builds')}
                                            disabled={syncing.builds}
                                        >
                                            <RefreshCw className={`h-4 w-4 ${syncing.builds ? 'animate-spin' : ''}`} />
                                            <span className="ml-2">同步构建信息</span>
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            )}

            {loading ? (
                <Card>
                    <CardContent className="flex items-center justify-center py-8">
                        <RefreshCw className="h-6 w-6 animate-spin" />
                    </CardContent>
                </Card>
            ) : instanceDetails && (
                <Tabs value={currentView} onValueChange={setCurrentView}>
                    <div className="relative mb-6">
                        <div className="absolute left-0 top-0 bottom-0 flex items-center">
                            <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 rounded-full bg-background/80 backdrop-blur-sm"
                                onClick={() => handleScroll('left')}
                            >
                                <ChevronLeft className="h-4 w-4" />
                            </Button>
                        </div>

                        <div className="overflow-x-auto scrollbar-hide mx-10" ref={tabsRef}>
                            <TabsList className="w-max">
                                {instanceDetails.jenkinsViewList.map(view => (
                                    <TabsTrigger
                                        key={view.id}
                                        value={String(view.id)}
                                        className="min-w-[120px] max-w-[200px]"
                                        title={`${view.viewName}${view.description ? ` - ${view.description}` : ''}`}
                                    >
                                        <div className="truncate">
                                            <span className="font-medium">{view.viewName}</span>
                                            {view.description && (
                                                <span className="ml-1 text-xs text-muted-foreground">
                                                    ({view.description})
                                                </span>
                                            )}
                                        </div>
                                    </TabsTrigger>
                                ))}
                            </TabsList>
                        </div>

                        <div className="absolute right-0 top-0 bottom-0 flex items-center">
                            <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 rounded-full bg-background/80 backdrop-blur-sm"
                                onClick={() => handleScroll('right')}
                            >
                                <ChevronRight className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>

                    {instanceDetails.jenkinsViewList.map(view => (
                        <TabsContent key={view.id} value={String(view.id)}>
                            <Card>
                                <CardContent className="pt-6">
                                    <div className="space-y-4">
                                        {instanceDetails.jenkinsJobList
                                            .filter(job => job.viewId === view.id)
                                            .map(job => (
                                                <div key={job.id} className="flex items-center justify-between text-sm py-2">
                                                    <div>
                                                        <a 
                                                            href={job.jobUrl} 
                                                            target="_blank" 
                                                            rel="noopener noreferrer"
                                                            className="hover:underline"
                                                        >
                                                            {job.jobName}
                                                        </a>
                                                        {job.description && (
                                                            <p className="text-xs text-muted-foreground">{job.description}</p>
                                                        )}
                                                    </div>
                                                    <div className="flex items-center gap-2">
                                                        <Badge variant={job.lastBuildStatus === 'SUCCESS' ? 'outline' : 'destructive'}>
                                                            #{job.lastBuildNumber} - {job.lastBuildStatus}
                                                        </Badge>
                                                        <span className="text-muted-foreground">{formatTime(job.lastBuildTime)}</span>
                                                    </div>
                                                </div>
                                            ))}
                                    </div>
                                </CardContent>
                            </Card>
                        </TabsContent>
                    ))}
                </Tabs>
            )}
        </PageContainer>
    );
};

export default JenkinsManagerList;
