import React, { useEffect, useState, useMemo, useRef } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogBody,
} from '@/components/ui/dialog';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { PaginatedTable, type ColumnDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import { Plus, Edit, Trash2, GitBranch } from 'lucide-react';
import type { Environment } from '@/pages/Deploy/Environment/List/types';
import type { TeamApplication, Application } from '../types';
import type { WorkflowDefinition } from '@/pages/Workflow/Definition/List/types';
import {
  getTeamApplicationsPage,
  deleteTeamApplication,
  getApplicationList,
  getJenkinsSystems,
  getJenkinsJobs,
  getWorkflowDefinitions,
  createTeamApplication,
  updateTeamApplication,
} from '../service';
import { getRepositoryBranchesList } from '@/pages/Resource/Git/List/service';
import TeamApplicationDialog from './TeamApplicationDialog';

interface TeamApplicationManageDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  teamId: number;
  enableGitSyncCheck: boolean; // 🆕 团队是否启用Git同步检测
  environmentId?: number; // 可选：如果指定，则只管理该环境的应用
  environments: Environment[];
  onSuccess?: () => void;
}

export const TeamApplicationManageDialog: React.FC<
  TeamApplicationManageDialogProps
> = ({ open, onOpenChange, teamId, enableGitSyncCheck, environmentId, environments, onSuccess }) => {
  const { toast } = useToast();
  const tableRef = useRef<PaginatedTableRef<TeamApplication>>(null);
  const [teamApplications, setTeamApplications] = useState<TeamApplication[]>([]);
  // 如果从环境管理进入，只显示该环境的应用；否则显示所有应用
  const selectedEnvironmentId = environmentId || null;

  // 基础数据状态
  const [applications, setApplications] = useState<Application[]>([]);
  const [jenkinsSystems, setJenkinsSystems] = useState<any[]>([]);
  const [workflowDefinitions, setWorkflowDefinitions] = useState<WorkflowDefinition[]>([]);

  // 应用配置对话框状态
  const [appDialogOpen, setAppDialogOpen] = useState(false);
  const [appDialogMode, setAppDialogMode] = useState<'create' | 'edit'>('create');
  const [editingApp, setEditingApp] = useState<TeamApplication | null>(null);
  const [editingEnvironment, setEditingEnvironment] = useState<Environment | null>(null);

  // 删除确认对话框状态
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingApp, setDeletingApp] = useState<TeamApplication | null>(null);

  // 加载基础数据
  useEffect(() => {
    if (open) {
      loadBaseData();
    }
  }, [open]);

  const loadBaseData = async () => {
    try {
      const [appsData, jenkinsData, workflowsData] = await Promise.all([
        getApplicationList(),
        getJenkinsSystems(),
        getWorkflowDefinitions(),
      ]);
      setApplications(appsData || []);
      setJenkinsSystems(jenkinsData || []);
      setWorkflowDefinitions(workflowsData || []);
    } catch (error: any) {
      toast({
        title: '加载基础数据失败',
        description: error.message || '无法加载应用、Jenkins和工作流数据',
        variant: 'destructive',
      });
    }
  };

  // 包装 fetchFn
  const fetchData = async (query: any) => {
    const result = await getTeamApplicationsPage({
      ...query,
      teamId,
      environmentId: selectedEnvironmentId || undefined,
    });
    setTeamApplications(result.content || []);
    return result;
  };

  const handleOpenAddAppDialog = () => {
    // 如果指定了环境，使用指定的环境；否则使用第一个环境
    const defaultEnv = selectedEnvironmentId 
      ? environments.find(e => e.id === selectedEnvironmentId) || environments[0]
      : environments[0];
    setAppDialogMode('create');
    setEditingApp(null);
    setEditingEnvironment(defaultEnv);
    setAppDialogOpen(true);
  };

  const handleOpenEditAppDialog = (app: TeamApplication) => {
    const env = environments.find(e => e.id === app.environmentId);
    setAppDialogMode('edit');
    setEditingApp(app);
    setEditingEnvironment(env || null);
    setAppDialogOpen(true);
  };

  const handleSaveApplication = async (data: {
    id?: number;
    appId: number;
    buildType: 'JENKINS' | 'NATIVE' | 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;                 // 🆕 目标分支
  }) => {
    if (!editingEnvironment) return;

    const payload = {
      teamId,
      applicationId: data.appId,
      environmentId: editingEnvironment.id,
      buildType: data.buildType || undefined,
      sourceBranch: data.sourceBranch,
      // 只有当 buildType 为 JENKINS 时才传递 Jenkins 相关字段
      deploySystemId: data.buildType === 'JENKINS' ? (data.deploySystemId || undefined) : undefined,
      deployJob: data.buildType === 'JENKINS' ? data.deployJob : '',
      workflowDefinitionId: data.workflowDefinitionId || undefined,
      sourceGitSystemId: data.sourceGitSystemId || undefined,
      sourceGitProjectId: data.sourceGitProjectId || undefined,
      // 🆕 目标Git相关字段
      targetGitSystemId: data.targetGitSystemId || undefined,
      targetGitProjectId: data.targetGitProjectId || undefined,
      targetBranch: data.targetBranch || undefined,
    };

    if (appDialogMode === 'edit' && data.id) {
      await updateTeamApplication(data.id, payload);
    } else {
      await createTeamApplication(payload);
    }

    // 刷新应用列表
    tableRef.current?.refresh();
  };

  const handleLoadBranches = async (_appId: number, app: Application) => {
    if (!app.repoProjectId || !app.externalSystemId) {
      return [];
    }
    // 使用不分页的列表接口
    const result = await getRepositoryBranchesList({
      externalSystemId: app.externalSystemId,
      repoProjectId: app.repoProjectId,
    });
    // getRepositoryBranchesList 直接返回数组，不需要提取 content
    return Array.isArray(result) ? result : [];
  };

  const handleLoadJenkinsJobs = async (systemId: number) => {
    return await getJenkinsJobs(systemId);
  };

  const handleOpenDeleteDialog = (app: TeamApplication) => {
    setDeletingApp(app);
    setDeleteDialogOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!deletingApp) return;
    await deleteTeamApplication(deletingApp.id!);
  };

  const getEnvironmentName = (environmentId: number) => {
    return (
      environments.find((env) => env.id === environmentId)?.envName || '未知环境'
    );
  };

  // 列定义
  const columns: ColumnDef<TeamApplication>[] = useMemo(() => [
    {
      key: 'applicationName',
      title: '应用名称',
      width: '200px',
      render: (_, app) => (
        <span className="font-medium">
          {app.applicationName && app.applicationCode
            ? `${app.applicationName}（${app.applicationCode}）`
            : app.applicationName || app.applicationCode || `应用 ${app.applicationId}`}
        </span>
      ),
    },
    {
      key: 'environmentId',
      title: '环境',
      width: '100px',
      render: (_, app) => getEnvironmentName(app.environmentId),
    },
    {
      key: 'gitConfig',
      title: 'Git配置',
      width: '350px',
      render: (_, app) => {
        const hasTargetGit = app.targetGitSystemId && app.targetGitProjectId;
        
        if (!hasTargetGit) {
          // 未配置目标：单行显示
          return (
            <div className="flex items-center gap-2 text-sm">
              <span className="font-medium truncate">
                {app.sourceGitSystemName || '-'} / {app.sourceGitProjectName || '-'}
              </span>
              {app.sourceBranch && (
                <span className="text-xs text-muted-foreground">({app.sourceBranch})</span>
              )}
            </div>
          );
        }
        
        // 配置了目标：对称双行显示
        return (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <div className="space-y-0.5 cursor-help">
                  {/* 源Git */}
                  <div className="text-sm">
                    <span className="text-muted-foreground">源：</span>
                    <span className="font-medium">
                      {app.sourceGitSystemName || '-'} / {app.sourceGitProjectName || '-'}
                    </span>
                    {app.sourceBranch && (
                      <span className="text-muted-foreground">({app.sourceBranch})</span>
                    )}
                  </div>
                  {/* 同步标识 - 居中 */}
                  <div className="flex justify-center text-xs text-blue-500">
                    <span>⇅ 同步</span>
                  </div>
                  {/* 目标Git */}
                  <div className="text-sm">
                    <span className="text-muted-foreground">目：</span>
                    <span className="font-medium text-blue-600">
                      {app.targetGitSystemName || '-'} / {app.targetGitProjectName || '-'}
                    </span>
                    {app.targetBranch && (
                      <span className="text-blue-500">({app.targetBranch})</span>
                    )}
                  </div>
                </div>
              </TooltipTrigger>
              <TooltipContent side="top" className="max-w-xs">
                <div className="space-y-2 text-xs">
                  <div>
                    <div className="font-semibold mb-1">源Git</div>
                    <div className="text-muted-foreground">
                      <div>系统: {app.sourceGitSystemName}</div>
                      <div>项目: {app.sourceGitProjectName}</div>
                      <div>分支: {app.sourceBranch || '-'}</div>
                    </div>
                  </div>
                  <div className="border-t pt-2">
                    <div className="font-semibold mb-1">目标Git</div>
                    <div className="text-muted-foreground">
                      <div>系统: {app.targetGitSystemName}</div>
                      <div>项目: {app.targetGitProjectName}</div>
                      <div>分支: {app.targetBranch || '-'}</div>
                    </div>
                  </div>
                </div>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        );
      },
    },
    {
      key: 'buildType',
      title: '构建类型',
      width: '120px',
      render: (_, app) => 
        app.buildType === 'JENKINS' ? 'Jenkins构建' : app.buildType === 'NATIVE' ? '脚本部署' : '-',
    },
    {
      key: 'deploySystemName',
      title: 'Jenkins系统',
      width: '150px',
      render: (_, app) =>
        app.buildType === 'JENKINS' 
          ? (app.deploySystemName || (app.deploySystemId ? `系统 ${app.deploySystemId}` : '-'))
          : '-',
    },
    {
      key: 'deployJob',
      title: 'Jenkins Job',
      width: '150px',
      render: (_, app) => (app.buildType === 'JENKINS' ? (app.deployJob || '-') : '-'),
    },
    {
      key: 'workflowDefinitionName',
      title: '工作流',
      dataIndex: 'workflowDefinitionName',
      width: '180px',
      render: (value) => value || '-',
    },
    {
      key: 'actions',
      title: '操作',
      width: '100px',
      sticky: true,
      render: (_, app) => (
        <div className="flex items-center justify-end gap-1">
          <Button
            variant="ghost"
            size="sm"
            className="h-8 w-8 p-0"
            onClick={() => handleOpenEditAppDialog(app)}
          >
            <Edit className="h-3.5 w-3.5" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-8 w-8 p-0"
            onClick={() => handleOpenDeleteDialog(app)}
          >
            <Trash2 className="h-3.5 w-3.5 text-destructive" />
          </Button>
        </div>
      ),
    },
  ], [environments]);

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-5xl">
          <DialogHeader>
            <DialogTitle>管理应用配置</DialogTitle>
          </DialogHeader>

          <DialogBody>
            {/* 工具栏 */}
            <div className="flex items-center justify-end mb-4">
              <Button onClick={handleOpenAddAppDialog}>
                <Plus className="mr-2 h-4 w-4" />
                添加应用
              </Button>
            </div>

            {/* 应用列表表格 */}
            <div className="border rounded-lg">
              <PaginatedTable<TeamApplication, any>
                ref={tableRef}
                fetchFn={fetchData}
                columns={columns}
                rowKey="id"
                minWidth="1000px"
                pageSize={10}
              />
            </div>
          </DialogBody>

          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 应用配置对话框 */}
      {editingEnvironment && (
        <TeamApplicationDialog
          open={appDialogOpen}
          onOpenChange={setAppDialogOpen}
          mode={appDialogMode}
          enableGitSyncCheck={enableGitSyncCheck}
          teamId={teamId}
          environmentId={editingEnvironment.id}
          environmentName={editingEnvironment.envName}
          application={editingApp || undefined}
          applications={applications}
          jenkinsSystems={jenkinsSystems}
          workflowDefinitions={workflowDefinitions}
          existingApplicationIds={
            // 传递当前环境已添加的应用ID列表
            teamApplications
              .filter(app => app.environmentId === editingEnvironment.id)
              .map(app => app.applicationId)
          }
          onSave={handleSaveApplication}
          onLoadBranches={handleLoadBranches}
          onLoadJenkinsJobs={handleLoadJenkinsJobs}
        />
      )}

      {/* 删除确认对话框 */}
      <ConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        title="确认删除"
        description={`确定要删除应用配置 "${
          deletingApp?.applicationName && deletingApp?.applicationCode
            ? `${deletingApp.applicationName}（${deletingApp.applicationCode}）`
            : deletingApp?.applicationName || deletingApp?.applicationCode || `应用 ${deletingApp?.applicationId}`
        }" 吗？此操作无法撤销。`}
        item={deletingApp}
        onConfirm={handleConfirmDelete}
        onSuccess={() => {
          toast({
            title: '删除成功',
            description: '应用配置已删除',
          });
          setDeletingApp(null);
          tableRef.current?.refresh();
          onSuccess?.();
        }}
        variant="destructive"
        confirmText="删除"
      />
    </>
  );
};

