import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FiSend, FiX } from "react-icons/fi";
import type { Message } from "@/api/generated/private/models/message";
import Button from "@/components/ui/Button";

interface Props {
  disabled?: boolean;
  replyTo?: Message | null;
  onCancelReply?: () => void;
  onSend: (text: string, replyToId?: number) => boolean;
  onTyping?: (isTyping: boolean) => void;
}

export default function MessageComposer({
  disabled,
  replyTo,
  onCancelReply,
  onSend,
  onTyping,
}: Props) {
  const { t } = useTranslation("social");
  const [text, setText] = useState("");
  const typingTimerRef = useRef<number | null>(null);
  const isTypingRef = useRef(false);

  useEffect(() => {
    return () => {
      if (typingTimerRef.current) window.clearTimeout(typingTimerRef.current);
      if (isTypingRef.current) onTyping?.(false);
    };
  }, [onTyping]);

  function notifyTyping() {
    if (!isTypingRef.current) {
      isTypingRef.current = true;
      onTyping?.(true);
    }
    if (typingTimerRef.current) window.clearTimeout(typingTimerRef.current);
    typingTimerRef.current = window.setTimeout(() => {
      isTypingRef.current = false;
      onTyping?.(false);
    }, 2500);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = text.trim();
    if (!trimmed) return;
    const ok = onSend(trimmed, replyTo?.id);
    if (ok) {
      setText("");
      if (isTypingRef.current) {
        isTypingRef.current = false;
        onTyping?.(false);
      }
      onCancelReply?.();
    }
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="border-t border-brand-lines/15 bg-brand-bg/60 px-4 py-3"
    >
      {replyTo && (
        <div className="mb-2 flex items-center justify-between gap-2 rounded-xl border border-brand-lines/15 bg-brand-bgLight/40 px-3 py-1.5 text-xs text-brand-text/80">
          <span className="truncate">
            {t("chat.composer.replyTo", {
              snippet: (replyTo.content ?? "").slice(0, 60),
            })}
          </span>
          <button
            type="button"
            onClick={onCancelReply}
            className="rounded-full p-1 hover:bg-brand-lines/10"
            aria-label={t("chat.composer.cancelReply")}
          >
            <FiX size={12} />
          </button>
        </div>
      )}

      <div className="flex items-end gap-2">
        <textarea
          value={text}
          onChange={(e) => {
            setText(e.target.value);
            notifyTyping();
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              handleSubmit(e);
            }
          }}
          disabled={disabled}
          rows={1}
          placeholder={t("chat.composer.placeholder")}
          className="min-h-[42px] max-h-[160px] flex-1 resize-none rounded-xl border border-brand-lines/25 bg-brand-bgLight/40 px-3 py-2 text-sm text-brand-text placeholder:text-brand-text/40 focus:outline-none focus:border-brand-accent"
        />
        <Button
          type="submit"
          disabled={disabled || !text.trim()}
          leftIcon={<FiSend size={14} />}
        >
          {t("common:send", { defaultValue: "Odeslat" })}
        </Button>
      </div>
    </form>
  );
}
