import React, { useState, useEffect } from 'react';
import { Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { fileApi } from '../api/file';

// 上传接口由 fileApi.upload 固定使用 /admin-api/infra/file/upload（axios baseURL + /infra/file/upload）

function normalizeUrl(item: unknown): { url: string; name?: string } | null {
  if (item == null) return null;
  if (typeof item === 'string' && item !== '') return { url: item };
  if (typeof item === 'object' && item !== null) {
    const o = item as Record<string, unknown>;
    const url = o.url;
    const str = typeof url === 'string' ? url : undefined;
    if (str) return { url: str, name: typeof o.name === 'string' ? o.name : undefined };
  }
  return null;
}

function toFileList(value: string | string[] | Record<string, unknown>[] | undefined): UploadFile[] {
  if (value == null || value === '') return [];
  const list = Array.isArray(value) ? value : [value];
  return list
    .map((item) => normalizeUrl(item))
    .filter((item): item is { url: string; name?: string } => item != null)
    .map((item, i) => ({
      uid: `-${i}-${item.url}`,
      name: item.name ?? (typeof item.url === 'string' ? item.url.split('/').pop() : undefined) ?? `文件${i + 1}`,
      status: 'done' as const,
      url: item.url,
    }));
}

function extractUrls(fileList: UploadFile[]): string[] {
  return fileList
    .map((f) => (f.response as string) ?? f.url)
    .filter(Boolean) as string[];
}

export interface FormUploadFieldProps {
  value?: string | string[];
  onChange?: (value: string | string[]) => void;
  disabled?: boolean;
  uploadType?: 'single-image' | 'multiple-image' | 'file';
  maxCount?: number;
  accept?: string;
}

/**
 * 自定义表单上传组件：内部固定使用 /admin-api/infra/file/upload，支持图片/文件上传与回显。
 */
export default function FormUploadField({
  value,
  onChange,
  disabled = false,
  uploadType = 'multiple-image',
  maxCount,
  accept,
}: FormUploadFieldProps) {
  const [fileList, setFileList] = useState<UploadFile[]>(() => toFileList(value));

  useEffect(() => {
    setFileList((prev) => {
      const fromValue = toFileList(value);
      const pending = prev.filter((f) => f.status === 'uploading');
      if (pending.length === 0) return fromValue;
      return [...fromValue, ...pending];
    });
  }, [value]);

  const isSingleImage = uploadType === 'single-image';
  const limit = maxCount ?? (isSingleImage ? 1 : uploadType === 'multiple-image' ? 9 : undefined);
  const acceptAttr = accept ?? (uploadType === 'file' ? undefined : 'image/*');
  const listType = uploadType === 'file' ? 'text' : 'picture-card';

  return (
    <Upload
      disabled={disabled}
      listType={listType as 'text' | 'picture-card' | 'picture'}
      fileList={fileList}
      maxCount={limit}
      accept={acceptAttr}
      multiple={!isSingleImage}
      customRequest={async ({ file, onSuccess, onError }) => {
        try {
          const url = await fileApi.upload(file as File);
          onSuccess?.(url);
        } catch (e: any) {
          onError?.(e);
        }
      }}
      onChange={({ fileList: nextList }) => {
        const list = nextList.map((f) => {
          if (f.response && !f.url) return { ...f, url: f.response as string };
          return f;
        });
        setFileList(list);
        const urls = extractUrls(list);
        const out = isSingleImage ? (urls[0] ?? '') : urls;
        onChange?.(out);
      }}
    >
      {uploadType === 'file' ? (
        <Button icon={<UploadOutlined />}>上传文件</Button>
      ) : (
        <div>
          <UploadOutlined />
          <div style={{ marginTop: 8 }}>上传</div>
        </div>
      )}
    </Upload>
  );
}
