/**
 * KRA - Select File Component
 * Select file from uploaded files
 */
import React, { useState, useEffect } from 'react';
import { Modal, Table, Spin, Input, Tag } from 'antd';
import { FileOutlined, FileImageOutlined, FileTextOutlined, FilePdfOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getFileList } from '@/services/kratos/fileUpload';
import { formatFileSize } from '@/utils/format';

const { Search } = Input;

interface SelectFileProps {
  visible: boolean;
  onCancel: () => void;
  onSelect: (url: string, file: FileItem) => void;
  accept?: string;
}

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

const getFileIcon = (name: string) => {
  const ext = name.split('.').pop()?.toLowerCase();
  if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(ext || '')) {
    return <FileImageOutlined style={{ color: '#52c41a' }} />;
  }
  if (['pdf'].includes(ext || '')) {
    return <FilePdfOutlined style={{ color: '#ff4d4f' }} />;
  }
  if (['doc', 'docx', 'txt', 'md'].includes(ext || '')) {
    return <FileTextOutlined style={{ color: '#1890ff' }} />;
  }
  return <FileOutlined />;
};

const SelectFile: React.FC<SelectFileProps> = ({
  visible,
  onCancel,
  onSelect,
  accept,
}) => {
  const [loading, setLoading] = useState(false);
  const [files, setFiles] = useState<FileItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(10);
  const [keyword, setKeyword] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  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();
      setSelectedRowKeys([]);
    }
  }, [visible, page, keyword]);

  const columns: ColumnsType<FileItem> = [
    {
      title: '文件名',
      dataIndex: 'name',
      render: (name: string) => (
        <span>
          {getFileIcon(name)} {name}
        </span>
      ),
    },
    {
      title: '标签',
      dataIndex: 'tag',
      width: 100,
      render: (tag: string) => tag ? <Tag>{tag}</Tag> : '-',
    },
  ];

  const handleOk = () => {
    const selectedFile = files.find((f) => f.ID === selectedRowKeys[0]);
    if (selectedFile) {
      onSelect(selectedFile.url, selectedFile);
    }
    onCancel();
  };

  return (
    <Modal
      title="选择文件"
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={700}
      okButtonProps={{ disabled: selectedRowKeys.length === 0 }}
    >
      <Search
        placeholder="搜索文件名"
        onSearch={(value) => {
          setKeyword(value);
          setPage(1);
        }}
        style={{ marginBottom: 16 }}
      />
      <Table
        rowKey="ID"
        columns={columns}
        dataSource={files}
        loading={loading}
        rowSelection={{
          type: 'radio',
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        pagination={{
          current: page,
          total,
          pageSize,
          onChange: setPage,
          showSizeChanger: false,
        }}
        size="small"
      />
    </Modal>
  );
};

export default SelectFile;
