import { FormEvent, useEffect, useRef, useState } from "react";
import CloseIcon from "./icons/CloseIcon";
import SendChatIcon from "./icons/SendChatIcon";
import SubtracktIcon from "./icons/SubtracktIcon";
import Button from "./ui/Button";
import { Socket } from "socket.io-client";
import { format } from "date-fns";

interface User {
  id: string;
  name: string;
  isAdmin: boolean;
}

interface Message {
  user: User;
  text: string;
  time: string;
}

interface ChatNewProps {
  isShow: boolean;
  socket: Socket;
  userId: string;
  name: string;
  onClose: () => void;
}

function ChatNew({ isShow, socket, userId, name, onClose }: ChatNewProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [message, setMessage] = useState<string>("");
  const messagesRef = useRef<HTMLDivElement>(null);
  const textRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    console.log("Component ChatNew state isShow: ", isShow);
  }, [isShow]);

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

    if (message) {
      socket?.emit("message", {
        user: { id: userId, name },
        text: message.replace(/\s+/g, " ").trim(),
        time: format(new Date(), "HH:mm"),
      });

      setMessage("");
    }

    textRef.current?.focus();
  }

  useEffect(() => {
    if (!socket) return;

    socket.on("message", (message) =>
      setMessages((prev) => [...prev, message])
    );
  }, [socket]);

  useEffect(() => {
    messagesRef.current?.scrollBy({
      behavior: "smooth",
      top: messagesRef.current?.scrollHeight,
    });
  }, [messages]);

  useEffect(() => {
    console.log("Change isShow", isShow);

    if (isShow) {
      messagesRef.current?.scrollBy({
        behavior: "smooth",
        top: messagesRef.current?.scrollHeight,
      });
      textRef.current?.focus();
    }
  }, [isShow]);

  return (
    // <div className={`max-h-[calc(100vh-48px)]`}>
    //   <div
    //     className={`overflow-y-scroll relative h-full bg-white flex flex-col ${
    //       isShow ? "w-[296px]" : "w-0 hidden"
    //     }`}
    //   >
    //     <div
    //       className={`fixed z-10 top-0 bg-white w-full flex items-center justify-between p-2 pl-4`}
    //     >
    //       <p className="font-semibold">Чат</p>
    //       <div className="flex">
    //         <Button
    //           variant="tertiary"
    //           icon={<CloseIcon />}
    //           onlyIcon
    //           onClick={onClose}
    //         />
    //       </div>
    //     </div>
    //     <div
    //       ref={messagesRef}
    //       className="flex flex-col gap-2 p-4 pt-12 pb-[72px]"
    //     >
    //       {messages.map((message) => (
    //         <div
    //           className={`flex gap-1 items-end ${
    //             message.user.id === userId ? "self-end" : ""
    //           }`}
    //         >
    //           {message.user.id !== userId && (
    //             <div className="">
    //               <div className="h-6 w-6 flex items-center justify-center bg-[#E6ECF2] font-semibold text-[10px] rounded-full">
    //                 {message.user.name[0].toUpperCase()}
    //               </div>
    //             </div>
    //           )}
    //           <div className="relative">
    //             <div
    //               className={`p-2 rounded-tl-[4px] rounded-r-lg flex flex-col gap-1 ${
    //                 message.user.id !== userId ? "bg-[#F0F1F2]" : "bg-[#C4DDF5]"
    //               }`}
    //             >
    //               {message.user.id !== userId && (
    //                 <p className="text-sm text-[#49A1F5] font-semibold">
    //                   {message.user.name}
    //                 </p>
    //               )}
    //               <p
    //                 className="text-sm break-words"
    //                 style={{ wordBreak: "break-word" }}
    //               >
    //                 {message.text}
    //               </p>
    //               <p className="text-xs self-end text-[#767676]">
    //                 {message.time}
    //               </p>
    //             </div>
    //             {message.user.id !== userId && (
    //               <div className="absolute bottom-0 -left-[7px]">
    //                 <SubtracktIcon />
    //               </div>
    //             )}
    //           </div>
    //         </div>
    //       ))}
    //     </div>
    //     <div className="fixed z-10 bottom-0 p-4 bg-white w-full">
    //       <form onSubmit={sendMessage} className="flex gap-3 border-t pt-3">
    //         <input
    //           ref={textRef}
    //           type="text"
    //           placeholder="Напишите сообщение..."
    //           className="outline-none w-full bg-white text-sm"
    //           value={message}
    //           onChange={(e) => setMessage(e.target.value)}
    //         />
    //         <button type="submit" className="text-[#49A1F5]">
    //           <SendChatIcon />
    //         </button>
    //       </form>
    //     </div>
    //   </div>
    // </div>

    <div
      className={`h-full flex flex-col ${
        isShow ? "w-[296px] p-4" : "w-0 overflow-hidden"
      }`}
    >
      <div className="flex justify-between items-center mb-4">
        <p className="font-semibold text-sm">Чат демонстрации</p>
        <Button
          variant="tertiary"
          icon={<CloseIcon />}
          onlyIcon
          onClick={onClose}
        />
      </div>

      <div
        ref={messagesRef}
        className={`border-t border-b border-[#DAE0E5] flex-1 flex flex-col gap-2 overflow-y-scroll overflow-x-hidden py-2 px-1`}
      >
        {messages.map((message, index) => (
          <div
            key={index}
            className={`flex gap-1 items-end ${
              message.user.id === userId ? "self-end" : ""
            }`}
          >
            {message.user.id !== userId && (
              <div className="">
                <div className="h-6 w-6 flex items-center justify-center bg-[#E6ECF2] font-semibold text-[10px] rounded-full">
                  {message.user.name[0].toUpperCase()}
                </div>
              </div>
            )}
            <div className="relative">
              <div
                className={`flex flex-col gap-1 p-2 rounded-t-lg ${
                  message.user.id !== userId
                    ? "rounded-r-lg bg-[#F0F1F2]"
                    : "rounded-l-lg bg-[#C4DDF5]"
                }`}
              >
                {message.user.id !== userId && (
                  <p className="text-sm text-[#49A1F5] font-semibold">
                    {message.user.name}
                  </p>
                )}
                <p
                  className="text-sm break-words"
                  style={{ wordBreak: "break-word" }}
                >
                  {message.text}
                </p>
                <p className="text-xs self-end text-[#767676]">
                  {message.time}
                </p>
              </div>
              {message.user.id !== userId ? (
                <div className="absolute bottom-0 -left-[7px]">
                  <SubtracktIcon />
                </div>
              ) : (
                <div className="absolute bottom-0 -right-[7px]">
                  <svg
                    width="7"
                    height="12"
                    viewBox="0 0 7 12"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M0 0V12H6.75C6.88807 12 7 11.8881 7 11.75C7 11.6119 6.88996 11.4995 6.75615 11.4655C4.98232 11.0143 0 6.18654 0 0Z"
                      fill="#C4DDF5"
                    />
                  </svg>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
      <div className="mt-4">
        <form
          onSubmit={sendMessage}
          className="flex items-center justify-between gap-4"
        >
          <input
            ref={textRef}
            type="text"
            placeholder="Написать сообщение"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            className="bg-white outline-none w-full"
          />
          <button type="submit">
            <SendChatIcon />
          </button>
        </form>
      </div>
    </div>
  );
}

export default ChatNew;
