import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogBody,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Search, Check, ChevronDown, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useToast } from '@/components/ui/use-toast';
import type {
  TeamApplication,
  Application,
  BuildType,
} from '../types';
import { BUILD_TYPE_OPTIONS } from '../types';
import type { RepositoryBranchResponse } from '@/pages/Resource/Git/List/types';
import type { WorkflowDefinition } from '@/pages/Workflow/Definition/List/types';
import { getExternalSystemList } from '@/pages/Resource/External/List/service';
import { getRepositoryProjectsList, getRepositoryBranchesList } from '@/pages/Resource/Git/List/service';
import { GitConfigSelector } from './GitConfigSelector';

interface TeamApplicationDialogProps {
  open: boolean;
  mode: 'create' | 'edit';
  teamId: number;
  environmentId: number;
  environmentName: string;
  enableGitSyncCheck: boolean; // 🆕 团队是否启用Git同步检测
  application?: TeamApplication; // 编辑时传入
  applications: Application[]; // 可选择的应用列表
  jenkinsSystems: any[];
  workflowDefinitions: WorkflowDefinition[];
  existingApplicationIds?: number[]; // 已添加的应用ID列表（用于过滤）
  onOpenChange: (open: boolean) => void;
  onSave: (data: {
    id?: number;
    appId: number;
    buildType: BuildType | null;
    sourceBranch: string;
    deploySystemId: number | null;
    deployJob: string;
    workflowDefinitionId: number | null;
    sourceGitSystemId: number | null;
    sourceGitProjectId: number | null;
    targetGitSystemId: number | null;    // 🆕 目标Git系统ID
    targetGitProjectId: number | null;   // 🆕 目标Git项目ID
    targetBranch: string;                 // 🆕 目标分支
  }) => Promise<void>;
  onLoadBranches: (appId: number, app: Application) => Promise<RepositoryBranchResponse[]>;
  onLoadJenkinsJobs: (systemId: number) => Promise<any[]>;
}

