

import { FormGenerator } from '../FormGenerator/FormGenerator';
import { Popup } from '../Popup/Popup';
import { EditForm } from '../Popup/EditForm';
import { usePromptsLogic } from './promptsLogic';
import { PromptsTableProps } from './promptsTypes';
import { useLanguage } from '../../contexts/LanguageContext';
import styles from './PromptsTable.module.css';

function PromptsTable({ className = '' }: PromptsTableProps) {
  const { t } = useLanguage();
  const {
    prompts,
    loading,
    error,
    columns,
    actions,
    handleDeleteSingle,
    handleDeleteMultiple,
    editModalOpen,
    editingPrompt,
    editPromptFields,
    handleSavePrompt,
    handleCancelEdit,
    refetch
  } = usePromptsLogic();

  if (error) {
    return (
      <div className={styles.errorState}>
        <p>{t('prompts.error.loading', 'Error loading prompts:')} {error}</p>
        <button onClick={refetch} className={styles.retryButton}>
          {t('common.retry', 'Retry')}
        </button>
      </div>
    );
  }

  return (
    <div className={`${styles.promptsTable} ${className}`}>
      <FormGenerator
        data={prompts}
        columns={columns}
        title={t('prompts.title', 'Prompts')}
        searchable={true}
        filterable={true}
        sortable={true}
        resizable={true}
        pagination={true}
        pageSize={10}
        selectable={true}
        loading={loading}
        actions={actions}
        onDelete={handleDeleteSingle}
        onDeleteMultiple={handleDeleteMultiple}
        className={styles.promptsFormGenerator}
      />

      {/* Edit Modal */}
      <Popup
        isOpen={editModalOpen}
        title={t('prompts.modal.edit.title', 'Edit Prompt')}
        onClose={handleCancelEdit}
        size="large"
      >
        {editingPrompt && (
          <EditForm
            data={editingPrompt}
            fields={editPromptFields}
            onSave={handleSavePrompt}
            onCancel={handleCancelEdit}
            saveButtonText={t('prompts.modal.edit.save', 'Save Changes')}
            cancelButtonText={t('common.cancel', 'Cancel')}
          />
        )}
      </Popup>
    </div>
  );
}

export default PromptsTable;
