"use client";

import { useEffect, useRef, useState, type TextareaHTMLAttributes } from "react";

/*
 * A message box with its character limit shown (QA BUG-34: long messages were cut without warning). The count is
 * live; a paste longer than the room left is cut by the browser, so that case says so instead of passing silently.
 * The count resets with its form.
 */
export function LimitedTextarea({ max, id, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement> & { max: number; id: string }) {
  const ref = useRef<HTMLTextAreaElement>(null);
  const [length, setLength] = useState(0);
  const [cut, setCut] = useState(false);

  useEffect(() => {
    const form = ref.current?.form;
    if (!form) return;
    const reset = () => {
      setLength(0);
      setCut(false);
    };
    form.addEventListener("reset", reset);
    return () => form.removeEventListener("reset", reset);
  }, []);

  const countId = `${id}-count`;
  return (
    <>
      <textarea
        {...props}
        ref={ref}
        id={id}
        maxLength={max}
        aria-describedby={[props["aria-describedby"], countId].filter(Boolean).join(" ")}
        onInput={(e) => {
          const n = e.currentTarget.value.length;
          setLength(n);
          if (n < max) setCut(false);
        }}
        onPaste={(e) => {
          const el = e.currentTarget;
          const room = max - (el.value.length - (el.selectionEnd - el.selectionStart));
          if (e.clipboardData.getData("text").length > room) setCut(true);
        }}
      />
      <p className={`field__count${cut || length >= max ? " is-full" : ""}`} id={countId} aria-live="polite">
        {cut
          ? `That text was longer than ${max.toLocaleString("en-US")} characters, so the end was cut off. Shorten it, or send the rest in a second message.`
          : `${length.toLocaleString("en-US")} / ${max.toLocaleString("en-US")} characters`}
      </p>
    </>
  );
}
