import React, { useEffect, useState } from 'react';
import { Button, Space, Modal, Message, Popover } from '@arco-design/web-react';
import { IconSync } from '@arco-design/web-react/icon';
import { downloadEnvConfigFile, testEnv } from '@/api/componentDeployEnv';
import ConfigTutorial from './configTutorial';

const EnvExtra = ({ currentEnvData }) => {
  const [testLoading, setTestLoading] = useState(false);
  const [tutorialVisible, setTutorialVisible] = useState(false);
  const [onceTestType, setOnceTestType] = useState(null); // 单次测试结果

  // 下载配置证书压缩包文件
  const handleDownloadConfig = async () => {
    try {
      const blob = await downloadEnvConfigFile(currentEnvData.id);
      console.log('blob:', blob);

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;

      // 设置文件名 - 环境名称_时间戳.zip
      const fileName = `${currentEnvData.name}_配置文件_${new Date().getTime()}.zip`;
      link.setAttribute('download', fileName);

      // 触发下载
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      Message.success('下载配置文件成功');
    } catch (e) {
      console.error('下载配置文件失败：', e);
      Message.error('下载配置文件失败: ' + (e.message || '未知错误'));
    }
  };

  // 模拟查看环境配置教程
  const handleViewTutorial = () => {
    setTutorialVisible(true);
  };

  // 模拟点击测试环境可用性
  const handleTestAvailability = async () => {
    setTestLoading(true);
    const res: any = await testEnv(currentEnvData.id);
    if (res.code === 200 && res.data) {
      setOnceTestType(true);
      Message.success(`环境 ${currentEnvData.name} 测试成功`);
    }
    else {
      setOnceTestType(false);
      Message.error(`环境 ${currentEnvData.name} 测试失败: ${res.message}`);
    }
    setTestLoading(false);
  };

  useEffect(() => {
    if (currentEnvData?.available === 1) setOnceTestType(true);
    else if (currentEnvData?.available === -1) setOnceTestType(false);
    else setOnceTestType(null);
  }, [currentEnvData]);

  return (
    <>
      <div style={{ padding: '20px', borderRadius: 8 }}>
        <div style={{ marginBottom: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}>
            <span style={{ fontSize: 14, fontWeight: 500 }}>环境配置文件：</span>
            <Button
              type="text"
              onClick={handleDownloadConfig}
            >
              下载配置证书文件
            </Button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', marginLeft: 15 }}>
            <span style={{ color: '#FFA500', marginRight: 8 }}>●</span>
            <span style={{ fontSize: 13, color: '#666' }}>可点击查看</span>
            <Button
              type="text"
              onClick={handleViewTutorial}
              style={{ marginLeft: 4 }}
            >
              环境配置教程
            </Button>
          </div>
        </div>

        <div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontSize: 14, fontWeight: 500 }}>环境可用性：</span>

            {onceTestType === null && (
              <Button
                type="outline"
                onClick={handleTestAvailability}
                style={{ marginLeft: 16 }}
                loading={testLoading}
              >
                点击测试
              </Button>
            )}

            {onceTestType && (
              <div>
                <span style={{ color: '#81b367' }}>环境测试通过</span>
                <Popover
                  content={
                    <span>
                      点击重新测试
                    </span>
                  }
                >
                  <IconSync style={{ fontSize: 16, color: '#5484ff', marginLeft: 5, cursor: 'pointer' }}
                            onClick={handleTestAvailability} />
                </Popover>

              </div>
            )}

            {!onceTestType && (
              <div>
                <div>
                  <span style={{ color: '#c13131', fontSize: 14 }}>环境测试失败</span>
                  <Popover
                    content={
                      <span>
                      点击重新测试
                    </span>
                    }
                  >
                    <IconSync style={{ fontSize: 16, color: '#5484ff', marginLeft: 5, cursor: 'pointer' }}
                              onClick={handleTestAvailability} />
                  </Popover>
                </div>
                <div
                  style={{ color: '#c13131', fontSize: 12, fontWeight: 700 }}>证书配置错误,请根据教程文档检查配置内容
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <Modal
        title="环境配置教程"
        visible={tutorialVisible}
        onCancel={() => setTutorialVisible(false)}
        footer={null}
        style={{ top: 20, width: '100%' }}
      >
        <ConfigTutorial tutorialType="env" />
      </Modal>
    </>
  );
};

export default EnvExtra;