
import { useState } from 'react';
import { IoMdAdd } from 'react-icons/io';
import { PromptsTable } from '../../components/Prompts';
import { useLanguage } from '../../contexts/LanguageContext';
import { Popup } from '../../components/ui/Popup/Popup';
import { EditForm } from '../../components/ui/Popup/EditForm';
import { usePrompts, usePromptOperations } from '../../hooks/usePrompts';
import type { EditFieldConfig } from '../../components/ui/Popup/EditForm';
import sharedStyles from '../../core/PageManager/pages.module.css';

function Prompts() {
    const { t } = useLanguage();
    const { prompts } = usePrompts();
    const { handlePromptCreate, creatingPrompt } = usePromptOperations();
    const [createModalOpen, setCreateModalOpen] = useState(false);
    const [tableRefreshKey, setTableRefreshKey] = useState(0);

    // Configure fields for creating a new prompt
    const createPromptFields: EditFieldConfig[] = [
        {
            key: 'name',
            label: t('prompts.field.name', 'Prompt Name'),
            type: 'string',
            editable: true,
            required: true,
            validator: (value: string) => {
                if (!value || value.trim() === '') {
                    return t('prompts.validation.nameRequired', 'Prompt name cannot be empty');
                }
                if (value.length > 100) {
                    return t('prompts.validation.nameTooLong', 'Prompt name cannot exceed 100 characters');
                }
                return null;
            }
        },
        {
            key: 'content',
            label: t('prompts.field.content', 'Prompt Content'),
            type: 'textarea',
            editable: true,
            required: true,
            minRows: 4,
            maxRows: 8,
            validator: (value: string) => {
                if (!value || value.trim() === '') {
                    return t('prompts.validation.contentRequired', 'Prompt content cannot be empty');
                }
                if (value.length > 10000) {
                    return t('prompts.validation.contentTooLong', 'Prompt content cannot exceed 10,000 characters');
                }
                return null;
            }
        }
    ];

    const handleCreatePrompt = () => {
        setCreateModalOpen(true);
    };

    const handleSaveNewPrompt = async (newPromptData: any) => {
        // Get mandateId from existing prompts or use a default
        const mandateId = prompts.length > 0 ? prompts[0].mandateId : '';
        
        if (!mandateId) {
            console.error('No mandateId available. Cannot create prompt.');
            // TODO: Show error message to user
            return;
        }

        try {
            const result = await handlePromptCreate({
                name: newPromptData.name,
                content: newPromptData.content,
                mandateId: mandateId
            });

            if (result.success) {
                // Close modal
                setCreateModalOpen(false);
                
                // Force remount PromptsTable to refetch
                setTableRefreshKey(prev => prev + 1);
            } else {
                console.error('Failed to create prompt:', result.error);
                // TODO: Show error message to user
            }
        } catch (error) {
            console.error('Failed to create prompt:', error);
            // TODO: Show error message to user
        }
    };

    const handleCancelCreate = () => {
        setCreateModalOpen(false);
    };

    return (
        <div className={sharedStyles.pageContainer}>
            <div className={sharedStyles.pageCard}>
                <div className={sharedStyles.pageHeader}>
                    <h1 className={sharedStyles.pageTitle}>{t('prompts.title', 'Prompts')}</h1>
                    <button
                        className={sharedStyles.primaryButton}
                        onClick={handleCreatePrompt}
                        disabled={creatingPrompt}
                        aria-label="Add new prompt"
                    >
                        <span className={sharedStyles.buttonIcon}><IoMdAdd /></span>
                        {creatingPrompt ? t('prompts.creating', 'Creating...') : t('prompts.addNew', 'Add Prompt')}
                    </button>
                </div>
                <div className={sharedStyles.pageContent}>
                    <PromptsTable key={tableRefreshKey} />
                </div>

                {/* Create Prompt Modal */}
                <Popup
                    isOpen={createModalOpen}
                    title={t('prompts.modal.create.title', 'Create New Prompt')}
                    onClose={handleCancelCreate}
                    size="large"
                >
                    <EditForm
                        data={{ name: '', content: '' }}
                        fields={createPromptFields}
                        onSave={handleSaveNewPrompt}
                        onCancel={handleCancelCreate}
                        saveButtonText={t('prompts.modal.create.save', 'Create Prompt')}
                        cancelButtonText={t('common.cancel', 'Cancel')}
                    />
                </Popup>
            </div>
        </div>
    );
}

export default Prompts;

