/**
 * KRA - Import Excel Component
 * Import data from Excel file
 */
import React, { useState } from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { getToken } from '@/utils/auth';

interface ImportExcelProps {
  action: string;
  onSuccess?: (data: any) => void;
  onError?: (error: Error) => void;
  accept?: string;
  buttonText?: string;
  buttonType?: 'primary' | 'default' | 'dashed' | 'link' | 'text';
  className?: string;
  style?: React.CSSProperties;
}

const ImportExcel: React.FC<ImportExcelProps> = ({
  action,
  onSuccess,
  onError,
  accept = '.xlsx,.xls',
  buttonText = '导入Excel',
  buttonType = 'primary',
  className,
  style,
}) => {
  const [loading, setLoading] = useState(false);

  const uploadProps: UploadProps = {
    name: 'file',
    action,
    accept,
    headers: { 'x-token': getToken() || '' },
    showUploadList: false,
    beforeUpload: () => {
      setLoading(true);
      return true;
    },
    onChange: (info) => {
      if (info.file.status === 'done') {
        setLoading(false);
        const { response } = info.file;
        if (response?.code === 0) {
          message.success('导入成功');
          onSuccess?.(response.data);
        } else {
          message.error(response?.msg || '导入失败');
        }
      } else if (info.file.status === 'error') {
        setLoading(false);
        message.error('导入失败');
        onError?.(new Error('Import failed'));
      }
    },
  };

  return (
    <Upload {...uploadProps}>
      <Button
        type={buttonType}
        icon={<UploadOutlined />}
        loading={loading}
        className={className}
        style={style}
      >
        {buttonText}
      </Button>
    </Upload>
  );
};

export default ImportExcel;
