import { FormGenerator } from '../FormGenerator';
import { useLanguage } from '../../contexts/LanguageContext';
import { Popup, EditForm } from '../Popup';
import styles from './DateienTable.module.css';
import { useDateienLogic } from './dateienLogic.tsx';
import { useFileOperations, type UserFile } from '../../hooks/useFiles';
import type { DateienTableProps } from './dateienInterfaces';

export function DateienTable({ className = '' }: DateienTableProps) {
  const { t } = useLanguage();
  
  // Use the custom hook for all business logic
  const {
    files,
    loading,
    error,
    columns,
    actions,
    editModalOpen,
    editingFile,
    editFileFields,
    handleSaveFile,
    handleCancelEdit,
    refetch
  } = useDateienLogic();
  
  // Use file operations for delete functionality
  const { handleFileDelete } = useFileOperations();

  // Handle single file deletion
  const handleDeleteSingle = async (file: UserFile) => {
    const fileName = file.file_name || file.id;
    if (window.confirm(t('files.delete.confirm', 'Are you sure you want to delete "{name}"?').replace('{name}', fileName))) {
      const success = await handleFileDelete(file.id, () => {
        // Optimistic update - this will be called immediately
        refetch();
      });
      
      if (!success) {
        console.error('Delete failed for file:', file.id);
        // Refetch to restore the file in case of failure
        refetch();
      }
    }
  };

  // Handle multiple file deletion
  const handleDeleteMultiple = async (filesToDelete: UserFile[]) => {
    const fileCount = filesToDelete.length;
    if (window.confirm(t('files.delete.confirmMultiple', 'Are you sure you want to delete {count} files?').replace('{count}', fileCount.toString()))) {
      // Start all delete operations simultaneously
      const deletePromises = filesToDelete.map(async (file) => {
        try {
          const success = await handleFileDelete(file.id);
          return { fileId: file.id, success };
        } catch (error) {
          console.error('Failed to delete file:', file.id, error);
          return { fileId: file.id, success: false };
        }
      });

      // Wait for all deletions to complete
      const results = await Promise.all(deletePromises);
      
      // Check if any deletions failed
      const failedDeletions = results.filter(result => !result.success);
      if (failedDeletions.length > 0) {
        console.error('Some file deletions failed:', failedDeletions);
      }
      
      // Refresh the file list regardless of individual failures
      refetch();
    }
  };

  // Show error state
  if (error) {
    return (
      <div className={`${styles.dateienTable} ${className}`}>
        <div className={styles.errorState}>
          <p>{t('files.error.loading')} {error}</p>
          <button onClick={() => window.location.reload()} className={styles.retryButton}>
            {t('files.button.retry')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={`${styles.dateienTable} ${className}`}>
      <FormGenerator
        data={files}
        columns={columns}
        loading={loading}
        searchable={true}
        filterable={true}
        sortable={true}
        resizable={true}
        pagination={true}
        pageSize={10}
        onRowClick={undefined}
        onDelete={handleDeleteSingle}
        onDeleteMultiple={handleDeleteMultiple}
        actions={actions}
        className={styles.dateienFormGenerator}
      />

      {/* Edit File Modal */}
      <Popup
        isOpen={editModalOpen}
        title={t('files.edit.title', 'Edit File')}
        onClose={handleCancelEdit}
        size="small"
      >
        {editingFile && (
          <EditForm
            data={editingFile}
            fields={editFileFields}
            onSave={handleSaveFile}
            onCancel={handleCancelEdit}
            saveButtonText={t('common.save', 'Save')}
            cancelButtonText={t('common.cancel', 'Cancel')}
          />
        )}
      </Popup>
    </div>
  );
}

export default DateienTable;