import React from "react";
import { Icon } from "@iconify/react";

interface FileUploadProps {
  files: File[];
  onChange: (files: File[]) => void;
}

export const FileUpload: React.FC<FileUploadProps> = ({ files, onChange }) => {
  const handleRemove = (index: number) => {
    onChange(files.filter((_, i) => i !== index));
  };

  const handleClearAll = () => {
    onChange([]);
  };

  const getFileIcon = (filename: string): string => {
    const ext = filename.split(".").pop()?.toLowerCase() || "";
    if (ext === "pdf") return "mdi:file-pdf";
    if (["doc", "docx"].includes(ext)) return "mdi:file-word";
    if (["xls", "xlsx"].includes(ext)) return "mdi:file-excel";
    if (ext === "txt") return "mdi:file-document";
    if (["zip", "rar", "7z"].includes(ext)) return "mdi:folder-zip";
    return "mdi:file";
  };

  const formatFileSize = (bytes: number): string => {
    return (bytes / 1024 / 1024).toFixed(2) + " MB";
  };

  if (files.length === 0) {
    return null;
  }

  return (
    <div className="file-preview-container" style={{ display: "block" }}>
      <div className="file-preview-header">
        <span>Прикрепленные файлы:</span>
        <button
          type="button"
          className="clear-files-btn"
          onClick={handleClearAll}
        >
          Очистить все
        </button>
      </div>
      <div className="file-preview-list">
        {files.map((file, index) => (
          <div key={index} className="file-preview-item">
            <Icon icon={getFileIcon(file.name)} className="file-icon" />
            <div className="file-info">
              <div className="file-name">{file.name}</div>
              <div className="file-size">{formatFileSize(file.size)}</div>
            </div>
            <button
              className="file-preview-remove"
              onClick={() => handleRemove(index)}
              title="Удалить"
            >
              <Icon icon="mdi:close" />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
};
