import React, { useState } from 'react';
import axios from 'axios';

function SettingsForm({ gateway, onClose }) {
  const [settings, setSettings] = useState(gateway.settings || {});
  const [saving, setSaving] = useState(false);

  const handleChange = (key, value) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);

    try {
      const response = await axios.post(
        `${window.irandargahData.restUrl}save-settings`,
        {
          gateway_id: gateway.id,
          settings: settings
        },
        {
          headers: {
            'X-WP-Nonce': window.irandargahData.restNonce
          }
        }
      );

      if (response.data.success) {
        alert('تنظیمات با موفقیت ذخیره شد.');
        window.location.reload();
      }
    } catch (error) {
      console.error('Error saving settings:', error);
      alert('خطا در ذخیره‌سازی تنظیمات');
    } finally {
      setSaving(false);
    }
  };

  return (
    <form className="irandargah-settings-form" onSubmit={handleSubmit}>
      {gateway.settings_sections && Object.entries(gateway.settings_sections).map(([sectionKey, section]) => (
        <div key={sectionKey} className="irandargah-settings-section">
          <h3 className="irandargah-section-title">{section.title}</h3>
          {section.fields && Object.entries(section.fields).map(([fieldKey, field]) => (
            <div key={fieldKey} className="irandargah-form-group">
              <label className="irandargah-label">
                {field.title}
                {field.description && (
                  <span className="irandargah-help-tip" title={field.description}>?</span>
                )}
              </label>
              {field.type === 'text' && (
                <input
                  type="text"
                  className="irandargah-input"
                  value={settings[fieldKey] || field.value || ''}
                  onChange={(e) => handleChange(fieldKey, e.target.value)}
                />
              )}
              {field.type === 'textarea' && (
                <textarea
                  className="irandargah-textarea"
                  value={settings[fieldKey] || field.value || ''}
                  onChange={(e) => handleChange(fieldKey, e.target.value)}
                  rows="4"
                />
              )}
              {field.type === 'checkbox' && (
                <label className="irandargah-checkbox">
                  <input
                    type="checkbox"
                    checked={settings[fieldKey] === 'yes' || field.value === 'yes'}
                    onChange={(e) => handleChange(fieldKey, e.target.checked ? 'yes' : 'no')}
                  />
                  <span className="irandargah-checkbox-label">{field.label}</span>
                </label>
              )}
            </div>
          ))}
        </div>
      ))}
      <div className="irandargah-form-actions">
        <button type="submit" className="irandargah-btn irandargah-btn-success" disabled={saving}>
          {saving ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
        </button>
        <button type="button" className="irandargah-btn irandargah-btn-secondary" onClick={onClose}>
          انصراف
        </button>
      </div>
    </form>
  );
}

export default SettingsForm;

