import React, { useState, useEffect, useMemo } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import { RefreshCw, Layers, Box, Activity, Search, CheckCircle, XCircle, AlertTriangle, Loader2, ExternalLink } from 'lucide-react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { Progress } from '@/components/ui/progress';
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 [instanceDetails, setInstanceDetails] = useState<JenkinsInstanceDTO>();
  const [loading, setLoading] = useState(false);
  const [currentView, setCurrentView] = useState<number>();
  const [syncing, setSyncing] = useState<Record<string, boolean>>({
    views: false,
    jobs: false,
    builds: false,
    all: false,
  });
  
  // 搜索和过滤状态
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');

  const { toast } = useToast();

  // 获取 Jenkins 实例列表
  const loadJenkinsList = async () => {
    try {
      const data = await getJenkinsInstances();
      setJenkinsList(data);
      if (!currentJenkinsId && data.length > 0) {
        setCurrentJenkinsId(String(data[0].id));
      }
    } 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);
      // 设置默认视图
      if (data.jenkinsViewList.length > 0 && !currentView) {
        setCurrentView(data.jenkinsViewList[0].id);
      }
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '获取实例详情失败',
        duration: 3000,
      });
    } finally {
      setLoading(false);
    }
  };

  // 切换 Jenkins 实例
  const handleJenkinsChange = (id: string) => {
    setCurrentJenkinsId(id);
    setInstanceDetails(undefined);
    setCurrentView(undefined);
    setSearchKeyword('');
    setStatusFilter('all');
  };

  // 单个同步
  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: 2000,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '同步失败',
        duration: 3000,
      });
    } finally {
      setSyncing((prev) => ({ ...prev, [type]: false }));
    }
  };

  // 全部同步
  const handleSyncAll = async () => {
    if (!currentJenkinsId) return;
    setSyncing((prev) => ({ ...prev, all: true }));
    try {
      await Promise.all([
        syncViews(currentJenkinsId),
        syncJobs(currentJenkinsId),
        syncBuilds(currentJenkinsId),
      ]);
      await loadInstanceDetails();
      toast({
        title: '全部同步成功',
        duration: 2000,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '同步失败',
        description: '部分数据同步失败，请重试',
        duration: 3000,
      });
    } finally {
      setSyncing((prev) => ({ ...prev, all: false }));
    }
  };

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

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

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

  // 获取构建状态信息
  const getBuildStatusInfo = (status: string) => {
    const statusMap: Record<string, { variant: 'default' | 'destructive' | 'secondary' | 'outline', icon: React.ReactNode, label: string }> = {
      SUCCESS: {
        variant: 'default',
        icon: <CheckCircle className="h-3 w-3" />,
        label: '成功',
      },
      FAILURE: {
        variant: 'destructive',
        icon: <XCircle className="h-3 w-3" />,
        label: '失败',
      },
      UNSTABLE: {
        variant: 'secondary',
        icon: <AlertTriangle className="h-3 w-3" />,
        label: '不稳定',
      },
      ABORTED: {
        variant: 'outline',
        icon: <XCircle className="h-3 w-3" />,
        label: '已中止',
      },
      RUNNING: {
        variant: 'outline',
        icon: <Loader2 className="h-3 w-3 animate-spin" />,
        label: '构建中',
      },
    };
    return statusMap[status] || {
      variant: 'outline' as const,
      icon: <AlertTriangle className="h-3 w-3" />,
      label: status || '未知',
    };
  };

  // 获取健康度颜色
  const getHealthColor = (score: number) => {
    if (score >= 80) return 'bg-green-500';
    if (score >= 60) return 'bg-green-400';
    if (score >= 40) return 'bg-yellow-400';
    if (score >= 20) return 'bg-orange-400';
    return 'bg-red-500';
  };

  // 过滤和搜索 Jobs
  const filteredJobs = useMemo(() => {
    if (!instanceDetails) return [];
    
    let jobs = instanceDetails.jenkinsJobList;
    
    // 按 View 过滤
    if (currentView) {
      jobs = jobs.filter((job) => job.viewId === currentView);
    }
    
    // 按搜索关键词过滤
    if (searchKeyword) {
      jobs = jobs.filter((job) =>
        job.jobName.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        job.description?.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }
    
    // 按状态过滤
    if (statusFilter !== 'all') {
      jobs = jobs.filter((job) => job.lastBuildStatus === statusFilter);
    }
    
    return jobs;
  }, [instanceDetails, currentView, searchKeyword, statusFilter]);

  // 空状态：没有实例
  if (jenkinsList.length === 0) {
    return (
      <PageContainer>
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-3xl font-bold tracking-tight">Jenkins 三方管理</h2>
        </div>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16">
            <Activity className="h-16 w-16 text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold mb-2">暂无 Jenkins 实例</h3>
            <p className="text-sm text-muted-foreground mb-4">
              请先在外部服务管理中添加 Jenkins 系统
            </p>
            <Button onClick={() => window.location.href = '/deploy/external'}>
              前往外部服务管理
            </Button>
          </CardContent>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold tracking-tight">Jenkins 三方管理</h2>
        <div className="flex items-center gap-4">
          <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>
          <Button
            onClick={handleSyncAll}
            disabled={syncing.all}
            variant="outline"
          >
            {syncing.all ? (
              <Loader2 className="h-4 w-4 animate-spin mr-2" />
            ) : (
              <RefreshCw className="h-4 w-4 mr-2" />
            )}
            全部同步
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card className="min-h-[140px]">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Views</CardTitle>
            <div className="flex items-center gap-2">
              <Layers className="h-4 w-4 text-muted-foreground" />
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={() => handleSync('views')}
                disabled={syncing.views}
              >
                <RefreshCw className={`h-3 w-3 ${syncing.views ? 'animate-spin' : ''}`} />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{instanceDetails?.totalViews || 0}</div>
            <p className="text-xs text-muted-foreground mt-1">
              最后同步: {formatTime(instanceDetails?.lastSyncViewsTime)}
            </p>
          </CardContent>
        </Card>

        <Card className="min-h-[140px]">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Jobs</CardTitle>
            <div className="flex items-center gap-2">
              <Box className="h-4 w-4 text-muted-foreground" />
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={() => handleSync('jobs')}
                disabled={syncing.jobs}
              >
                <RefreshCw className={`h-3 w-3 ${syncing.jobs ? 'animate-spin' : ''}`} />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{instanceDetails?.totalJobs || 0}</div>
            <p className="text-xs text-muted-foreground mt-1">
              最后同步: {formatTime(instanceDetails?.lastSyncJobsTime)}
            </p>
          </CardContent>
        </Card>

        <Card className="min-h-[140px]">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Builds</CardTitle>
            <div className="flex items-center gap-2">
              <Activity className="h-4 w-4 text-muted-foreground" />
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={() => handleSync('builds')}
                disabled={syncing.builds}
              >
                <RefreshCw className={`h-3 w-3 ${syncing.builds ? 'animate-spin' : ''}`} />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{instanceDetails?.totalBuilds || 0}</div>
            <p className="text-xs text-muted-foreground mt-1">
              最后同步: {formatTime(instanceDetails?.lastSyncBuildsTime)}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* View 切换 */}
      {instanceDetails && instanceDetails.jenkinsViewList.length > 0 && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex gap-2 overflow-x-auto pb-2">
              {instanceDetails.jenkinsViewList.map((view) => (
                <Button
                  key={view.id}
                  variant={currentView === view.id ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setCurrentView(view.id)}
                  className="whitespace-nowrap"
                >
                  {view.viewName}
                </Button>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 搜索和过滤 */}
      {instanceDetails && instanceDetails.jenkinsViewList.length > 0 && (
        <Card>
          <div className="p-6">
            <div className="flex items-center gap-4">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索 Job 名称或描述..."
                  value={searchKeyword}
                  onChange={(e) => setSearchKeyword(e.target.value)}
                  className="pl-9"
                />
              </div>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="构建状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="SUCCESS">成功</SelectItem>
                  <SelectItem value="FAILURE">失败</SelectItem>
                  <SelectItem value="UNSTABLE">不稳定</SelectItem>
                  <SelectItem value="RUNNING">构建中</SelectItem>
                </SelectContent>
              </Select>
              <Button
                variant="outline"
                onClick={() => {
                  setSearchKeyword('');
                  setStatusFilter('all');
                }}
              >
                重置
              </Button>
            </div>
          </div>
        </Card>
      )}

      {/* Jobs 表格 */}
      {loading ? (
        <Card>
          <CardContent className="flex items-center justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          </CardContent>
        </Card>
      ) : instanceDetails && instanceDetails.jenkinsViewList.length > 0 ? (
        <Card>
          <CardHeader>
            <CardTitle>
              {instanceDetails.jenkinsViewList.find((v) => v.id === currentView)?.viewName || 'Jobs'} 列表
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[250px]">Job 名称</TableHead>
                    <TableHead className="w-[300px]">描述</TableHead>
                    <TableHead className="w-[100px]">最后构建</TableHead>
                    <TableHead className="w-[120px]">状态</TableHead>
                    <TableHead className="w-[120px]">健康度</TableHead>
                    <TableHead className="w-[180px]">构建时间</TableHead>
                    <TableHead className="w-[100px]">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredJobs.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="h-24 text-center">
                        <div className="flex flex-col items-center justify-center text-muted-foreground">
                          <Box className="h-8 w-8 mb-2" />
                          <p>暂无任务</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredJobs.map((job) => {
                      const statusInfo = getBuildStatusInfo(job.lastBuildStatus);
                      return (
                        <TableRow key={job.id}>
                          <TableCell className="font-medium">
                            <div className="flex items-center gap-2">
                              <span className="truncate">{job.jobName}</span>
                            </div>
                          </TableCell>
                          <TableCell className="text-muted-foreground text-sm">
                            {job.description || '-'}
                          </TableCell>
                          <TableCell>
                            <span className="text-sm">#{job.lastBuildNumber}</span>
                          </TableCell>
                          <TableCell>
                            <Badge variant={statusInfo.variant} className="inline-flex items-center gap-1">
                              {statusInfo.icon}
                              {statusInfo.label}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <Progress
                                value={job.healthReportScore}
                                className="h-2"
                                indicatorClassName={getHealthColor(job.healthReportScore)}
                              />
                              <span className="text-xs text-muted-foreground">{job.healthReportScore}%</span>
                            </div>
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            {formatTime(job.lastBuildTime)}
                          </TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={(e) => {
                                e.preventDefault();
                                // 确保使用绝对 URL
                                const url = job.jobUrl.startsWith('http') 
                                  ? job.jobUrl 
                                  : `${jenkinsList.find(j => j.id === Number(currentJenkinsId))?.url || ''}${job.jobUrl}`;
                                window.open(url, '_blank', 'noopener,noreferrer');
                              }}
                            >
                              <ExternalLink className="h-4 w-4 mr-1" />
                              查看
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16">
            <Layers className="h-16 w-16 text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold mb-2">暂无视图数据</h3>
            <p className="text-sm text-muted-foreground mb-4">
              请点击上方的同步按钮获取 Jenkins 数据
            </p>
            <Button onClick={handleSyncAll} disabled={syncing.all}>
              {syncing.all ? (
                <Loader2 className="h-4 w-4 animate-spin mr-2" />
              ) : (
                <RefreshCw className="h-4 w-4 mr-2" />
              )}
              立即同步
            </Button>
          </CardContent>
        </Card>
      )}
    </PageContainer>
  );
};

export default JenkinsManagerList;
