/**
 * KRA - Select Image Component
 * Select image from uploaded files
 */
import React, { useState, useEffect } from 'react';
import { Modal, Image, Spin, Empty, Pagination, Input } from 'antd';
import { getFileList } from '@/services/kratos/fileUpload';

const { Search } = Input;

interface SelectImageProps {
  visible: boolean;
  onCancel: () => void;
  onSelect: (url: string) => void;
  multiple?: boolean;
}

interface FileItem {
  ID: number;
  url: string;
  name: string;
  tag: string;
}

const SelectImage: React.FC<SelectImageProps> = ({
  visible,
  onCancel,
  onSelect,
  multiple = false,
}) => {
  const [loading, setLoading] = useState(false);
  const [files, setFiles] = useState<FileItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(12);
  const [keyword, setKeyword] = useState('');
  const [selected, setSelected] = useState<string[]>([]);

  const fetchFiles = async () => {
    setLoading(true);
    try {
      const res = await getFileList({ page, pageSize, keyword });
      if (res.code === 0) {
        setFiles(res.data?.list || []);
        setTotal(res.data?.total || 0);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchFiles();
    }
  }, [visible, page, keyword]);

  const handleSelect = (url: string) => {
    if (multiple) {
      setSelected((prev) =>
        prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url]
      );
    } else {
      onSelect(url);
    }
  };

  const handleOk = () => {
    if (multiple && selected.length > 0) {
      onSelect(selected.join(','));
    }
    onCancel();
  };

  return (
    <Modal
      title="选择图片"
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={800}
      okButtonProps={{ disabled: multiple && selected.length === 0 }}
    >
      <Search
        placeholder="搜索文件名"
        onSearch={(value) => {
          setKeyword(value);
          setPage(1);
        }}
        style={{ marginBottom: 16 }}
      />
      <Spin spinning={loading}>
        {files.length === 0 ? (
          <Empty description="暂无图片" />
        ) : (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {files.map((file) => (
              <div
                key={file.ID}
                onClick={() => handleSelect(file.url)}
                style={{
                  width: 120,
                  height: 120,
                  border: selected.includes(file.url)
                    ? '2px solid #1890ff'
                    : '1px solid #d9d9d9',
                  borderRadius: 4,
                  cursor: 'pointer',
                  overflow: 'hidden',
                }}
              >
                <Image
                  src={file.url}
                  alt={file.name}
                  width={118}
                  height={118}
                  style={{ objectFit: 'cover' }}
                  preview={false}
                />
              </div>
            ))}
          </div>
        )}
      </Spin>
      <Pagination
        current={page}
        total={total}
        pageSize={pageSize}
        onChange={setPage}
        style={{ marginTop: 16, textAlign: 'right' }}
        showSizeChanger={false}
      />
    </Modal>
  );
};

export default SelectImage;
