import { useEffect, useState } from 'react';
import Input from '../Input/input';

export default function CustomInstructions({
  customInstructions,
  setCustomInstructions,
}: {
  customInstructions: string[];
  setCustomInstructions: (customInstructions: string[]) => void;
}) {
  useEffect(() => {
    setLastInstructions(customInstructions);
  }, []);

  const [lastInstructions, setLastInstructions] = useState<string[]>([]);
  async function postInstructions(value: string[]): Promise<void> {
    try {
      const response = await fetch(
        `${wpApiSettings.root}botfoundry/v1/set-custom-instructions`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': wpApiSettings.nonce, // Include the nonce for authentication
          },
          body: JSON.stringify({ customInstructions: value }),
        }
      );
      if (!response.ok) {
        throw new Error('Failed to post main goal');
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLastInstructions(value);
    }
  }

  return (
    <div>
      <h4 className="mt-0 mb-8">Custom instructions</h4>
      <p>
        Here you can add custom instructions for the chat bot. These
        instructions will be used to train the AI to answer questions specific
        to your website.
      </p>
      {customInstructions.map((instruction, index) => (
        <div className="d-flex gap-8 mb-16" key={index}>
          <Input
            value={instruction}
            onChange={(value) => {
              const newInstructions = [...customInstructions];
              newInstructions[index] = value;
              setCustomInstructions(newInstructions);
            }}
            className="extra-large-input"
          />
          <button
            className="botfoundry-btn"
            onClick={() => {
              const newInstructions = [...customInstructions];
              newInstructions.splice(index, 1);
              setCustomInstructions(newInstructions);
            }}
          >
            -
          </button>
        </div>
      ))}
      <div className="d-flex gap-8">
        <button
          className="botfoundry-btn std-button"
          onClick={() => postInstructions(customInstructions)}
          disabled={
            JSON.stringify(lastInstructions) ===
            JSON.stringify(customInstructions)
          }
        >
          Save
        </button>
        <button
          className="botfoundry-btn std-button"
          onClick={() => {
            setCustomInstructions([...customInstructions, '']);
          }}
        >
          Add new field
        </button>
      </div>
    </div>
  );
}
