import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Upload, Button, Checkbox, message } from 'antd';
import { InboxOutlined, DownloadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { userImportApi } from '../../api/user/import';
import { getAccessToken, getTenantId } from '../../utils/auth';
import { useTranslation } from 'react-i18next';

const { Dragger } = Upload;

interface UserImportFormProps {
  onSuccess?: () => void;
}

export interface UserImportFormRef {
  open: () => void;
}

const UserImportForm = forwardRef<UserImportFormRef, UserImportFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [updateSupport, setUpdateSupport] = useState(false);

  // 打开弹窗
  const open = () => {
    setDialogVisible(true);
    setFileList([]);
    setUpdateSupport(false);
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  // 下载模板
  const importTemplate = async () => {
    try {
      const blob = await userImportApi.importUserTemplate();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = t('form.userImportTemplateFileName');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      message.success(t('form.templateDownloadSuccess'));
    } catch (error: any) {
      message.error(error.message || t('form.templateDownloadFailed'));
    }
  };

  // 上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    fileList,
    accept: '.xlsx,.xls',
    beforeUpload: (file) => {
      const validTypes = ['.xlsx', '.xls'];
      const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
      if (!validTypes.includes(fileExtension)) {
        message.error(t('form.fileFormatError'));
        return false;
      }
      setFileList([file]);
      return false; // 阻止自动上传
    },
    onRemove: () => {
      setFileList([]);
    },
    onChange: (info) => {
      setFileList(info.fileList);
    },
  };

  // 提交表单
  const submitForm = async () => {
    if (fileList.length === 0) {
      message.error(t('form.pleaseUploadFile'));
      return;
    }

    const file = fileList[0].originFileObj;
    if (!file) {
      message.error(t('form.pleaseUploadFile'));
      return;
    }

    setFormLoading(true);
    try {
      const response = await userImportApi.importUser(file, updateSupport ? 1 : 0);
      
      // 拼接提示语
      const data = response;
      let text = `${t('form.uploadSuccessCount')}${data.createUsernames?.length || 0}; `;
      if (data.createUsernames?.length > 0) {
        text += data.createUsernames.map((u: string) => `< ${u} >`).join(' ');
      }
      text += `${t('form.updateSuccessCount')}${data.updateUsernames?.length || 0}; `;
      if (data.updateUsernames?.length > 0) {
        text += data.updateUsernames.map((u: string) => `< ${u} >`).join(' ');
      }
      text += `${t('form.updateFailedCount')}${Object.keys(data.failureUsernames || {}).length}; `;
      if (data.failureUsernames) {
        text += Object.entries(data.failureUsernames)
          .map(([username, reason]) => `< ${username}: ${reason} >`)
          .join(' ');
      }
      
      Modal.info({
        title: t('form.importResult'),
        content: <div dangerouslySetInnerHTML={{ __html: text }} />,
        width: 600,
      });
      
      setDialogVisible(false);
      onSuccess?.();
    } catch (error: any) {
      message.error(error.message || t('form.uploadFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  return (
    <Modal
      title={t('form.userImport')}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={400}
      destroyOnClose
    >
      <div style={{ padding: '16px 0' }}>
        <Dragger
          {...uploadProps}
          disabled={formLoading}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">{t('form.uploadDragText')}</p>
        </Dragger>

        <div style={{ marginTop: 16, marginBottom: 16 }}>
          <Checkbox
            checked={updateSupport}
            onChange={(e) => setUpdateSupport(e.target.checked)}
          >
            {t('form.updateExistingUser')}
          </Checkbox>
        </div>

        <div style={{ fontSize: 12, color: '#999', textAlign: 'center' }}>
          <span>{t('form.onlyAllowImportFormat')}</span>
          <Button
            type="link"
            size="small"
            icon={<DownloadOutlined />}
            onClick={importTemplate}
            style={{ padding: 0, fontSize: 12, height: 'auto' }}
          >
            {t('form.downloadTemplate')}
          </Button>
        </div>
      </div>
    </Modal>
  );
});

UserImportForm.displayName = 'UserImportForm';

export default UserImportForm;
