import React, { useState, useEffect, useCallback } 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 { Progress } from '@/components/ui/progress';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import {
    Layers,
    RefreshCw,
    Search,
    Loader2,
    ExternalLink,
    Box,
    GitBranch,
    CheckCircle,
    XCircle,
    Clock,
    AlertTriangle,
    Calendar,
    Activity,
    RotateCw,
} from 'lucide-react';
import type {
    JenkinsInstance,
    JenkinsViewDTO,
    JenkinsJobDTO,
    JenkinsBuildDTO,
} from './types';
import {
    getJenkinsInstances,
    getJenkinsViews,
    getJenkinsJobs,
    getJenkinsBuilds,
    syncJenkinsViews,
    syncJenkinsJobs,
    syncJenkinsBuilds,
} 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 BUILD_STATUS_CONFIG: Record<string, {
    label: string;
    variant: 'default' | 'secondary' | 'destructive' | 'outline';
    icon: React.ElementType;
    color: string;
}> = {
    SUCCESS: { label: '成功', variant: 'default', icon: CheckCircle, color: 'text-green-600' },
    FAILURE: { label: '失败', variant: 'destructive', icon: XCircle, color: 'text-red-600' },
    UNSTABLE: { label: '不稳定', variant: 'secondary', icon: AlertTriangle, color: 'text-yellow-600' },
    ABORTED: { label: '已中止', variant: 'outline', icon: Clock, color: 'text-gray-600' },
    NOT_BUILT: { label: '未构建', variant: 'outline', icon: Box, color: 'text-gray-400' },
};

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

    // Jenkins 实例选择
    const [instances, setInstances] = useState<JenkinsInstance[]>([]);
    const [selectedInstanceId, setSelectedInstanceId] = useState<number>();

    // 数据状态
    const [views, setViews] = useState<JenkinsViewDTO[]>([]);

    // 选中状态
    const [selectedView, setSelectedView] = useState<JenkinsViewDTO>();
    const [selectedJob, setSelectedJob] = useState<JenkinsJobDTO>();

    // 加载状态
    const [loading, setLoading] = useState({ views: false });

    // 同步状态
    const [syncing, setSyncing] = useState({
        views: false,
        jobs: false,
        builds: false,
    });

    // 搜索状态
    const [viewSearch, setViewSearch] = useState('');
    const [jobSearch, setJobSearch] = useState('');
    const [buildSearch, setBuildSearch] = useState('');

    // 数量统计
    const [jobCount, setJobCount] = useState(0);
    const [buildCount, setBuildCount] = useState(0);

    // 刷新触发器
    const [jobRefreshKey, setJobRefreshKey] = useState(0);
    const [buildRefreshKey, setBuildRefreshKey] = useState(0);

    // 加载视图列表
    const loadViews = useCallback(async () => {
        if (!selectedInstanceId) return;
        setLoading((prev) => ({ ...prev, views: true }));
        try {
            const data = await getJenkinsViews(selectedInstanceId);
            setViews(data || []);
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '获取视图列表失败',
            });
        } finally {
            setLoading((prev) => ({ ...prev, views: false }));
        }
    }, [selectedInstanceId, toast]);

    // 加载 Jenkins 实例列表
    useEffect(() => {
        const loadInstances = async () => {
            try {
                const data = await getJenkinsInstances();
                setInstances(data);
                if (data.length > 0 && !selectedInstanceId) {
                    setSelectedInstanceId(data[0].id);
                }
            } catch (error) {
                toast({
                    variant: 'destructive',
                    title: '加载失败',
                    description: '获取 Jenkins 实例列表失败',
                });
            }
        };
        loadInstances();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 实例变化时加载视图
    useEffect(() => {
        if (!selectedInstanceId) return;
        setSelectedView(undefined);
        setSelectedJob(undefined);
        loadViews();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedInstanceId]);

    // 同步视图
    const handleSyncViews = useCallback(async () => {
        if (!selectedInstanceId) return;
        setSyncing((prev) => ({ ...prev, views: true }));
        try {
            await syncJenkinsViews(selectedInstanceId);
            toast({
                title: '同步成功',
                description: '视图同步任务已启动',
            });
            setTimeout(() => loadViews(), 2000);
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '视图同步失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, views: false }));
        }
    }, [selectedInstanceId, toast, loadViews]);

    // 同步任务
    const handleSyncJobs = useCallback(async () => {
        if (!selectedInstanceId) return;
        setSyncing((prev) => ({ ...prev, jobs: true }));
        try {
            await syncJenkinsJobs({
                externalSystemId: selectedInstanceId,
                viewId: selectedView?.id,
            });
            toast({
                title: '同步成功',
                description: selectedView ? '视图任务同步任务已启动' : '所有任务同步任务已启动',
            });
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '任务同步失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, jobs: false }));
        }
    }, [selectedInstanceId, selectedView, toast]);

    // 同步构建
    const handleSyncBuilds = useCallback(async () => {
        if (!selectedInstanceId) return;
        setSyncing((prev) => ({ ...prev, builds: true }));
        try {
            await syncJenkinsBuilds({
                externalSystemId: selectedInstanceId,
                jobId: selectedJob?.id,
            });
            toast({
                title: '同步成功',
                description: selectedJob ? '任务构建同步任务已启动' : '所有构建同步任务已启动',
            });
        } catch (error) {
            toast({
                variant: 'destructive',
                title: '同步失败',
                description: '构建同步失败',
            });
        } finally {
            setSyncing((prev) => ({ ...prev, builds: false }));
        }
    }, [selectedInstanceId, selectedJob, toast]);

    // 过滤视图
    const filteredViews = React.useMemo(() => {
        if (!viewSearch) return views;
        return views.filter((view) =>
            view.viewName.toLowerCase().includes(viewSearch.toLowerCase())
        );
    }, [views, viewSearch]);

    // 获取构建状态徽章
    const getBuildStatusBadge = useCallback((status: string) => {
        const config = BUILD_STATUS_CONFIG[status] || BUILD_STATUS_CONFIG.NOT_BUILT;
        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 formatDuration = useCallback((duration?: number) => {
        if (!duration) return '-';
        const seconds = Math.floor(duration / 1000);
        if (seconds < 60) return `${seconds}秒`;
        const minutes = Math.floor(seconds / 60);
        if (minutes < 60) return `${minutes}分钟`;
        const hours = Math.floor(minutes / 60);
        return `${hours}小时${minutes % 60}分钟`;
    }, []);

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

    const buildResetTrigger = React.useMemo(
        () => [selectedInstanceId, selectedJob?.id, buildRefreshKey],
        [selectedInstanceId, selectedJob?.id, buildRefreshKey]
    );

    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 text-foreground">Jenkins 管理</h1>
                        <p className="text-muted-foreground mt-2">
                            管理和监控 Jenkins 视图、任务和构建。
                        </p>
                    </div>
                    <Select
                        value={selectedInstanceId?.toString() || ''}
                        onValueChange={(value) => setSelectedInstanceId(Number(value))}
                    >
                        <SelectTrigger className="w-[240px]">
                            <SelectValue placeholder="选择Jenkins实例" />
                        </SelectTrigger>
                        <SelectContent>
                            {instances.map((instance) => (
                                <SelectItem key={instance.id} value={instance.id.toString()}>
                                    {instance.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </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 flex items-center gap-2">
                                    <Layers className="h-4 w-4" />
                                    视图 ({filteredViews.length})
                                </CardTitle>
                                <div className="flex items-center gap-1">
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={loadViews}
                                        disabled={loading.views || !selectedInstanceId}
                                        title="刷新列表"
                                    >
                                        <RefreshCw className={`h-4 w-4 ${loading.views ? 'animate-spin' : ''}`} />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={handleSyncViews}
                                        disabled={syncing.views || !selectedInstanceId}
                                        title="从Jenkins同步"
                                    >
                                        <RotateCw className={`h-4 w-4 ${syncing.views ? '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={viewSearch}
                                    onChange={(e) => setViewSearch(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.views ? (
                                    <div className="flex items-center justify-center py-12">
                                        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                                    </div>
                                ) : filteredViews.length === 0 ? (
                                    <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                                        <Layers className="h-12 w-12 mb-2 opacity-20" />
                                        <p className="text-sm">暂无视图</p>
                                    </div>
                                ) : (
                                    filteredViews.map((view) => (
                                        <div
                                            key={view.id}
                                            className={`group p-3 border rounded-lg cursor-pointer hover:bg-accent transition-colors ${
                                                selectedView?.id === view.id ? 'bg-accent border-primary' : ''
                                            }`}
                                            onClick={() => setSelectedView(selectedView?.id === view.id ? undefined : view)}
                                        >
                                            <div className="flex items-center gap-2 mb-2">
                                                <span className="flex-1 truncate font-medium">{view.viewName}</span>
                                                {view.jobCount !== undefined && view.jobCount > 0 && (
                                                    <Badge variant="secondary" className="text-xs px-1.5 py-0 h-5">
                                                        {view.jobCount}
                                                    </Badge>
                                                )}
                                                {view.viewUrl && (
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <a
                                                                href={view.viewUrl}
                                                                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>在 Jenkins 中查看</p>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                )}
                                            </div>
                                            {view.description && (
                                                <p className="text-xs text-muted-foreground line-clamp-2">
                                                    {view.description}
                                                </p>
                                            )}
                                        </div>
                                    ))
                                )}
                            </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">
                                    任务 ({jobCount}){selectedView && ` - ${selectedView.viewName}`}
                                </CardTitle>
                                <div className="flex items-center gap-1">
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={() => setJobRefreshKey(prev => prev + 1)}
                                        disabled={!selectedInstanceId}
                                        title="刷新列表"
                                    >
                                        <RefreshCw className="h-4 w-4" />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={handleSyncJobs}
                                        disabled={syncing.jobs || !selectedInstanceId}
                                        title="从Jenkins同步"
                                    >
                                        <RotateCw className={`h-4 w-4 ${syncing.jobs ? '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={jobSearch}
                                    onChange={(e) => setJobSearch(e.target.value)}
                                    className="pl-8 h-8"
                                />
                            </div>
                        </CardHeader>
                        <div id="jobScrollableDiv" className="flex-1 overflow-auto">
                            <InfiniteScrollList<JenkinsJobDTO>
                                loadData={(pageNum, size) => getJenkinsJobs({
                                    externalSystemId: selectedInstanceId!,
                                    viewId: selectedView?.id,
                                    pageNum,
                                    size,
                                })}
                                onDataChange={(data, total) => setJobCount(data.length)}
                                renderItem={(job, index, isSelected) => (
                                    <div className={`group p-3 border rounded-lg transition-colors ${
                                        isSelected ? 'bg-accent border-primary' : 'hover:bg-accent'
                                    }`}>
                                        <div className="flex items-center gap-2 mb-2">
                                            <span className="flex-1 truncate font-medium">{job.jobName}</span>
                                            {job.buildCount !== undefined && job.buildCount > 0 && (
                                                <Badge variant="secondary" className="text-xs px-1.5 py-0 h-5">
                                                    {job.buildCount}
                                                </Badge>
                                            )}
                                            {job.jobUrl && (
                                                <Tooltip>
                                                    <TooltipTrigger asChild>
                                                        <a
                                                            href={job.jobUrl}
                                                            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-6 w-6">
                                                                <ExternalLink className="h-3 w-3" />
                                                            </Button>
                                                        </a>
                                                    </TooltipTrigger>
                                                    <TooltipContent>
                                                        <p>在 Jenkins 中查看</p>
                                                    </TooltipContent>
                                                </Tooltip>
                                            )}
                                        </div>
                                        {job.description && (
                                            <p className="text-xs text-muted-foreground line-clamp-2 mb-2">
                                                {job.description}
                                            </p>
                                        )}
                                        <div className="flex items-center gap-3 text-xs">
                                            {job.lastBuildStatus && getBuildStatusBadge(job.lastBuildStatus)}
                                            {job.healthReportScore !== undefined && (
                                                <Tooltip>
                                                    <TooltipTrigger asChild>
                                                        <div className="flex items-center gap-1">
                                                            <Activity className="h-3 w-3 text-muted-foreground" />
                                                            <Progress value={job.healthReportScore} className="w-16 h-2" />
                                                            <span className="text-muted-foreground">
                                                                {job.healthReportScore}%
                                                            </span>
                                                        </div>
                                                    </TooltipTrigger>
                                                    <TooltipContent>
                                                        健康度: {job.healthReportScore}%
                                                    </TooltipContent>
                                                </Tooltip>
                                            )}
                                        </div>
                                        {job.lastBuildTime && (
                                            <div className="flex items-center gap-1 text-xs text-muted-foreground mt-2">
                                                <Calendar className="h-3 w-3" />
                                                最近构建: {dayjs(job.lastBuildTime).fromNow()}
                                            </div>
                                        )}
                                    </div>
                                )}
                                searchValue={jobSearch}
                                localFilter={(job, search) =>
                                    job.jobName.toLowerCase().includes(search.toLowerCase())
                                }
                                selectedItem={selectedJob}
                                onItemClick={(job) => setSelectedJob(selectedJob?.id === job.id ? undefined : job)}
                                itemKey="id"
                                scrollableTarget="jobScrollableDiv"
                                emptyText={selectedView ? '当前视图暂无任务' : '暂无任务'}
                                emptyIcon={<Box className="h-12 w-12 mb-2 opacity-20" />}
                                resetTrigger={jobResetTrigger}
                            />
                        </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">
                                    构建 ({buildCount}){selectedJob && ` - ${selectedJob.jobName}`}
                                </CardTitle>
                                <div className="flex items-center gap-1">
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={() => setBuildRefreshKey(prev => prev + 1)}
                                        disabled={!selectedInstanceId}
                                        title="刷新列表"
                                    >
                                        <RefreshCw className="h-4 w-4" />
                                    </Button>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-7 w-7"
                                        onClick={handleSyncBuilds}
                                        disabled={syncing.builds || !selectedInstanceId}
                                        title="从Jenkins同步"
                                    >
                                        <RotateCw className={`h-4 w-4 ${syncing.builds ? '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={buildSearch}
                                    onChange={(e) => setBuildSearch(e.target.value)}
                                    className="pl-8 h-8"
                                />
                            </div>
                        </CardHeader>
                        <div id="buildScrollableDiv" className="flex-1 overflow-auto">
                            <InfiniteScrollList<JenkinsBuildDTO>
                                loadData={(pageNum, size) => getJenkinsBuilds({
                                    externalSystemId: selectedInstanceId!,
                                    jobId: selectedJob?.id,
                                    pageNum,
                                    size,
                                })}
                                onDataChange={(data, total) => setBuildCount(data.length)}
                                renderItem={(build) => (
                                    <div className="group p-3 hover:bg-accent transition-colors border rounded-lg">
                                        <div className="flex items-center justify-between mb-2">
                                            <div className="flex items-center gap-2">
                                                <span className="font-mono font-semibold text-sm">
                                                    #{build.buildNumber}
                                                </span>
                                                {getBuildStatusBadge(build.buildStatus)}
                                            </div>
                                            {build.buildUrl && (
                                                <Tooltip>
                                                    <TooltipTrigger asChild>
                                                        <a
                                                            href={build.buildUrl}
                                                            target="_blank"
                                                            rel="noopener noreferrer"
                                                            className="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"
                                                        >
                                                            <Button variant="ghost" size="icon" className="h-6 w-6">
                                                                <ExternalLink className="h-3 w-3" />
                                                            </Button>
                                                        </a>
                                                    </TooltipTrigger>
                                                    <TooltipContent>
                                                        <p>在 Jenkins 中查看</p>
                                                    </TooltipContent>
                                                </Tooltip>
                                            )}
                                        </div>
                                        {build.starttime && (
                                            <div className="flex items-center gap-1 text-xs text-muted-foreground mb-1">
                                                <Calendar className="h-3 w-3" />
                                                {dayjs(build.starttime).format('YYYY-MM-DD HH:mm:ss')}
                                            </div>
                                        )}
                                        {build.duration !== undefined && (
                                            <div className="flex items-center gap-1 text-xs text-muted-foreground mb-1">
                                                <Clock className="h-3 w-3" />
                                                耗时: {formatDuration(build.duration)}
                                            </div>
                                        )}
                                    </div>
                                )}
                                searchValue={buildSearch}
                                localFilter={(build, search) => {
                                    const searchLower = search.toLowerCase();
                                    return build.buildNumber.toString().includes(searchLower) ||
                                           build.buildStatus.toLowerCase().includes(searchLower);
                                }}
                                scrollableTarget="buildScrollableDiv"
                                emptyText={selectedJob ? '当前任务暂无构建' : '暂无构建'}
                                emptyIcon={<GitBranch className="h-12 w-12 mb-2 opacity-20" />}
                                resetTrigger={buildResetTrigger}
                            />
                        </div>
                    </Card>
                </div>
            </div>
        </TooltipProvider>
    );
};

export default JenkinsManager;
