/**
 * Content Plan Plugin - Dynamic Settings Form Component
 */

import React, { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useContentPlan } from '../context/ContentPlanContext';
import DynamicFormField from './DynamicFormField';
import { DynamicSettingsFormProps, Settings } from '../types';

const DynamicSettingsForm = ({
    settings,
    fieldConfigs,
    onSave,
}: DynamicSettingsFormProps) => {
    const [formData, setFormData] = useState<Settings>(settings || {});
    const { saving, getString } = useContentPlan();

    const handleFieldChange = (fieldKey: string, value: any): void => {
        setFormData(prev => ({
            ...prev,
            [fieldKey]: value,
        }));
    };

    const handleSubmit = async (e: any): Promise<void> => {
        e.preventDefault();

        try {
            await onSave(formData);
        } catch (error) {
            console.error('Error saving settings:', error);
        }
    };

    const renderFieldValue = (
        fieldKey: string,
        config: any,
        value: any
    ): string => {
        if (config.type === 'password' && value) {
            return `${value.substring(0, 8)}...`;
        }

        if (config.type === 'select' || config.type === 'radio') {
            return (
                config.options?.[value] ||
                value ||
                getString('form_fields', 'not_set', 'Not set')
            );
        }

        if (config.type === 'checkbox') {
            return value
                ? getString('form_fields', 'enabled', 'Enabled')
                : getString('form_fields', 'disabled', 'Disabled');
        }

        return value || getString('form_fields', 'not_set', 'Not set');
    };

    return (
        <div className="space-y-4 sm:space-y-6">
            {/* Settings Form */}
            <form
                onSubmit={handleSubmit}
                className="bg-white rounded-lg p-4 sm:p-6 flex flex-col min-h-[400px] sm:min-h-[500px] md:min-h-[600px]"
            >
                <div className="space-y-6 sm:space-y-8 flex-1">
                    {Object.entries(fieldConfigs).map(([fieldKey, config]) => (
                        <DynamicFormField
                            key={fieldKey}
                            fieldKey={fieldKey}
                            config={config}
                            value={formData[fieldKey]}
                            onChange={handleFieldChange}
                        />
                    ))}
                </div>

                <div className="mt-auto pt-4 sm:pt-6 flex flex-col sm:flex-row gap-2 sm:gap-3">
                    <button
                        type="button"
                        onClick={() => setFormData(settings || {})}
                        className="cpepai-button cpepai-button--secondary w-full sm:w-auto"
                    >
                        {getString('settings', 'reset', 'Reset')}
                    </button>
                    <button
                        type="submit"
                        disabled={saving}
                        className="cpepai-button cpepai-button--primary w-full sm:w-auto"
                    >
                        {saving
                            ? getString('settings', 'saving', 'Saving...')
                            : getString(
                                  'settings',
                                  'save_settings',
                                  'Save Settings'
                              )}
                    </button>
                </div>
            </form>
        </div>
    );
};

export default DynamicSettingsForm;
