import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';

export default function Testing() {
  const [email, setEmail] = useState('');
  const [isSending, setIsSending] = useState(false);
  const [notice, setNotice] = useState(null);
  const [logLines, setLogLines] = useState([]);

  const sendForm = async (e) => {
    e.preventDefault();
    setNotice(null);
    setLogLines([]);

    if (!email) {
      setNotice({ type: 'error', message: __('Please enter an email address.', 'hq-mail') });
      return;
    }

    setIsSending(true);

    try {
      const response = await fetch(hqMailAdmin.sendTestUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': hqMailAdmin.nonce,
        },
        body: JSON.stringify({ email }),
      });

      const data = await response.json();

      if (!response.ok) {
        const serverLog = data?.data?.log || data?.log || [];
        setNotice({
          type: 'error',
          message: data?.message || __('Email sending failed.', 'hq-mail'),
        });
        setLogLines(Array.isArray(serverLog) ? serverLog : []);
        return;
      }

      const serverLog = data?.log || [];
      setNotice({
        type: 'success',
        message: data?.message || __('Email sent.', 'hq-mail'),
      });
      setLogLines(Array.isArray(serverLog) ? serverLog : []);
      setEmail('');
    } catch (error) {
      setNotice({
        type: 'error',
        message: __('Network error. Please try again.', 'hq-mail'),
      });
      setLogLines([__('Client error: request was not completed.', 'hq-mail')]);
    } finally {
      setIsSending(false);
    }
  };

  return (
    <div className="mt-5 p-6 bg-white rounded shadow">
      <h2 className="text-2xl font-bold mb-4">{__('Testing', 'hq-mail')}</h2>
      <p className="mb-4">{__('Send a test email to the specified address.', 'hq-mail')}</p>

      <form onSubmit={sendForm}>
        <div>
          <input className="mb-4 rounded border px-3 py-2 w-full" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder={__('Enter email', 'hq-mail')} required />
        </div>

        <div>
          <button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-60" disabled={isSending}>
            {isSending ? __('Sending...', 'hq-mail') : __('Send', 'hq-mail')}
          </button>
        </div>
      </form>

      {notice && <p className={`mt-4 ${notice.type === 'success' ? 'text-green-600' : 'text-red-600'}`}>{notice.message}</p>}

      {logLines.length > 0 && (
        <div className="mt-4 rounded border bg-slate-50 p-3">
          <p className="mb-2 font-semibold">{__('Sending Log', 'hq-mail')}</p>
          <div className="space-y-1 font-mono text-sm">
            {logLines.map((line, index) => (
              <p key={`${index}-${line}`}>{line}</p>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
