/**
 * Prompt Instructions Component
 */
import { useState, useEffect } from 'react';

const PromptInstructions = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [promptInstructions, setPromptInstructions] = useState('');
  const [promptInstructionsImage, setPromptInstructionsImage] = useState('');

  useEffect(() => {
    loadPromptInstructions();
  }, []);

  const loadPromptInstructions = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `${window.samurAiAdmin.apiUrl}/prompt-instructions`,
        {
          headers: {
            'X-WP-Nonce': window.samurAiAdmin.nonce,
          },
        }
      );

      const data = await response.json();

      if (data.success) {
        setPromptInstructions(data.data.PromptInstructions || '');
        setPromptInstructionsImage(data.data.PromptInstructionsImage || '');
      } else {
        setError(data.message || 'Failed to load prompt instructions');
      }
    } catch (err) {
      setError('An error occurred while loading prompt instructions');
      console.error('Error loading prompt instructions:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSave = async () => {
    setIsSaving(true);
    setError(null);
    setSuccess(null);

    try {
      const response = await fetch(
        `${window.samurAiAdmin.apiUrl}/prompt-instructions`,
        {
          method: 'POST',
          headers: {
            'X-WP-Nonce': window.samurAiAdmin.nonce,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            promptInstructions,
            promptInstructionsImage,
          }),
        }
      );

      const data = await response.json();

      if (data.success) {
        setSuccess('Prompt instructions saved successfully!');
        setTimeout(() => setSuccess(null), 3000);
      } else {
        setError(data.message || 'Failed to save prompt instructions');
      }
    } catch (err) {
      setError('An error occurred while saving prompt instructions');
      console.error('Error saving prompt instructions:', err);
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="prompt-instructions">
        <div className="loading">Loading prompt instructions...</div>
      </div>
    );
  }

  // If there was an error loading, only show the error message
  if (error && !success) {
    return (
      <div className="prompt-instructions">
        <div className="prompt-instructions-header">
          <h3>Extra Prompt Instructions</h3>
          <p>
            Configure additional instructions that will be sent with AI prompts
            for text and image generation.
          </p>
        </div>

        <div className="prompt-instructions-error">
          <strong>Error:</strong> {error}
        </div>
      </div>
    );
  }

  return (
    <div className="prompt-instructions">
      <div className="prompt-instructions-header">
        <h3>Extra Prompt Instructions</h3>
        <p>
          Configure additional instructions that will be sent with AI prompts
          for text and image generation.
        </p>
      </div>

      {success && (
        <div className="prompt-instructions-success">
          <strong>Success:</strong> {success}
        </div>
      )}

      <div className="prompt-instructions-fields">
        <div className="field-group">
          <label htmlFor="prompt-instructions">
            <strong>Prompt Instructions</strong>
          </label>
          <p className="field-description">
            Additional instructions for general AI text generation prompts.
          </p>
          <textarea
            id="prompt-instructions"
            className="large-text"
            rows="8"
            value={promptInstructions}
            onChange={(e) => setPromptInstructions(e.target.value)}
            placeholder="Enter additional prompt instructions for text generation..."
          />
        </div>

        <div className="field-group">
          <label htmlFor="prompt-instructions-image">
            <strong>Prompt Instructions (Image)</strong>
          </label>
          <p className="field-description">
            Additional instructions for AI image generation prompts.
          </p>
          <textarea
            id="prompt-instructions-image"
            className="large-text"
            rows="8"
            value={promptInstructionsImage}
            onChange={(e) => setPromptInstructionsImage(e.target.value)}
            placeholder="Enter additional prompt instructions for image generation..."
          />
        </div>
      </div>

      <div className="prompt-instructions-actions">
        <button
          className="button button-primary"
          onClick={handleSave}
          disabled={isSaving}
        >
          {isSaving ? 'Saving...' : 'Save Prompt Instructions'}
        </button>
      </div>
    </div>
  );
};

export default PromptInstructions;
