import { FormGenerator } from '../FormGenerator';
import { useLanguage } from '../../contexts/LanguageContext';
import { Popup, EditForm } from '../Popup';
import { FilePreview } from '../FilePreview';
import styles from './DateienTable.module.css';
import { useDateienLogic } from './dateienLogic.tsx';
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,
    refetch,
    columns,
    actions,
    editModalOpen,
    editingFile,
    editFileFields,
    previewModalOpen,
    previewingFile,
    handleSaveFile,
    handleCancelEdit,
    handleClosePreview,
    handleDelete,
    handleDeleteMultiple
  } = useDateienLogic();

  // 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={handleDelete}
        onDeleteMultiple={handleDeleteMultiple}
        onRefresh={refetch}
        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>

      {/* File Preview Modal */}
      {previewingFile && (
        <FilePreview
          isOpen={previewModalOpen}
          onClose={handleClosePreview}
          fileId={previewingFile.id}
          fileName={previewingFile.file_name}
          mimeType={previewingFile.mime_type}
        />
      )}
    </div>
  );
}

export default DateienTable;