import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogBody,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { Settings, AppWindow, Trash2, Plus, Loader2, Bell } from 'lucide-react';
import type { Environment } from '@/pages/Deploy/Environment/List/types';
import type { TeamEnvironmentConfig } from '../types';
import { getTeamEnvironmentConfigs, deleteTeamEnvironmentConfig } from '../service';
import { TeamEnvironmentConfigDialog } from './TeamEnvironmentConfigDialog';
import { TeamApplicationManageDialog } from './TeamApplicationManageDialog';
import { NotificationConfigDialog } from './NotificationConfigDialog';
import { NotificationChannelCell } from './NotificationChannelCell';
import { ApproversCell } from './ApproversCell';
import { CodeReviewCell } from './CodeReviewCell';
import { ApplicationCountCell } from './ApplicationCountCell';
import { ActionButtonsCell } from './ActionButtonsCell';

interface User {
  id: number;
  username: string;
  realName?: string;
}

interface TeamEnvironmentManageDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  teamId: number;
  teamName: string;
  enableGitSyncCheck: boolean; // 🆕 团队是否启用Git同步检测
  environments: Environment[];
  users: User[];
  onSuccess?: () => void;
}

export const TeamEnvironmentManageDialog: React.FC<
  TeamEnvironmentManageDialogProps
