import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Button,
  Typography,
  CircularProgress,
  Alert,
  Chip,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  List,
  ListItem,
  ListItemText,
  Divider,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import RefreshIcon from '@mui/icons-material/Refresh';
import { useTranslation } from 'react-i18next';
import type { IMcpServer } from '@/interfaces/database/mcp';
import type { ICreateMcpServerRequestBody, ITestMcpRequestBody } from '@/interfaces/request/mcp';
import { Mode } from '@mui/icons-material';

const FormContainer = styled(Box)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  gap: theme.spacing(3),
  padding: theme.spacing(2),
}));

const TestSection = styled(Box)(({ theme }) => ({
  marginTop: theme.spacing(2),
  padding: theme.spacing(2),
  border: `1px solid ${theme.palette.divider}`,
  borderRadius: theme.shape.borderRadius,
  backgroundColor: theme.palette.background.paper,
}));

const ToolsContainer = styled(Box)(({ theme }) => ({
  maxHeight: '300px',
  overflowY: 'auto',
  marginTop: theme.spacing(1),
}));

interface McpFormData {
  name?: string;
  url: string;
  server_type: string;
  authorization_token?: string;
}

interface McpTool {
  name: string;
  description: string;
}

interface McpFormProps {
  initialData?: Partial<IMcpServer>;
  onSubmit: (data: ICreateMcpServerRequestBody) => Promise<{ success: boolean; error?: string }>;
  onTest?: (data: ITestMcpRequestBody) => Promise<{ success: boolean; data?: any; error?: string }>;
  loading?: boolean;
  disabled?: boolean;
}

