/**
 * KRA - Image Upload Component
 * Image upload with preview and compression support
 */
import React, { useState } from 'react';
import { Upload, message, Image } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import type { UploadProps, UploadFile } from 'antd';
import { getToken } from '@/utils/auth';

interface ImageUploadProps {
  value?: string;
  onChange?: (url: string) => void;
  action?: string;
  classId?: number;
  maxSize?: number; // KB
  accept?: string;
  width?: number;
  height?: number;
}

const ImageUpload: React.FC<ImageUploadProps> = ({
  value,
  onChange,
  action = '/api/fileUploadAndDownload/upload',
  classId = 0,
  maxSize = 2048, // 2MB
  accept = 'image/jpeg,image/png,image/gif,image/webp',
  width = 104,
  height = 104,
}) => {
  const [loading, setLoading] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);

  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
      return false;
    }
    const isLtMaxSize = file.size / 1024 < maxSize;
    if (!isLtMaxSize) {
      message.error(`图片大小不能超过 ${maxSize}KB`);
      return false;
    }
    setLoading(true);
    return true;
  };

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'done') {
      setLoading(false);
      const { response } = info.file;
      if (response?.code === 0 && response?.data?.file) {
        onChange?.(response.data.file.url);
      } else {
        message.error(response?.msg || '上传失败');
      }
    } else if (info.file.status === 'error') {
      setLoading(false);
      message.error('上传失败');
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  return (
    <>
      <Upload
        name="file"
        listType="picture-card"
        showUploadList={false}
        action={action}
        headers={{ 'x-token': getToken() || '' }}
        data={{ classId }}
        accept={accept}
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {value ? (
          <img
            src={value}
            alt="avatar"
            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
            onClick={(e) => {
              e.stopPropagation();
              setPreviewOpen(true);
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
      <Image
        style={{ display: 'none' }}
        preview={{
          visible: previewOpen,
          onVisibleChange: setPreviewOpen,
        }}
        src={value}
      />
    </>
  );
};

export default ImageUpload;
