import React, { useState } from 'react';
import styles from './SendMessageWizard.module.css';
import { tokenService } from '../../services/TokenService';
import { messageApi, CreateMessageRequest } from '../../api/messageApi';

function MessageForm({
  message,
  onMessageChange,
  onMessageCreated,
  onToggleScheduled,
}) {
  const [characterCount, setCharacterCount] = useState(message.length);
  const [isCreatingMessage, setIsCreatingMessage] = useState(false);
  const [isScheduledChecked, setIsScheduledChecked] = useState(false);
  const [createdMessage, setCreatedMessage] = useState(null);

  const handleMessageChange = (e) => {
    const newMessage = e.target.value;
    onMessageChange(newMessage);
    setCharacterCount(newMessage.length);
  };

  const handleIsScheduledCheckbox = (event) => {
    setIsScheduledChecked(event.target.checked);
    onToggleScheduled(event.target.checked);
  };

  const createMessage = async () => {
    if (!message.trim()) {
      return;
    }

    setIsCreatingMessage(true);
    setCreatedMessage(null);

    try {
      const userId = tokenService.getUserId();
      let reqBod = new CreateMessageRequest();
      reqBod.user_id = userId;
      reqBod.content = message;
      const response = await messageApi.createMessage(
        reqBod,
        tokenService.bearerToken()
      );

      if (!response) {
        throw new Error('Failed to create message');
      } else {
        const createdMessage = response.data[0];
        setCreatedMessage(createdMessage);
        if (onMessageCreated) {
          onMessageCreated(createdMessage);
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsCreatingMessage(false);
    }
  };

  return (
    <div className={styles.messageForm}>
      <div className={styles.formGroup}>
        <label htmlFor="message" className={styles.formLabel}>
          Your Message
        </label>
        <textarea
          id="message"
          value={message}
          onChange={handleMessageChange}
          placeholder="Type your message here..."
          className={styles.messageTextarea}
          rows={8}
        />
        <div className={styles.textareaFooter}>
          <span className={styles.characterCount}>
            {characterCount} characters
          </span>
          <button
            type="button"
            onClick={createMessage}
            disabled={isCreatingMessage || !message.trim()}
            className={styles.testButton}
          >
            {isCreatingMessage ? 'Creating message...' : 'Create message'}
          </button>
        </div>
      </div>

      {createdMessage && (
        <div
          className={`${styles.createdMessage} ${
            createdMessage.content ? styles.success : styles.error
          }`}
        >
          {createdMessage.content}
        </div>
      )}

      <div className={styles.messageTips}>
        <h4>Tips:</h4>
        <ul>
          <li>Keep messages clear and concise</li>
          <li>Use [Name] placeholder for personalization</li>
          <li>Check spelling and grammar</li>
        </ul>
      </div>
      <div>
        <label>
          <input
            type="checkbox"
            checked={isScheduledChecked}
            onChange={handleIsScheduledCheckbox}
            readOnly
          />
          Schedule Message
        </label>
      </div>
    </div>
  );
}

export default MessageForm;
