/* eslint-disable react-hooks/exhaustive-deps */
import React, { useContext, useEffect } from "react";

import dynamic from "next/dynamic";

const Input = dynamic(() => import("../Input"));
const Button = dynamic(() => import("../Button"));

import { BodyProps, Context } from "../../contexts/Context";

import styles from "./Body.module.scss";

import { FiSend } from "react-icons/fi";
import { deviceCompanyOptions, firstOptions, otherOptions } from "../../services/api";

export default function Body({
  color,
  baseUrl,
  ownerName,
  whatsappNumber,
  backgroundColor,
}: BodyProps) {
  const containerRef = React.useRef<HTMLDivElement>(null);

  const {
    step,
    userName,
    inputValue,
    deviceModel,
    lastMessages,
    deviceCompany,
    deviceProblem,
    otherMessages,
    initialMessages,
    otherMessagesText,
    firstOptionSelected,
    othersOptionSelected,
    technicalAssitanceMessages,
    deviceCompanyOptionSelected,
    handleGetContainerRef,
    handleSelectFirstOptions,
    handleSelectOthersOptions,
    handleSelectDeviceCompanyOptions,
  } = useContext(Context);

  const technicalAssistanceWhatsappMessage = `https://wa.me/${whatsappNumber}?text=Olá,%0D%0AEstou precisando de ajuda referente à:%0D%0A*Assistência Técnica*.%0D%0A%0D%0A*Minhas informações*%0D%0A Nome: ${userName}%0D%0A Marca: ${deviceCompany}%0D%0A Modelo: ${deviceModel}%0D%0A Problema: ${deviceProblem}%0D%0A%0D%0A- Não se preocupe, em breve um de nossos colaboradores irá te atender.%0D%0A%0D%0AMensagem gerada automaticamente através de:%0D%0A${baseUrl}%0D%0A${new Date().toLocaleString()}
  `;

  const othersWhatsappMessage = `https://wa.me/${whatsappNumber}?text=Olá,%0D%0AEstou precisando de ajuda referente à:%0D%0A*Outros*.%0D%0A%0D%0A*Minhas informações*%0D%0A Nome: ${userName}%0D%0A Assunto: ${otherMessagesText}%0D%0A%0D%0A- Não se preocupe, em breve um de nossos colaboradores irá te atender.%0D%0A%0D%0AMensagem gerada automaticamente através de:%0D%0A${baseUrl}%0D%0A${new Date().toLocaleString()}
  `;

  useEffect(() => {
    handleGetContainerRef(containerRef as any);
  }, [containerRef]);

  return (
    <div className={styles.container} ref={containerRef}>
      {initialMessages?.slice(0, 1).map((message) => {
        return (
          <div className={styles.bot} key={message.id}>
            <div>
              <span>{message.text.split("|")[0]}</span>
              <span style={{ fontWeight: 600 }}>
                {message.text.split("|")[1]}
              </span>
            </div>
            <label>{ownerName}</label>
          </div>
        );
      })}
      {userName && (
        <div className={styles.user}>
          <Input
            color={color}
            name="user_name"
            placeholder="Ex: Hugo"
            backgroundColor={backgroundColor}
            value={userName || inputValue}
          />
          <label>Você</label>
        </div>
      )}

      {initialMessages?.slice(1, step).map((message) => {
        return (
          <div className={styles.bot} key={message.id}>
            <div>
              <p style={{ fontWeight: 600 }}>{message.text.split("|")[0]},</p>
              <p>{message.text.split("|")[1]}</p>
            </div>
            <label>{ownerName}</label>
          </div>
        );
      })}
      {step >= 2 && (
        <div className={styles.user}>
          <div className={styles.options}>
            {firstOptions.map((option) => {
              return (
                <Button
                  name={option.name}
                  type="button"
                  onClick={() => handleSelectFirstOptions(option.id)}
                  key={option.id}
                  style={{
                    background:
                      option.id === firstOptionSelected
                        ? backgroundColor
                        : "transparent",
                    color: option.id === firstOptionSelected ? color : "",
                    boxShadow: option.id === firstOptionSelected ? "" : "none",
                    border: `1px solid ${color}`,
                  }}
                >
                  {option.text}
                </Button>
              );
            })}
            <label>Você</label>
          </div>
        </div>
      )}
      {firstOptionSelected === 1 && (
        <>
          {step >= 3 && (
            <>
              {technicalAssitanceMessages?.slice(0, 1).map((message) => {
                return (
                  <div className={styles.bot} key={message.id}>
                    <div>
                      <p>{message.text.split("|")[0]}</p>
                      <span>{message.text.split("|")[1]}</span>
                      <span style={{ fontWeight: 600 }}>
                        {message.text.split("|")[2]}
                      </span>
                      <span>{message.text.split("|")[3]}</span>
                    </div>
                    <label>{ownerName}</label>
                  </div>
                );
              })}
              <div className={styles.user}>
                <div className={styles.deviceOptions}>
                  {deviceCompanyOptions.map((option) => {
                    return (
                      <Button
                        name={option.name}
                        type="button"
                        onClick={() =>
                          handleSelectDeviceCompanyOptions(
                            option.id,
                            option.text
                          )
                        }
                        key={option.id}
                        style={{
                          background:
                            option.id === deviceCompanyOptionSelected
                              ? backgroundColor
                              : "transparent",
                          color:
                            option.id === deviceCompanyOptionSelected
                              ? color
                              : "",
                          boxShadow:
                            option.id === deviceCompanyOptionSelected
                              ? ""
                              : "none",
                          border: `1px solid ${color}`,
                        }}
                      >
                        {option.text}
                      </Button>
                    );
                  })}
                  <label>Você</label>
                </div>
              </div>
            </>
          )}
          {step >= 4 && deviceCompanyOptionSelected !== 0 && (
            <>
              {technicalAssitanceMessages?.slice(1, 2).map((message) => {
                return (
                  <div className={styles.bot} key={message.id}>
                    <div>
                      <p>{message.text.split("|")[0]}</p>
                      <span>{message.text.split("|")[1]}</span>
                      <span style={{ fontWeight: 600 }}>
                        {message.text.split("|")[2]}
                      </span>
                      <span>{message.text.split("|")[3]}</span>
                    </div>
                    <label>{ownerName}</label>
                  </div>
                );
              })}
              {deviceModel && (
                <div className={styles.user}>
                  <Input
                    color={color}
                    name="deviceModel"
                    placeholder="Ex: iPhone 12"
                    backgroundColor={backgroundColor}
                    value={deviceModel || inputValue}
                  />
                  <label>Você</label>
                </div>
              )}
            </>
          )}
          {step >= 5 && deviceModel && deviceCompanyOptionSelected && (
            <>
              {technicalAssitanceMessages?.slice(2, 3).map((message) => {
                return (
                  <div className={styles.bot} key={message.id}>
                    <div>
                      <p style={{ fontWeight: 600 }}>
                        {message.text.split("|")[0]},
                      </p>
                      <span>{message.text.split("|")[1]}</span>
                      <span style={{ fontWeight: 600 }}>
                        {message.text.split("|")[2]}
                      </span>
                      <span>{message.text.split("|")[3]}</span>
                    </div>
                    <label>{ownerName}</label>
                  </div>
                );
              })}
              {deviceProblem && (
                <div className={styles.user}>
                  <Input
                    color={color}
                    name="deviceProblem"
                    placeholder="Ex: Tela quebrada"
                    backgroundColor={backgroundColor}
                    value={deviceProblem || inputValue}
                  />
                  <label>Você</label>
                </div>
              )}
            </>
          )}
          {step >= 6 && deviceProblem && deviceModel && (
            <>
              <div className={styles.bot}>
                <div>
                  <p style={{ fontWeight: 600 }}>
                    {lastMessages.text.split("|")[0]}
                  </p>
                  <p>{lastMessages.text.split("|")[1]}</p>
                </div>
                <label>{ownerName}</label>
              </div>
              <div className={styles.send}>
                <a
                  target="_blank"
                  href={technicalAssistanceWhatsappMessage}
                  rel="noopener noreferrer"
                >
                  <Button style={{ backgroundColor: backgroundColor }}>
                    Enviar Informações <FiSend />
                  </Button>
                </a>
              </div>
            </>
          )}
        </>
      )}
      {firstOptionSelected === 2 && (
        <>
          {step >= 2 && (
            <>
              {otherMessages?.slice(0, 1).map((message) => {
                return (
                  <div className={styles.bot} key={message.id}>
                    <p>{message.text}</p>
                    <label>{ownerName}</label>
                  </div>
                );
              })}
              <div className={styles.user}>
                <div className={styles.options}>
                  {otherOptions.map((option) => {
                    return (
                      <Button
                        name={option.name}
                        type="button"
                        onClick={() => handleSelectOthersOptions(option.id)}
                        key={option.id}
                        style={{
                          background:
                            option.id === othersOptionSelected
                              ? backgroundColor
                              : "transparent",
                          color:
                            option.id === othersOptionSelected ? color : "",
                          boxShadow:
                            option.id === othersOptionSelected ? "" : "none",
                          border: `1px solid ${color}`,
                        }}
                      >
                        {option.text}
                      </Button>
                    );
                  })}
                  <label>Você</label>
                </div>
              </div>
            </>
          )}
          {step >= 3 &&
            othersOptionSelected === 3 &&
            otherMessages?.slice(1, 2).map((message) => {
              return (
                <div className={styles.bot} key={message.id}>
                  <p>
                    {message.text.split("|").map((item) => {
                      return <p key={item}>🗓️{item}</p>;
                    })}
                  </p>
                  <label>{ownerName}</label>
                </div>
              );
            })}
          {step >= 3 &&
            othersOptionSelected === 4 &&
            otherMessages?.slice(2, 3).map((message) => {
              return (
                <div className={styles.bot} key={message.id}>
                  <div>
                    <p>{message.text.split("|")[0]}:</p>
                    <br />
                    {message.text
                      .split("|")
                      ?.slice(1)
                      .map((item) => {
                        return (
                          <p key={item} style={{ fontWeight: 600 }}>
                            - {item}
                          </p>
                        );
                      })}
                  </div>
                  <label>{ownerName}</label>
                </div>
              );
            })}
          {step >= 3 && othersOptionSelected === 5 && (
            <>
              {otherMessages?.slice(3, 4).map((message) => {
                return (
                  <div className={styles.bot} key={message.id}>
                    <div>
                      <p>{message.text}</p>
                    </div>
                    <label>{ownerName}</label>
                  </div>
                );
              })}
              {otherMessagesText && (
                <div className={styles.user}>
                  <Input
                    color={color}
                    name="otherMessagesText"
                    placeholder="Ex: Quero ser revendedor"
                    backgroundColor={backgroundColor}
                    value={otherMessagesText || inputValue}
                  />
                  <label>Você</label>
                </div>
              )}
            </>
          )}
          {step >= 4 && otherMessagesText && (
            <>
              <div className={styles.bot}>
                <div>
                  <p style={{ fontWeight: 600 }}>
                    {lastMessages.text.split("|")[0]}
                  </p>
                  <p>{lastMessages.text.split("|")[1]}</p>
                </div>
                <label>{ownerName}</label>
              </div>
              <div className={styles.send}>
                <a
                  target="_blank"
                  href={othersWhatsappMessage}
                  rel="noopener noreferrer"
                >
                  <Button style={{ backgroundColor: backgroundColor }}>
                    Enviar Informações <FiSend />
                  </Button>
                </a>
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}