const TeamApplicationDialog: React.FC<TeamApplicationDialogProps> = ({
  open,
  mode,
  teamId,
  environmentId,
  environmentName,
  enableGitSyncCheck,
  application,
  applications,
  jenkinsSystems,
  workflowDefinitions,
  existingApplicationIds = [],
  onOpenChange,
  onSave,
  onLoadBranches,
  onLoadJenkinsJobs,
}) => {
  const { toast } = useToast();

  // 表单状态
  const [formData, setFormData] = useState({
    appId: 0,
    buildType: 'JENKINS' as 'JENKINS' | 'NATIVE' | null,
    sourceBranch: '',                               // 源分支名称
    deploySystemId: null as number | null,
    deployJob: '',
    workflowDefinitionId: null as number | null,
    sourceGitSystemId: null as number | null,      // 源Git系统ID
    sourceGitProjectId: null as number | null,     // 源Git项目ID
    targetGitSystemId: null as number | null,      // 目标Git系统ID
    targetGitProjectId: null as number | null,     // 目标Git项目ID
    targetBranch: '',                               // 目标分支名称
  });

  // 加载状态
  const [branches, setBranches] = useState<RepositoryBranchResponse[]>([]);
  const [loadingBranches, setLoadingBranches] = useState(false);
  const [jenkinsJobs, setJenkinsJobs] = useState<any[]>([]);
  const [loadingJobs, setLoadingJobs] = useState(false);
  const [saving, setSaving] = useState(false);
  const [gitSystems, setGitSystems] = useState<any[]>([]);
  const [repoProjects, setRepoProjects] = useState<any[]>([]);
  const [loadingRepoProjects, setLoadingRepoProjects] = useState(false);
  // 🆕 目标Git相关状态
  const [targetRepoProjects, setTargetRepoProjects] = useState<any[]>([]);
  const [loadingTargetRepoProjects, setLoadingTargetRepoProjects] = useState(false);
  const [targetBranches, setTargetBranches] = useState<RepositoryBranchResponse[]>([]);
  const [loadingTargetBranches, setLoadingTargetBranches] = useState(false);

  // 搜索和弹窗状态
  const [appSearchValue, setAppSearchValue] = useState('');
  const [appPopoverOpen, setAppPopoverOpen] = useState(false);
  const [jobSearchValue, setJobSearchValue] = useState('');
  const [jobPopoverOpen, setJobPopoverOpen] = useState(false);

  // 初始化表单数据
  useEffect(() => {
    if (open) {
      if (mode === 'edit' && application) {
        // 编辑模式：填充现有数据
        setFormData({
          appId: application.applicationId,
          buildType: application.buildType || 'JENKINS',
          sourceBranch: application.sourceBranch || '',
          deploySystemId: application.deploySystemId || null,
          deployJob: application.deployJob || '',
          workflowDefinitionId: application.workflowDefinitionId || null,
          sourceGitSystemId: application.sourceGitSystemId || null,
          sourceGitProjectId: application.sourceGitProjectId || null,
          targetGitSystemId: application.targetGitSystemId || null,
          targetGitProjectId: application.targetGitProjectId || null,
          targetBranch: application.targetBranch || '',
        });

        // 加载源仓库项目
        if (application.sourceGitSystemId) {
          loadRepoProjects(application.sourceGitSystemId);
        }
        
        // 加载源分支（优先使用代码源信息，向后兼容旧数据）
        if (application.sourceGitSystemId && application.sourceGitProjectId) {
          // 使用代码源信息加载分支
          loadBranchesFromCodeSource(application.sourceGitSystemId, application.sourceGitProjectId);
        } else {
          // 向后兼容：使用应用信息加载分支
          const app = applications.find(a => a.id === application.applicationId);
          if (app) {
            loadBranches(application.applicationId, app);
          }
        }
        
        // 🆕 加载目标仓库项目（如果有）
        if (application.targetGitSystemId) {
          loadTargetRepoProjects(application.targetGitSystemId);
        }
        
        // 🆕 加载目标分支（如果有）
        if (application.targetGitSystemId && application.targetGitProjectId) {
          loadTargetBranches(application.targetGitSystemId, application.targetGitProjectId);
        }
        
        // 加载Jenkins Jobs
        if (application.deploySystemId) {
          loadJenkinsJobs(application.deploySystemId);
        }
      } else {
        // 新建模式：重置表单
        setFormData({
          appId: null,
          buildType: 'JENKINS',
          sourceBranch: '',
          deploySystemId: null,
          deployJob: '',
          workflowDefinitionId: null,
          sourceGitSystemId: null,
          sourceGitProjectId: null,
          targetGitSystemId: null,
          targetGitProjectId: null,
          targetBranch: '',
        });
        setBranches([]);
        setJenkinsJobs([]);
      }
    }
  }, [open, mode, application]);

  // 加载分支列表
  const loadBranches = async (appId: number, app: Application) => {
    setLoadingBranches(true);
    try {
      const branchList = await onLoadBranches(appId, app);
      setBranches(branchList || []);
    } catch (error) {
      console.error('加载分支失败:', error);
      setBranches([]);
    } finally {
      setLoadingBranches(false);
    }
  };

  // 加载 Jenkins Jobs
  const loadJenkinsJobs = async (systemId: number) => {
    setLoadingJobs(true);
    try {
      const jobs = await onLoadJenkinsJobs(systemId);
      setJenkinsJobs(jobs || []);
    } catch (error) {
      console.error('加载Jenkins Jobs失败:', error);
      setJenkinsJobs([]);
    } finally {
      setLoadingJobs(false);
    }
  };

  // 加载Git系统列表
  const loadGitSystems = async () => {
    try {
      const systems = await getExternalSystemList({ type: 'GIT' });
      setGitSystems(systems || []);
    } catch (error) {
      console.error('加载Git系统失败:', error);
      setGitSystems([]);
    }
  };

  // 加载源仓库项目列表
  const loadRepoProjects = async (externalSystemId: number) => {
    setLoadingRepoProjects(true);
    try {
      const projects = await getRepositoryProjectsList({ externalSystemId });
      setRepoProjects(projects || []);
    } catch (error) {
      console.error('加载源仓库项目失败:', error);
      setRepoProjects([]);
    } finally {
      setLoadingRepoProjects(false);
    }
  };

  // 🆕 加载目标仓库项目列表
  const loadTargetRepoProjects = async (externalSystemId: number) => {
    setLoadingTargetRepoProjects(true);
    try {
      const projects = await getRepositoryProjectsList({ externalSystemId });
      setTargetRepoProjects(projects || []);
    } catch (error) {
      console.error('加载目标仓库项目失败:', error);
      setTargetRepoProjects([]);
    } finally {
      setLoadingTargetRepoProjects(false);
    }
  };

  // 初始化加载Git系统列表
  useEffect(() => {
    if (open) {
      loadGitSystems();
    }
  }, [open]);

  // 处理应用选择
  const handleAppChange = (appId: number) => {
    setFormData({
      appId: appId,
      buildType: formData.buildType,
      sourceBranch: '',
      deploySystemId: null,
      deployJob: '',
      workflowDefinitionId: null,
      sourceGitSystemId: null,
      sourceGitProjectId: null,
      targetGitSystemId: null,
      targetGitProjectId: null,
      targetBranch: '',
    });
    // 清空分支列表（分支现在基于代码源，不基于应用）
    setBranches([]);
  };

  // 处理构建类型选择
  const handleBuildTypeChange = (buildType: BuildType) => {
    setFormData({
      ...formData,
      buildType,
      // 切换构建类型时清空 Jenkins 相关配置
      deploySystemId: null,
      deployJob: '',
    });
    setJenkinsJobs([]);
  };

  // 处理 Jenkins 系统选择
  const handleJenkinsSystemChange = (systemId: number) => {
    setFormData({
      ...formData,
      deploySystemId: systemId,
      deployJob: '',
    });
    loadJenkinsJobs(systemId);
  };

  // 加载基于源代码的分支列表
  const loadBranchesFromCodeSource = async (externalSystemId: number, repoProjectId: number) => {
    setLoadingBranches(true);
    try {
      const branchList = await getRepositoryBranchesList({ externalSystemId, repoProjectId });
      setBranches(branchList || []);
    } catch (error) {
      console.error('加载源分支失败:', error);
      setBranches([]);
    } finally {
      setLoadingBranches(false);
    }
  };

  // 🆕 加载目标分支列表
  const loadTargetBranches = async (externalSystemId: number, repoProjectId: number) => {
    setLoadingTargetBranches(true);
    try {
      const branchList = await getRepositoryBranchesList({ externalSystemId, repoProjectId });
      setTargetBranches(branchList || []);
    } catch (error) {
      console.error('加载目标分支失败:', error);
      setTargetBranches([]);
    } finally {
      setLoadingTargetBranches(false);
    }
  };

  // 处理源代码系统选择
  const handleCodeSourceSystemChange = (systemId: number) => {
    setFormData({
      ...formData,
      sourceGitSystemId: systemId,
      sourceGitProjectId: null,
      sourceBranch: '', // 清空分支
    });
    setBranches([]); // 清空分支列表
    loadRepoProjects(systemId);
  };

  // 处理源仓库项目选择
  const handleCodeSourceProjectChange = (projectId: number) => {
    setFormData({
      ...formData,
      sourceGitProjectId: projectId,
      sourceBranch: '', // 清空分支
    });
    // 加载该项目的分支
    if (formData.sourceGitSystemId) {
      loadBranchesFromCodeSource(formData.sourceGitSystemId, projectId);
    }
  };

  // 🆕 处理目标Git系统选择
  const handleTargetGitSystemChange = (systemId: number) => {
    setFormData({
      ...formData,
      targetGitSystemId: systemId,
      targetGitProjectId: null,
      targetBranch: '', // 清空分支
    });
    setTargetBranches([]); // 清空分支列表
    loadTargetRepoProjects(systemId);
  };

  // 🆕 处理目标仓库项目选择
  const handleTargetGitProjectChange = (projectId: number) => {
    setFormData({
      ...formData,
      targetGitProjectId: projectId,
      targetBranch: '', // 清空分支
    });
    // 加载该项目的分支
    if (formData.targetGitSystemId) {
      loadTargetBranches(formData.targetGitSystemId, projectId);
    }
  };

  // 保存
  const handleSave = async () => {
    // 表单验证
    if (!formData.appId) {
      toast({
        variant: 'destructive',
        title: '请选择应用',
      });
      return;
    }

    // 源Git级联验证
    if (formData.sourceGitSystemId) {
      if (!formData.sourceGitProjectId) {
        toast({
          variant: 'destructive',
          title: '请选择源仓库项目',
          description: '已选择源Git系统，必须选择对应的仓库项目',
        });
        return;
      }
      if (!formData.sourceBranch) {
        toast({
          variant: 'destructive',
          title: '请选择源分支',
          description: '已选择源Git系统，必须选择对应的分支',
        });
        return;
      }
    }

    // 目标Git级联验证
    if (formData.targetGitSystemId) {
      if (!formData.targetGitProjectId) {
        toast({
          variant: 'destructive',
          title: '请选择目标仓库项目',
          description: '已选择目标Git系统，必须选择对应的仓库项目',
        });
        return;
      }
      if (!formData.targetBranch) {
        toast({
          variant: 'destructive',
          title: '请选择目标分支',
          description: '已选择目标Git系统，必须选择对应的分支',
        });
        return;
      }
    }

    setSaving(true);
    try {
      await onSave({
        id: mode === 'edit' && application ? application.id : undefined,
        appId: formData.appId,
        buildType: formData.buildType,
        sourceBranch: formData.sourceBranch,
        deploySystemId: formData.buildType === 'JENKINS' ? formData.deploySystemId : null,
        deployJob: formData.buildType === 'JENKINS' ? formData.deployJob : '',
        workflowDefinitionId: formData.workflowDefinitionId,
        sourceGitSystemId: formData.sourceGitSystemId,
        sourceGitProjectId: formData.sourceGitProjectId,
        targetGitSystemId: formData.targetGitSystemId,
        targetGitProjectId: formData.targetGitProjectId,
        targetBranch: formData.targetBranch,
      });

      toast({
        title: mode === 'edit' ? '保存成功' : '添加成功',
      });
      onOpenChange(false);
    } catch (error: any) {
      // 错误已经在 request.ts 中通过 toast 显示了，这里不需要再显示
    } finally {
      setSaving(false);
    }
  };

  // Job 过滤
  const filteredJobs = jenkinsJobs.filter(job =>
    job.jobName.toLowerCase().includes(jobSearchValue.toLowerCase())
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl h-[680px] flex flex-col">
        <DialogHeader>
          <DialogTitle>
            {mode === 'edit' ? '编辑' : '添加'}应用配置 - {environmentName}
          </DialogTitle>
        </DialogHeader>

        <DialogBody className="flex-1 overflow-y-auto">
          <div className="space-y-4">
          {/* 应用选择 */}
          <div className="space-y-2">
            <Label>
              应用 <span className="text-destructive">*</span>
            </Label>
            {mode === 'edit' ? (
              // 编辑模式：显示只读输入框
              <>
                <Input
                  value={(() => {
                    const app = applications.find(a => a.id === formData.appId);
                    if (!app) return '';
                    const category = app.applicationCategory?.name || '未分类';
                    return `${category}/${app.appCode}（${app.appName}）`;
                  })()}
                  disabled
                />
                <p className="text-xs text-muted-foreground">
                  编辑时不可修改应用，如需更换请删除后重新添加
                </p>
              </>
            ) : (
              // 新建模式：使用 Popover + Command 组件
              <Popover open={appPopoverOpen} onOpenChange={setAppPopoverOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    className={cn(
                      'w-full justify-between',
                      !formData.appId && 'text-muted-foreground'
                    )}
                  >
                    {formData.appId ? (() => {
                      const app = applications.find(a => a.id === formData.appId);
                      if (!app) return '选择应用';
                      const category = app.applicationCategory?.name || '未分类';
                      return `${category}/${app.appCode}（${app.appName}）`;
                    })() : '选择应用'}
                    <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
                  <div className="flex items-center border-b px-3">
                    <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                    <input
                      placeholder="搜索应用..."
                      className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"
                      value={appSearchValue}
                      onChange={(e) => setAppSearchValue(e.target.value)}
                    />
                  </div>
                  <ScrollArea className="h-[200px]">
                    <div className="p-1">
                      {(() => {
                        // 过滤掉已添加的应用
                        const availableApps = applications.filter(app => !existingApplicationIds.includes(app.id));
                        // 搜索过滤
                        const filteredApps = availableApps.filter(app =>
                          app.appName.toLowerCase().includes(appSearchValue.toLowerCase()) ||
                          app.appCode.toLowerCase().includes(appSearchValue.toLowerCase()) ||
                          (app.applicationCategory?.name || '').toLowerCase().includes(appSearchValue.toLowerCase())
                        );
                        
                        if (filteredApps.length === 0) {
                          return (
                            <div className="p-4 text-center text-sm text-muted-foreground">
                              {availableApps.length === 0 ? '暂无可添加的应用' : '未找到应用'}
                            </div>
                          );
                        }
                        
                        return filteredApps.map((app) => {
                          const category = app.applicationCategory?.name || '未分类';
                          return (
                            <div
                              key={app.id}
                              className={cn(
                                'relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground',
                                app.id === formData.appId && 'bg-accent text-accent-foreground'
                              )}
                              onClick={() => {
                                handleAppChange(app.id);
                                setAppSearchValue('');
                                setAppPopoverOpen(false);
                              }}
                            >
                              <div className="flex-1 truncate">
                                <span className="text-muted-foreground">{category} / </span>
                                <span className="font-medium">{app.appCode}</span>
                                <span className="text-muted-foreground">（{app.appName}）</span>
                              </div>
                              {app.id === formData.appId && (
                                <Check className="ml-2 h-4 w-4" />
                              )}
                            </div>
                          );
                        });
                      })()}
                    </div>
                  </ScrollArea>
                </PopoverContent>
              </Popover>
            )}
          </div>

          {/* 构建类型选择 */}
          <div className="space-y-2">
            <Label>
              构建类型 <span className="text-destructive">*</span>
            </Label>
            <Select
              value={formData.buildType || ''}
              onValueChange={(value) => handleBuildTypeChange(value as BuildType)}
            >
              <SelectTrigger>
                <SelectValue placeholder="选择构建类型" />
              </SelectTrigger>
              <SelectContent>
                {BUILD_TYPE_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground">
              Jenkins构建：通过Jenkins执行构建任务；脚本部署：通过自定义脚本执行部署
            </p>
          </div>

          {/* Jenkins 系统 - 仅在构建类型为 JENKINS 时显示 */}
          {formData.buildType === 'JENKINS' && (
            <div className="space-y-2">
              <Label>Jenkins系统</Label>
              <Select
                value={formData.deploySystemId?.toString() || ''}
                onValueChange={(value) =>
                  handleJenkinsSystemChange(Number(value))
                }
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择Jenkins系统" />
                </SelectTrigger>
                <SelectContent>
                  {jenkinsSystems.length === 0 ? (
                    <div className="p-4 text-center text-sm text-muted-foreground">
                      暂无Jenkins系统
                    </div>
                  ) : (
                    jenkinsSystems.map((system) => (
                      <SelectItem key={system.id} value={system.id.toString()}>
                        {system.name}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* Jenkins Job - 仅在构建类型为 JENKINS 时显示 */}
          {formData.buildType === 'JENKINS' && (
            <div className="space-y-2">
              <Label>Jenkins Job</Label>
              {formData.deploySystemId ? (
                <Popover open={jobPopoverOpen} onOpenChange={setJobPopoverOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      disabled={loadingJobs || jenkinsJobs.length === 0}
                      className={cn(
                        'w-full justify-between',
                        !formData.deployJob && 'text-muted-foreground'
                      )}
                    >
                      <span className="truncate">
                        {formData.deployJob ||
                          (loadingJobs
                            ? '加载中...'
                            : jenkinsJobs.length === 0
                            ? '无Job'
                            : '选择Job')}
                      </span>
                      <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-full p-0">
                    <div className="flex items-center border-b px-3">
                      <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                      <input
                        placeholder="搜索Job..."
                        className="flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"
                        value={jobSearchValue}
                        onChange={(e) => setJobSearchValue(e.target.value)}
                      />
                    </div>
                    <ScrollArea className="h-[200px]">
                      <div className="p-1">
                        {filteredJobs.length === 0 ? (
                          <div className="p-4 text-center text-sm text-muted-foreground">
                            未找到Job
                          </div>
                        ) : (
                          filteredJobs.map((job) => (
                            <div
                              key={job.id}
                              className={cn(
                                'relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent',
                                job.jobName === formData.deployJob && 'bg-accent'
                              )}
                              onClick={() => {
                                setFormData({
                                  ...formData,
                                  deployJob: job.jobName,
                                });
                                setJobSearchValue('');
                                setJobPopoverOpen(false);
                              }}
                            >
                              <span className="flex-1 truncate">
                                {job.jobName}
                              </span>
                              {job.jobName === formData.deployJob && (
                                <Check className="ml-2 h-4 w-4" />
                              )}
                            </div>
                          ))
                        )}
                      </div>
                    </ScrollArea>
                  </PopoverContent>
                </Popover>
              ) : (
                <Input placeholder="请先选择Jenkins系统" disabled />
              )}
            </div>
          )}

          {/* 源Git配置 */}
          <GitConfigSelector
            label="源"
            gitSystems={gitSystems}
            selectedSystemId={formData.sourceGitSystemId}
            onSystemChange={handleCodeSourceSystemChange}
            repoProjects={repoProjects}
            loadingRepoProjects={loadingRepoProjects}
            selectedProjectId={formData.sourceGitProjectId}
            onProjectChange={handleCodeSourceProjectChange}
            branches={branches}
            loadingBranches={loadingBranches}
            selectedBranch={formData.sourceBranch}
            onBranchChange={(sourceBranch) => setFormData({ ...formData, sourceBranch })}
          />

          {/* 🆕 目标Git配置（仅当启用Git同步检测时显示） */}
          {enableGitSyncCheck && (
            <GitConfigSelector
              label="目标"
              gitSystems={gitSystems}
              selectedSystemId={formData.targetGitSystemId}
              onSystemChange={handleTargetGitSystemChange}
              repoProjects={targetRepoProjects}
              loadingRepoProjects={loadingTargetRepoProjects}
              selectedProjectId={formData.targetGitProjectId}
              onProjectChange={handleTargetGitProjectChange}
              branches={targetBranches}
              loadingBranches={loadingTargetBranches}
              selectedBranch={formData.targetBranch}
              onBranchChange={(branch) => setFormData({ ...formData, targetBranch: branch })}
            />
          )}

          {/* 工作流定义 */}
          <div className="space-y-2">
            <Label>流程</Label>
            <Select
              value={formData.workflowDefinitionId?.toString() || ''}
              onValueChange={(value) =>
                setFormData({
                  ...formData,
                  workflowDefinitionId: Number(value),
                })
              }
            >
              <SelectTrigger>
                <SelectValue placeholder="选择工作流" />
              </SelectTrigger>
              <SelectContent>
                {workflowDefinitions.length === 0 ? (
                  <div className="p-4 text-center text-sm text-muted-foreground">
                    暂无已发布的工作流
                  </div>
                ) : (
                  workflowDefinitions.map((workflow) => (
                    <SelectItem key={workflow.id} value={workflow.id.toString()}>
                      {workflow.name}
                    </SelectItem>
                  ))
                )}
              </SelectContent>
            </Select>
          </div>
          </div>
        </DialogBody>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSave} disabled={saving}>
            {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {mode === 'edit' ? '保存' : '添加'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export { TeamApplicationDialog };
export default TeamApplicationDialog;

