import { useEffect, useState } from 'react';
import { useFileService } from '../hooks/useFileService';
import type { FileMetadata, FileServiceConfig } from '../types';

interface FileListProps {
  config?: FileServiceConfig;
  onFileSelect?: (file: FileMetadata) => void;
  onFileDelete?: (fileId: string) => void;
  className?: string;
  showPreview?: boolean;
  selectedFileId?: string | null;
}

export function FileList({
  config,
  onFileSelect,
  onFileDelete,
  className = '',
  showPreview = false,
  selectedFileId = null,
}: FileListProps) {
  const { listFiles, deleteFile, loading, error } = useFileService(config);
  const [files, setFiles] = useState<FileMetadata[]>([]);

  const loadFiles = async () => {
    const fileList = await listFiles();
    setFiles(fileList);
  };

  useEffect(() => {
    loadFiles();
  }, []);

  const handleDelete = async (fileId: string) => {
    const success = await deleteFile(fileId);
    if (success) {
      await loadFiles();
      onFileDelete?.(fileId);
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  if (loading && files.length === 0) {
    return <div className={`file-list loading ${className}`}>Loading files...</div>;
  }

  if (error) {
    return <div className={`file-list error ${className}`}>Error: {error}</div>;
  }

  if (files.length === 0) {
    return <div className={`file-list empty ${className}`}>No files found</div>;
  }

  return (
    <div className={`file-list ${className}`}>
      <h3>Files ({files.length})</h3>
      <ul>
        {files.map((file) => (
          <li key={file.id} className="file-item">
            <div className="file-info" onClick={() => onFileSelect?.(file)}>
              <span className="file-name">{file.fileName}</span>
              <span className="file-size">{formatFileSize(file.size)}</span>
              <span className="file-type">{file.fileExtension}</span>
            </div>
            <button
              className="delete-button"
              onClick={() => handleDelete(file.id)}
              aria-label={`Delete ${file.fileName}`}
            >
              Delete
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

