import { FormEvent, useState, useEffect } from "react";
import { ChatMessage } from "./ChatMessage";
import { useRef } from "react";

export { Chat };

interface Message {
  user: boolean;
  content: string;
}

interface ChatProps {
  assistant: string;
  messages: Message[];
  pushMessage: (message: Message) => void;
  conversationId: string;
  setConversationId: (id: string) => void;
  setAssistantName: (name: string) => void;
  receivingMsg: boolean;
  setReceivingMsg: (receiving: boolean) => void;
  onStartConversation: (user: string, assistant: string) => Promise<string>;
  sendIcon: string;
  userAvatar: string;
  botAvatar: string;
  onFeedback?: (key: string, rating: string) => Promise<void>;
}

function Chat({
  assistant,
  messages,
  pushMessage,
  conversationId,
  setConversationId,
  setAssistantName,
  receivingMsg,
  setReceivingMsg,
  onStartConversation,
  sendIcon,
  userAvatar,
  botAvatar,
  onFeedback
}: ChatProps) {
  const [input, setInput] = useState("");
  const bottomRef = useRef(null);

  async function startConversation() {
    const newId = await onStartConversation("user", assistant);
    setConversationId(newId);
  }

  useEffect(() => {
    setAssistantName(assistant);
    startConversation();
  }, []);

  function changeInput(e: FormEvent<HTMLInputElement>) {
    e.preventDefault();
    setInput(e.currentTarget.value);
  }

  async function clearInput(e: FormEvent) {
    e.preventDefault();

    // Validar que el input no esté vacío
    const trimmedInput = input.trim();
    if (!trimmedInput) {
      return;
    }

    pushMessage({ user: true, content: trimmedInput });
    setInput("");
    pushMessage({ user: false, content: trimmedInput });
  }

  function scrollToBottom() {
    // @ts-expect-error idk
    bottomRef.current.scrollIntoView({ behavior: "smooth" });
  }

  return (
    <div className="flex flex-1 flex-col items-center bg-slate-100 h-screen">
      <div className="mt-5 w-3/5 flex-1 overflow-y-auto scrollbar min-h-0">
        {messages.map((message, index) => (
          <ChatMessage
            key={index}
            isUser={message.user}
            content={message.content}
            event={scrollToBottom}
            conversationId={conversationId}
            setReceivingMsg={setReceivingMsg}
            userAvatar={userAvatar}
            botAvatar={botAvatar}
            onFeedback={onFeedback}
          />
        ))}
        <div ref={bottomRef}></div>
      </div>
      <form
        className="flex-shrink-0 ml-5 my-5 flex w-3/4 items-center justify-center mr-5"
        onSubmit={clearInput}
      >
        <input
          autoFocus
          type="text"
          value={input}
          onChange={changeInput}
          disabled={receivingMsg}
          placeholder="¡Pregúntame algo!"
          className="input input-bordered focus:input-primary w-[90%] p-7 rounded-3xl"
        />
        <button
          type="submit"
          className={`btn-error ml-4 hover:border-red-200 hover:opacity-80 ${
            !input.trim() ? "opacity-50" : ""
          }`}
          disabled={receivingMsg || !input.trim()}
        >
          <img src={sendIcon} alt="Send" className="h-14 w-14" />
        </button>
      </form>
    </div>
  );
}