const McpForm: React.FC<McpFormProps> = ({
  initialData,
  onSubmit,
  onTest,
  loading = false,
  disabled = false,
}) => {
  const { t } = useTranslation();
  const [formData, setFormData] = useState<McpFormData>({
    name: initialData?.name || '',
    url: initialData?.url || '',
    server_type: initialData?.server_type || 'sse',
    authorization_token: initialData?.variables?.authorization_token || '',
  });

  const [testLoading, setTestLoading] = useState(false);

  const [testResult, setTestResult] = useState<{
    success: boolean;
    tools?: McpTool[];
    error?: string;
  } | null>(null);

  const [formErrors, setFormErrors] = useState<Partial<McpFormData>>({});
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    if (!isInitialized) {
      // 只在首次初始化时设置默认值
      setFormData({
        name: '',
        url: '',
        server_type: 'sse',
        authorization_token: '',
      });
      setIsInitialized(true);
    }
    if (initialData) {
      setFormData({
        name: initialData.name || '',
        url: initialData.url || '',
        server_type: initialData.server_type || 'sse',
        authorization_token: initialData.variables?.authorization_token || '',
      });
      if (initialData.variables?.tools) {
        const tools = Object.entries(initialData.variables.tools).map(([name, tool]) => {
          const t: McpTool = {
            name: name,
            description: tool.description || '',
          }
          return t
        });
        setTestResult({
          success: tools.length > 0,
          tools,
        });
      }
      setIsInitialized(true);
    } 
  }, [isInitialized]);

  const validateForm = (): boolean => {
    const errors: Partial<McpFormData> = {};
    
    if (!formData.name?.trim()) {
      errors.name = t('setting.nameRequired');
    }
    
    if (!formData.url.trim()) {
      errors.url = t('setting.urlRequired');
    } else if (!/^https?:\/\/.+/.test(formData.url)) {
      errors.url = t('setting.urlFormatInvalid');
    }
    
    if (!formData.server_type) {
      errors.server_type = t('setting.serverTypeRequired');
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleInputChange = (field: keyof McpFormData) => (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | { target: { value: string } }
  ) => {
    const value = event.target.value;
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // 清除对应字段的错误
    if (formErrors[field]) {
      setFormErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const handleTest = async () => {
    if (!onTest) return;
    
    if (!formData.url.trim()) {
      setTestResult({
        success: false,
        error: t('setting.fillUrlFirst'),
      });
      return;
    }

    setTestLoading(true);
    setTestResult(null);

    try {
      const testData: ITestMcpRequestBody = {
        server_type: formData.server_type,
        url: formData.url,
        headers: formData.authorization_token ? { authorization_token: formData.authorization_token } : undefined,
        name: formData.name?.trim(),
      };

      const result = await onTest(testData);
      
      if (result.success && result.data) {
        // 解析工具数据
        const tools: McpTool[] = [];
        if (result.data && Array.isArray(result.data)) {
          result.data.forEach((tool: any) => {
            if (tool.name && tool.description) {
              tools.push({
                name: tool.name,
                description: tool.description,
              });
            }
          });
        }
        
        setTestResult({
          success: tools.length > 0,
          tools,
        });
      } else {
        setTestResult({
          success: false,
          error: result.error || t('setting.testFailed'),
        });
      }
    } catch (error: any) {
      setTestResult({
        success: false,
        error: error.message || t('setting.testConnectionError'),
      });
    } finally {
      setTestLoading(false);
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

    const submitData: ICreateMcpServerRequestBody = {
      name: formData.name?.trim(),
      server_type: formData.server_type,
      url: formData.url.trim(),
      headers: formData.authorization_token ? { authorization_token: formData.authorization_token } : undefined,
    };

    await onSubmit(submitData);
  };

  return (
    <FormContainer>
      <TextField
        label={t('common.name')}
        value={formData.name || ''}
        onChange={handleInputChange('name')}
        error={!!formErrors.name}
        helperText={formErrors.name}
        disabled={disabled}
        fullWidth
        required
      />

      <TextField
        label="URL"
        value={formData.url}
        onChange={handleInputChange('url')}
        error={!!formErrors.url}
        helperText={formErrors.url}
        disabled={disabled}
        fullWidth
        required
        placeholder="https://mcp.****.com/sse?key=..."
      />

      <FormControl fullWidth required error={!!formErrors.server_type}>
        <InputLabel>{t('mcp.serverType')}</InputLabel>
        <Select
          value={formData.server_type}
          onChange={handleInputChange('server_type')}
          disabled={disabled}
          label={t('mcp.serverType')}
        >
          <MenuItem value="sse">SSE</MenuItem>
          <MenuItem value="streamable-http">Streamable HTTP</MenuItem>
        </Select>
      </FormControl>

      <TextField
        label="Authorization Token"
        value={formData.authorization_token}
        onChange={handleInputChange('authorization_token')}
        disabled={disabled}
        fullWidth
        placeholder="e.g. eyJhbGciOiJIUzI1Ni..."
        helperText={t('setting.authTokenOptional')}
      />

      {/* 测试连接部分 */}
      {onTest && (
        <TestSection>
          <Box display="flex" alignItems="center" justifyContent="space-between" mb={2}>
            <Typography variant="h6">{t('setting.testConnection')}</Typography>
            <Button
              variant="outlined"
              onClick={handleTest}
              disabled={testLoading || disabled}
              startIcon={testLoading ? <CircularProgress size={16} /> : <RefreshIcon />}
            >
              {testLoading ? t('setting.testing') : t('setting.testConnection')}
            </Button>
          </Box>

          {testResult && (
            <Box>
              {testResult.success ? (
                <Box>
                  <Alert severity="success" sx={{ mb: 2 }}>
                    {t('setting.connectionSuccess', { count: testResult.tools?.length || 0 })}
                  </Alert>
                  
                  {testResult.tools && testResult.tools.length > 0 && (
                    <Accordion defaultExpanded>
                      <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                        <Box display="flex" alignItems="center" gap={1}>
                          <Typography variant="subtitle1">{t('setting.availableTools')}</Typography>
                          <Chip 
                            label={`${testResult.tools.length} ${t('mcp.toolsAvailable')}`} 
                            size="small" 
                            color="primary" 
                          />
                        </Box>
                      </AccordionSummary>
                      <AccordionDetails>
                        <ToolsContainer>
                          <List dense>
                            {testResult.tools.map((tool, index) => (
                              <React.Fragment key={tool.name}>
                                <ListItem>
                                  <ListItemText
                                    primary={
                                      <Typography variant="subtitle2" fontWeight="bold">
                                        {tool.name}
                                      </Typography>
                                    }
                                    secondary={
                                      <Typography variant="body2" color="text.secondary">
                                        {tool.description}
                                      </Typography>
                                    }
                                  />
                                </ListItem>
                                {index < (testResult.tools?.length || 0) - 1 && <Divider />}
                              </React.Fragment>
                            ))}
                          </List>
                        </ToolsContainer>
                      </AccordionDetails>
                    </Accordion>
                  )}
                </Box>
              ) : (
                <Alert severity="error">
                  {testResult.error || t('setting.connectionFailed')}
                </Alert>
              )}
            </Box>
          )}
        </TestSection>
      )}

      {/* 提交按钮 */}
      <Box display="flex" justifyContent="flex-end" mt={2}>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={loading || disabled || !testResult?.success}
          startIcon={loading ? <CircularProgress size={16} /> : undefined}
        >
          {loading ? t('setting.saving') : t('common.save')}
        </Button>
      </Box>
    </FormContainer>
  );
};

export default McpForm;