> = ({
  open,
  onOpenChange,
  teamId,
  teamName,
  enableGitSyncCheck,
  environments,
  users,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [configuredEnvs, setConfiguredEnvs] = useState<TeamEnvironmentConfig[]>(
    []
  );

  // 环境配置对话框状态
  const [envConfigDialogOpen, setEnvConfigDialogOpen] = useState(false);
  const [editEnvironmentId, setEditEnvironmentId] = useState<
    number | undefined
  >();

  // 应用管理对话框状态
  const [appManageDialogOpen, setAppManageDialogOpen] = useState(false);
  const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<
    number | null
  >(null);

  // 通知配置对话框状态
  const [notificationDialogOpen, setNotificationDialogOpen] = useState(false);
  const [notificationEnvironmentId, setNotificationEnvironmentId] = useState<number | null>(null);
  const [notificationEnvironmentName, setNotificationEnvironmentName] = useState<string>('');

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

  // 加载团队的环境配置列表
  useEffect(() => {
    if (open) {
      loadEnvironmentConfigs();
    }
  }, [open, teamId]);

  const loadEnvironmentConfigs = async () => {
    setLoading(true);
    try {
      const configs = await getTeamEnvironmentConfigs(teamId);
      // 关联环境名称
      const configsWithEnvName = configs.map((config: any) => ({
        ...config,
        environmentName:
          environments.find((env) => env.id === config.environmentId)
            ?.envName || '未知环境',
      }));
      setConfiguredEnvs(configsWithEnvName);
    } catch (error: any) {
      toast({
        title: '加载失败',
        description: error.message || '无法加载环境配置列表',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 未配置的环境
  const unconfiguredEnvs = environments.filter(
    (env) => !configuredEnvs.some((config) => config.environmentId === env.id)
  );

  const handleOpenConfigDialog = (environmentId?: number) => {
    setEditEnvironmentId(environmentId);
    setEnvConfigDialogOpen(true);
  };

  const handleOpenAppManageDialog = (environmentId: number) => {
    setSelectedEnvironmentId(environmentId);
    setAppManageDialogOpen(true);
  };

  const handleOpenNotificationDialog = (config: TeamEnvironmentConfig) => {
    setNotificationEnvironmentId(config.environmentId);
    setNotificationEnvironmentName(config.environmentName || '');
    setNotificationDialogOpen(true);
  };

  const handleOpenDeleteDialog = (config: TeamEnvironmentConfig) => {
    setDeletingConfig(config);
    setDeleteDialogOpen(true);
  };

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

  const handleConfigSuccess = () => {
    loadEnvironmentConfigs();
    onSuccess?.();
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-6xl max-h-[90vh]">
          <DialogHeader>
            <DialogTitle>环境管理 - {teamName}</DialogTitle>
            <DialogDescription>
              管理团队的环境配置，包括审批流程、通知设置和应用配置
            </DialogDescription>
          </DialogHeader>

          <DialogBody className="overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center h-64">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : (
              <div className="space-y-6">
                {/* 已配置的环境 */}
                <div>
                  <h3 className="text-lg font-semibold mb-4">已配置的环境</h3>
                  {configuredEnvs.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground border rounded-lg">
                      暂无已配置的环境
                    </div>
                  ) : (
                    <div className="border rounded-lg">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>环境名称</TableHead>
                            <TableHead>审批人</TableHead>
                            <TableHead>通知渠道</TableHead>
                            <TableHead>应用数量</TableHead>
                            <TableHead>代码审查</TableHead>
                            <TableHead>备注</TableHead>
                            <TableHead className="text-right">操作</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {configuredEnvs.map((config) => (
                            <TableRow key={config.id}>
                              <TableCell className="font-medium">
                                {config.environmentName}
                              </TableCell>
                              <TableCell>
                                <ApproversCell
                                  approvalRequired={config.approvalRequired}
                                  approverUserIds={config.approverUserIds}
                                  users={users}
                                />
                              </TableCell>
                              <TableCell>
                                <NotificationChannelCell
                                  notificationConfig={config.notificationConfig}
                                />
                              </TableCell>
                              <TableCell>
                                <ApplicationCountCell
                                  applicationCount={config.applicationCount}
                                />
                              </TableCell>
                              <TableCell>
                                <CodeReviewCell
                                  requireCodeReview={config.requireCodeReview}
                                />
                              </TableCell>
                              <TableCell>
                                <span className="text-sm text-muted-foreground">
                                  {config.remark || '-'}
                                </span>
                              </TableCell>
                              <TableCell>
                                <ActionButtonsCell
                                  environmentId={config.environmentId}
                                  environmentName={config.environmentName}
                                  onConfig={handleOpenConfigDialog}
                                  onNotification={handleOpenNotificationDialog}
                                  onAppManage={handleOpenAppManageDialog}
                                  onDelete={handleOpenDeleteDialog}
                                  config={config}
                                />
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </div>

                {/* 未配置的环境 */}
                {unconfiguredEnvs.length > 0 && (
                  <div>
                    <h3 className="text-lg font-semibold mb-4">
                      未配置的环境
                    </h3>
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                      {unconfiguredEnvs.map((env) => (
                        <div
                          key={env.id}
                          className="flex items-center justify-between p-4 border rounded-lg hover:bg-accent"
                        >
                          <span className="font-medium">{env.envName}</span>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleOpenConfigDialog(env.id)}
                          >
                            <Plus className="h-4 w-4 mr-1" />
                            绑定
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </DialogBody>

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

      {/* 环境配置对话框 */}
      <TeamEnvironmentConfigDialog
        open={envConfigDialogOpen}
        onOpenChange={setEnvConfigDialogOpen}
        teamId={teamId}
        environments={environments}
        users={users}
        editEnvironmentId={editEnvironmentId}
        onSuccess={handleConfigSuccess}
      />

      {/* 应用管理对话框 */}
      {selectedEnvironmentId && (
        <TeamApplicationManageDialog
          open={appManageDialogOpen}
          onOpenChange={setAppManageDialogOpen}
          teamId={teamId}
          enableGitSyncCheck={enableGitSyncCheck}
          environmentId={selectedEnvironmentId}
          environments={environments}
          onSuccess={handleConfigSuccess}
        />
      )}

      {/* 通知配置对话框 */}
      {notificationEnvironmentId && (
        <NotificationConfigDialog
          open={notificationDialogOpen}
          onOpenChange={setNotificationDialogOpen}
          teamId={teamId}
          environmentId={notificationEnvironmentId}
          environmentName={notificationEnvironmentName}
          onSuccess={handleConfigSuccess}
        />
      )}

      {/* 删除确认对话框 */}
      <ConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        title="确认删除"
        description={`确定要删除环境"${deletingConfig?.environmentName}"的配置吗？此操作将同时删除该环境下的所有应用配置，且无法撤销。`}
        item={deletingConfig}
        onConfirm={handleConfirmDelete}
        onSuccess={() => {
          toast({
            title: '删除成功',
            description: '环境配置已删除',
          });
          setDeletingConfig(null);
          loadEnvironmentConfigs();
          onSuccess?.();
        }}
        variant="destructive"
        confirmText="删除"
      />
    </>
  );
};

