'use client';

/**
 * The visitor's chat window (HUB-366), shown on a website in the frame that crm-chat.js opens.
 * The visitor sees their own messages and the answers, nothing else of the CRM.
 */
import { Fragment, useCallback, useEffect, useRef, useState, type FormEvent } from 'react';
import {
  ChatError,
  getChatConfig,
  getTranscript,
  sendChatMessage,
  startChat,
  type ChatConfig,
  type ChatLine,
  type ChatSession,
} from './api.client';
import { linkParts } from './linkify';
import { readSession, saveSession } from './session';
import { shownMessage } from './visibility';

const POLL_MS = 3000;
const MAX_TEXT = 2000;

const clock = (iso: string) =>
  new Date(iso).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });

function Line({ line }: { line: ChatLine }) {
  const mine = line.from === 'visitor';
  return (
    <li className={mine ? 'cw-line cw-line--me' : 'cw-line'}>
      <span className="cw-line__who">
        {mine ? 'You' : line.name} · <time dateTime={line.sentAt}>{clock(line.sentAt)}</time>
      </span>
      <p>
        {linkParts(line.text).map((part, i) => (
          <Fragment key={i}>
            {part.href ? (
              <a href={part.href} target="_blank" rel="noreferrer noopener">
                {part.text}
              </a>
            ) : (
              part.text
            )}
          </Fragment>
        ))}
      </p>
    </li>
  );
}

export function ChatWidget({ inboxId }: { inboxId: string }) {
  const [config, setConfig] = useState<ChatConfig | null>(null);
  const [unavailable, setUnavailable] = useState(false);
  const [session, setSession] = useState<ChatSession | null>(null);
  const [lines, setLines] = useState<ChatLine[]>([]);
  const [text, setText] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const logRef = useRef<HTMLUListElement>(null);
  /* false while the website has the chat window closed */
  const [shown, setShown] = useState(true);

  useEffect(() => {
    const onMessage = (e: MessageEvent<unknown>) => {
      const told = shownMessage(e.data);
      if (told !== null && e.source === window.parent) setShown(told);
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, []);

  useEffect(() => {
    setSession(readSession(inboxId));
    getChatConfig(inboxId).then(setConfig, () => setUnavailable(true));
  }, [inboxId]);

  const forget = useCallback(() => {
    saveSession(inboxId, null);
    setSession(null);
    setLines([]);
    setError('');
  }, [inboxId]);

  /* new answers, while the window is open: the server emails the ones it never fetched */
  useEffect(() => {
    if (!session || !shown) return;
    let alive = true;
    const look = async () => {
      if (document.visibilityState !== 'visible') return;
      try {
        const next = await getTranscript(inboxId, session);
        if (!alive) return;
        setLines((was) => (was.length === next.messages.length ? was : next.messages));
        setConfig((c) => (c && c.online !== next.online ? { ...c, online: next.online } : c));
      } catch (err) {
        // the chat is gone: begin again
        if (alive && err instanceof ChatError && err.status === 404) forget();
      }
    };
    void look();
    const timer = window.setInterval(() => void look(), POLL_MS);
    return () => {
      alive = false;
      window.clearInterval(timer);
    };
  }, [inboxId, session, shown, forget]);

  useEffect(() => {
    if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
  }, [lines]);

  const onStart = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    const value = (name: string) => String(form.get(name) ?? '').trim();
    if (!value('name') || !value('message')) {
      setError('Add your name and a message.');
      return;
    }
    setBusy(true);
    setError('');
    try {
      const started = await startChat(inboxId, {
        name: value('name'),
        message: value('message'),
        ...(value('email') && { email: value('email') }),
        website: value('website'),
      });
      saveSession(inboxId, started);
      setSession(started);
    } catch (err) {
      setError(err instanceof ChatError ? err.message : 'Please try again.');
    } finally {
      setBusy(false);
    }
  };

  const onSend = async () => {
    const message = text.trim();
    if (!session || !message || busy) return;
    setBusy(true);
    setError('');
    try {
      setLines((await sendChatMessage(inboxId, session, message)).messages);
      setText('');
    } catch (err) {
      setError(err instanceof ChatError ? err.message : 'Please try again.');
    } finally {
      setBusy(false);
    }
  };

  if (unavailable) {
    return (
      <main className="cw">
        <p className="cw-note">Chat isn’t available right now.</p>
      </main>
    );
  }
  if (!config) {
    return (
      <main className="cw">
        <p className="cw-note">Loading…</p>
      </main>
    );
  }

  return (
    <main className="cw">
      <header className="cw-head">
        <h1>{config.businessName}</h1>
        <p>
          <span className={config.online ? 'cw-dot is-on' : 'cw-dot'} aria-hidden="true" />
          {config.online ? 'We’re online' : 'We’re away'}
        </p>
      </header>
      {!config.online && (config.awayMessage || config.fallbackEmail) ? (
        <p className="cw-away" role="status">
          {config.awayMessage}
          {config.fallbackEmail ? (
            <>
              {' '}
              You can also email us at{' '}
              <a href={`mailto:${config.fallbackEmail}`}>{config.fallbackEmail}</a>.
            </>
          ) : null}
        </p>
      ) : null}

      {session ? (
        <>
          <ul className="cw-log" ref={logRef} aria-live="polite" aria-label="Chat messages">
            {config.greeting ? <li className="cw-greeting">{config.greeting}</li> : null}
            {lines.map((line) => (
              <Line key={line.id} line={line} />
            ))}
          </ul>
          {error ? (
            <p className="cw-error" role="alert">
              {error}
            </p>
          ) : null}
          <div className="cw-send">
            <textarea
              aria-label="Your message"
              placeholder="Write a message"
              rows={2}
              maxLength={MAX_TEXT}
              value={text}
              onChange={(e) => setText(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  void onSend();
                }
              }}
            />
            <button type="button" disabled={busy || !text.trim()} onClick={() => void onSend()}>
              Send
            </button>
          </div>
          <button type="button" className="cw-new" onClick={forget}>
            Start a new chat
          </button>
        </>
      ) : (
        <form className="cw-start" onSubmit={(e) => void onStart(e)} noValidate>
          {config.greeting ? <p className="cw-greeting">{config.greeting}</p> : null}
          <label>
            Your name
            <input name="name" maxLength={100} autoComplete="name" required />
          </label>
          <label>
            Email (optional, so we can reply if you leave)
            <input name="email" type="email" maxLength={191} autoComplete="email" />
          </label>
          {/* people never see this; programs that fill every box do */}
          <input
            name="website"
            className="cw-trap"
            tabIndex={-1}
            autoComplete="off"
            aria-hidden="true"
          />
          <label>
            Message
            <textarea name="message" rows={4} maxLength={MAX_TEXT} required />
          </label>
          {error ? (
            <p className="cw-error" role="alert">
              {error}
            </p>
          ) : null}
          <button type="submit" disabled={busy}>
            {busy ? 'Starting…' : 'Start chat'}
          </button>
        </form>
      )}
    </main>
  );
}
