'use client';

import * as React from 'react';
import AdminModal from '@/app/components/admin/admin-modal.jsx';

export function AddAllowlistModal({ onSubmit }) {
  const [open, setOpen] = React.useState(false);
  const [chatId, setChatId] = React.useState('');
  const [label, setLabel] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const close = React.useCallback(() => {
    if (submitting) return;
    setOpen(false);
    setError(null);
  }, [submitting]);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!chatId.trim()) return;
    setSubmitting(true);
    setError(null);
    const result = await onSubmit({ chat_id: chatId.trim(), label: label.trim() || null });
    setSubmitting(false);
    if (result?.ok === false) {
      setError(result.error || 'Failed to add');
      return;
    }
    setChatId('');
    setLabel('');
    setOpen(false);
  }

  return (
    <>
      <button type="button" className="admin-button secondary agents-new-cta" onClick={() => setOpen(true)}>
        <span aria-hidden className="agents-new-cta-glyph">+</span>
        Add allowlist
      </button>

      <AdminModal open={open} onClose={close} eyebrow="Allowlist" title="Allow a sender">
        <form className="agents-modal-form" onSubmit={handleSubmit}>
          <section className="agents-modal-section">
            <label className="agents-modal-field wide">
              <span>Chat id</span>
              <input
                placeholder="9715XXXXXXXX or 9715XXXXXXXX@s.whatsapp.net"
                value={chatId}
                onChange={(e) => setChatId(e.target.value)}
                autoFocus
                required
              />
            </label>
            <label className="agents-modal-field wide">
              <span>Label</span>
              <input
                placeholder="Optional"
                value={label}
                onChange={(e) => setLabel(e.target.value)}
              />
            </label>
          </section>

          {error ? <p className="agents-modal-error">{error}</p> : null}

          <footer className="agents-modal-foot">
            <button type="button" className="admin-button secondary" onClick={close} disabled={submitting}>
              Cancel
            </button>
            <button type="submit" className="admin-button" disabled={submitting} aria-busy={submitting || undefined}>
              {submitting ? 'Adding…' : 'Add to allowlist'}
            </button>
          </footer>
        </form>
      </AdminModal>
    </>
  );
}

export function SendMessageModal({ onSubmit }) {
  const [open, setOpen] = React.useState(false);
  const [chatId, setChatId] = React.useState('');
  const [text, setText] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const close = React.useCallback(() => {
    if (submitting) return;
    setOpen(false);
    setError(null);
  }, [submitting]);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!chatId.trim() || !text.trim()) return;
    setSubmitting(true);
    setError(null);
    const result = await onSubmit({ chat_id: chatId.trim(), text: text.trim() });
    setSubmitting(false);
    if (result?.ok === false) {
      setError(result.error || 'Failed to send');
      return;
    }
    setText('');
    setOpen(false);
  }

  return (
    <>
      <button type="button" className="admin-button agents-new-cta" onClick={() => setOpen(true)}>
        <span aria-hidden className="agents-new-cta-glyph">+</span>
        New message
      </button>

      <AdminModal open={open} onClose={close} eyebrow="WhatsApp" title="Send a message">
        <form className="agents-modal-form" onSubmit={handleSubmit}>
          <section className="agents-modal-section">
            <label className="agents-modal-field wide">
              <span>Chat id</span>
              <input
                placeholder="Digits or full JID"
                value={chatId}
                onChange={(e) => setChatId(e.target.value)}
                autoFocus
                required
              />
            </label>
            <label className="agents-modal-field wide">
              <span>Message</span>
              <textarea
                rows={4}
                placeholder="Plain text only"
                value={text}
                onChange={(e) => setText(e.target.value)}
                required
              />
            </label>
          </section>

          {error ? <p className="agents-modal-error">{error}</p> : null}

          <p className="agents-modal-help">
            Manual send. Logs to whatsapp_messages with an audit row.
          </p>

          <footer className="agents-modal-foot">
            <button type="button" className="admin-button secondary" onClick={close} disabled={submitting}>
              Cancel
            </button>
            <button type="submit" className="admin-button" disabled={submitting} aria-busy={submitting || undefined}>
              {submitting ? 'Sending…' : 'Send'}
            </button>
          </footer>
        </form>
      </AdminModal>
    </>
  );
}
