import React, { useState, useCallback } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  IconButton,
  Typography,
  Box,
  Alert,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import CloseIcon from '@mui/icons-material/Close';
import McpForm from './McpForm';
import type { IMcpServer } from '@/interfaces/database/mcp';
import type { ICreateMcpServerRequestBody, ITestMcpRequestBody } from '@/interfaces/request/mcp';
import logger from '@/utils/logger';

const StyledDialogTitle = styled(DialogTitle)(({ theme }) => ({
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  padding: theme.spacing(2, 3),
  borderBottom: `1px solid ${theme.palette.divider}`,
}));

const StyledDialogContent = styled(DialogContent)(({ theme }) => ({
  padding: 0,
  minHeight: '400px',
  maxHeight: '80vh',
  overflow: 'auto',
}));

interface McpDialogProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: ICreateMcpServerRequestBody) => Promise<{ success: boolean; error?: string }>;
  onTest?: (data: ITestMcpRequestBody) => Promise<{ success: boolean; data?: any; error?: string }>;
  initialData?: Partial<IMcpServer>;
  mode?: 'create' | 'edit';
  loading?: boolean;
}

const McpDialog: React.FC<McpDialogProps> = ({
  open,
  onClose,
  onSave,
  onTest,
  initialData,
  mode = 'create',
  loading = false,
}) => {
  const [submitLoading, setSubmitLoading] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [submitSuccess, setSubmitSuccess] = useState(false);

  const handleSubmit = useCallback(async (data: ICreateMcpServerRequestBody) => {
    setSubmitLoading(true);
    setSubmitError(null);
    setSubmitSuccess(false);

    try {
      const result = await onSave(data);
      
      if (result.success) {
        setSubmitSuccess(true);
        // 延迟关闭对话框，让用户看到成功消息
        setTimeout(() => {
          onClose();
          setSubmitSuccess(false);
        }, 1500);
      } else {
        setSubmitError(result.error || '保存失败');
      }
    } catch (error: any) {
      setSubmitError(error.message || '保存时发生错误');
    } finally {
      setSubmitLoading(false);
    }

    return { success: submitSuccess, error: submitError || undefined };
  }, [onSave, onClose, submitSuccess, submitError]);

  const handleClose = () => {
    if (submitLoading) return; // 防止在提交过程中关闭
    
    setSubmitError(null);
    setSubmitSuccess(false);
    onClose();
  };

  const getDialogTitle = () => {
    switch (mode) {
      case 'edit':
        return '编辑 MCP 服务器';
      case 'create':
      default:
        return '添加 MCP 服务器';
    }
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="md"
      fullWidth
      disableEscapeKeyDown={submitLoading}
    >
      <StyledDialogTitle>
        <Typography variant="h6" component="div">
          {getDialogTitle()}
        </Typography>
        <IconButton
          aria-label="close"
          onClick={handleClose}
          disabled={submitLoading}
          size="small"
        >
          <CloseIcon />
        </IconButton>
      </StyledDialogTitle>

      <StyledDialogContent>
        {/* 显示提交状态消息 */}
        {submitError && (
          <Box p={2}>
            <Alert severity="error" onClose={() => setSubmitError(null)}>
              {submitError}
            </Alert>
          </Box>
        )}
        
        {submitSuccess && (
          <Box p={2}>
            <Alert severity="success">
              {mode === 'create' ? 'MCP 服务器创建成功！' : 'MCP 服务器更新成功！'}
            </Alert>
          </Box>
        )}

        <McpForm
          initialData={initialData}
          onSubmit={handleSubmit}
          onTest={onTest}
          loading={submitLoading || loading}
          disabled={submitLoading || loading}
        />
      </StyledDialogContent>
    </Dialog>
  );
};

export default McpDialog;