import { useEffect, useState } from "react";

import Head from "next/head";

import "../styles/globals.scss";

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

import Chatbot from "../chatbot";
import Homepage from "../components/Homepage";
import { handleUppercaseFormatter } from "../utils/handleUppercaseFormatter";

import { lastMessages, otherMessages } from "../services/api";

function Owlchat({
  color,
  base_url,
  wallpaper,
  owner_name,
  initial_message,
  whatsapp_number,
  background_color,
}: ChatbotProps) {
  const [step, setStep] = useState(1);
  const [chatState, setChatState] = useState(false);
  const [audio, setAudio] = useState<HTMLAudioElement>();

  const [userName, setUserName] = useState("");
  const firstName = userName.split(" ")[0];

  const [containerRef, setContainerRef] = useState<HTMLDivElement | null>(null);

  const [deviceModel, setDeviceModel] = useState("");
  const [deviceCompany, setDeviceCompany] = useState("");
  const [deviceProblem, setDeviceProblem] = useState("");
  const [otherMessagesText, setOtherMessagesText] = useState("");

  const [inputValue, setInputValue] = useState("");
  const [firstOptionSelected, setFirstOptionSelected] = useState(0);
  const [othersOptionSelected, setOthersOptionSelected] = useState(0);
  const [deviceCompanyOptionSelected, setDeviceCompanyOptionSelected] =
    useState(0);

  const initialMessages = [
    {
      id: 1,
      text: "Olá, espero que esteja tudo bem com você! Para que nós possamos te ajudar, digite o seu |Nome. 👋",
      user: "BOT",
    },
    {
      id: 2,
      text: `${firstName}| Selecione a opção que melhor descreve seu caso por gentileza.`,
      user: "BOT",
    },
  ];

  const technicalAssitanceMessages = [
    {
      id: 1,
      text: "Anotado ✍️| Para continuarmos nos informe qual é a |Marca| do seu aparelho",
      user: "BOT",
    },
    {
      id: 2,
      text: "Muito bom 🔥| Agora precisamos saber qual é o |Modelo| do seu aparelho",
      user: "BOT",
    },
    {
      id: 3,
      text: `${firstName}| Por último, nos informe qual é o |Tipo de Problema| do seu aparelho. Se possível, detalhe o que está acontecendo.`,
      user: "BOT",
    },
  ];

  function handleChangeStep(step: number) {
    setStep(step);
  }

  function handleChangeUserName(name: string) {
    setUserName(name);
  }

  function handleChangeDeviceCompany(company: string) {
    setDeviceCompany(company);
  }

  function handleChangeDeviceModel(model: string) {
    setDeviceModel(model);
  }

  function handleChangeInputValue(value: string) {
    setInputValue(value);
  }

  function handleChangeDeviceProblem(problem: string) {
    setDeviceProblem(problem);
  }

  function handleChangeOtherMessagesText(text: string) {
    setOtherMessagesText(text);
  }

  function handleSelectFirstOptions(id: number) {
    handleSelectOthersOptions(0);
    handleChangeDeviceModel("");
    handleChangeDeviceCompany("");
    handleChangeDeviceProblem("");
    handleChangeOtherMessagesText("");
    setFirstOptionSelected(id);
    handleChangeStep(3);

    if (step === 2) {
      handleChangeStep(step + 1);
    }
  }

  function handleGetContainerRef(ref: HTMLDivElement) {
    setContainerRef(ref);
  }

  function handleSelectOthersOptions(id: number) {
    handleChangeStep(3);
    setOthersOptionSelected(id);
    setDeviceCompanyOptionSelected(0);
  }

  function handleSelectDeviceCompanyOptions(id: number, company: string) {
    if (step === 3) {
      handleChangeStep(step + 1);
    } else {
      deviceCompanyOptionSelected !== 0 && handleChangeStep(4);
    }
    handleChangeDeviceCompany("");
    handleChangeDeviceModel("");
    handleChangeDeviceProblem("");
    handleChangeDeviceCompany(handleUppercaseFormatter(company));
    setDeviceCompanyOptionSelected(id);
  }

  function handleBackStep() {
    handleChangeStep(step - 1);
    handleChangeInputValue("");

    switch (step) {
      case 2:
        handleChangeUserName("");
        break;
      case 3:
        setFirstOptionSelected(0);
        setOthersOptionSelected(0);
        setDeviceCompanyOptionSelected(0);
        handleChangeOtherMessagesText("");
        break;
      case 4:
        setOthersOptionSelected(0);
        handleChangeDeviceCompany("");
        setDeviceCompanyOptionSelected(0);
        handleChangeOtherMessagesText("");
        break;
      case 5:
        handleChangeDeviceModel("");
        break;
      case 6:
        handleChangeDeviceProblem("");
        break;
      default:
        break;
    }
  }

  function handleSetChatState(state: boolean) {
    setChatState(state);
  }

  useEffect(() => {
    setAudio(new Audio("./audios/pop-up-audio.mp3"));
  }, []);

  useEffect(() => {
    if (!chatState && userName === "") {
      setTimeout(() => {
        audio?.play();
      }, 5000);
    }
  }, [chatState, audio, userName]);

  return (
    <Context.Provider
      value={{
        step,
        chatState,
        inputValue,
        containerRef,

        firstOptionSelected,
        othersOptionSelected,
        deviceCompanyOptionSelected,

        lastMessages,
        otherMessages,
        initialMessages,
        technicalAssitanceMessages,

        userName,
        deviceModel,
        deviceCompany,
        deviceProblem,
        otherMessagesText,

        handleBackStep,

        handleSelectFirstOptions,
        handleSelectOthersOptions,
        handleSelectDeviceCompanyOptions,

        handleChangeStep,
        handleChangeUserName,
        handleChangeInputValue,
        handleChangeDeviceModel,
        handleChangeDeviceCompany,
        handleChangeDeviceProblem,
        handleChangeOtherMessagesText,

        handleGetContainerRef,

        handleSetChatState,
      }}
    >
      <Head>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
        />
      </Head>
      <Chatbot
        color={color}
        base_url={base_url}
        wallpaper={wallpaper}
        owner_name={owner_name}
        whatsapp_number={whatsapp_number}
        initial_message={initial_message}
        background_color={background_color}
      />
    </Context.Provider>
  );
}

export default Owlchat;
