import React, { useState } from 'react';
import { Card, Upload, Alert, message, Modal } from 'antd';
import { InboxOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { getToken } from '@/utils/auth';
import './index.less';

const { Dragger } = Upload;

interface InstallResult {
  msg: string;
  success?: boolean;
}

/**
 * 插件安装页面
 */
const InstallPlugin: React.FC = () => {
  const [installResults, setInstallResults] = useState<InstallResult[]>([]);

  // 获取上传地址
  const getUploadUrl = () => {
    const baseUrl = process.env.NODE_ENV === 'development' 
      ? '/api' 
      : (window as any).VITE_BASE_API || '/api';
    return `${baseUrl}/autoCode/installPlugin`;
  };

  // 上传成功/失败处理
  const handleUploadChange = (info: any) => {
    const { status, response } = info.file;
    
    if (status === 'done') {
      if (response?.code === 0) {
        // 安装成功
        const results = response.data || [];
        setInstallResults(results.map((item: any) => ({
          msg: item.msg,
          success: true,
        })));
        
        // 显示结果弹窗
        if (results.length > 0) {
          const msgContent = results.map((item: any, index: number) => 
            `${index + 1}. ${item.msg}`
          ).join('\n');
          
          Modal.success({
            title: '插件安装结果',
            content: (
              <pre style={{ whiteSpace: 'pre-wrap', maxHeight: 400, overflow: 'auto' }}>
                {msgContent}
              </pre>
            ),
            width: 500,
          });
        } else {
          message.success('插件安装成功');
        }
      } else {
        // 安装失败
        message.error(response?.msg || '插件安装失败');
        setInstallResults([{
          msg: response?.msg || '插件安装失败',
          success: false,
        }]);
      }
    } else if (status === 'error') {
      message.error('上传失败，请检查网络连接');
      setInstallResults([{
        msg: '上传失败，请检查网络连接',
        success: false,
      }]);
    }
  };

  // 上传前校验
  const beforeUpload = (file: File) => {
    const isZip = file.type === 'application/zip' || 
                  file.type === 'application/x-zip-compressed' ||
                  file.name.endsWith('.zip');
    
    if (!isZip) {
      message.error('只能上传 ZIP 格式的插件包！');
      return false;
    }
    
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (!isLt100M) {
      message.error('插件包大小不能超过 100MB！');
      return false;
    }
    
    return true;
  };

  return (
    <div className="install-plugin-container">
      <Alert
        message="插件安装"
        description="上传插件安装包（ZIP格式）进行安装。安装前请确保插件包是通过标准插件模板生成的。"
        type="info"
        showIcon
        className="install-plugin-alert"
      />

      <Card className="upload-card">
        <Dragger
          name="plug"
          action={getUploadUrl()}
          headers={{
            'x-token': getToken() || '',
          }}
          showUploadList={false}
          beforeUpload={beforeUpload}
          onChange={handleUploadChange}
          accept=".zip"
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">拖拽或点击上传</p>
          <p className="ant-upload-hint">请把安装包的 ZIP 拖拽至此处上传</p>
        </Dragger>

        <div className="upload-tips">
          <h4>安装说明：</h4>
          <ul>
            <li>只支持标准插件（通过插件模板生成的标准目录插件）</li>
            <li>非标准插件请自行打包安装</li>
            <li>插件包必须是 ZIP 格式</li>
            <li>安装包大小限制为 100MB</li>
            <li>安装过程中请勿刷新页面</li>
          </ul>
        </div>
      </Card>

      {installResults.length > 0 && (
        <div className="install-result">
          <div className="result-title">安装结果：</div>
          <div className="result-list">
            {installResults.map((result, index) => (
              <div 
                key={index} 
                className={`result-item ${result.success ? 'success' : 'error'}`}
              >
                {result.success ? (
                  <CheckCircleOutlined />
                ) : (
                  <CloseCircleOutlined />
                )}
                <span className="result-index">{index + 1}.</span>
                <span className="result-msg">{result.msg}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default InstallPlugin;
