import { cadastrarNovoContato } from "@/requests/CRUD/Cliente/cadastroCliente";
import { cadastrarColetaDados } from "@/requests/CRUD/ColetaDados/cadastroColetaDados";
import {
  listarPerfil,
  listarTodosCargos,
} from "@/requests/CRUD/Perfil/listarPerfil";
import { useSocketContext } from "@/src/contexts/SocketContext";
import { useAuth } from "@/src/contexts/authContext";
import { useKanbanContext } from "@/src/contexts/kanbanContext";
import { GetForm } from "@/utils";
import Box from "@mui/material/Box";
import SpeedDial from "@mui/material/SpeedDial";
import SpeedDialAction from "@mui/material/SpeedDialAction";
import SpeedDialIcon from "@mui/material/SpeedDialIcon";
import { toast } from "react-toastify";

import { listarUsuarioPeloId } from "@/requests/CRUD/Usuario/listarUsuarios";
import {
  Building2,
  CalendarPlus,
  EditIcon,
  Trash,
  UserPlus,
} from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import * as yup from "yup";
import NewDateScheduler from "../../pages/CXESCRM003/modalNewDateScheduler";
import Button from "../Forms/Button";
import ModalComponente from "../Modal/ModalComponente";
import ModalLixeira from "./ModalLiexeira.tsx";
import NewBusiness from "./modalNewBusiness";
import NewContactScheduler from "./modalNewContactScheduler";

const pagesOcultar = ["/CXESCRM005"];

export default function OpenIconSpeedDial({ opened }: any) {
  const router = useRouter();
  const pathname = usePathname();
  const { notificarNotificacao } = useSocketContext();

  const { valuesSession } = useAuth();
  const { session } = valuesSession();

  const [isLoading, setIsLoading] = useState(false);
  const [openModal, setOpenModal] = useState(false);
  const [isLoadingBussines, setIsLoadingBussines] = useState(false);
  const [modalType, setModalType] = useState("");
  const [vendedor, setVendedor] = useState(null);

  const [actions, setActions] = useState([
    {
      icon: <UserPlus size={20} />,
      name: "Novo Contato",
    },
    {
      icon: <Building2 size={20} />,
      name: "Novo Negócio",
    },
    { icon: <CalendarPlus />, name: "Novo Agendamento" },
  ]);

  const { listarDadosKanban } = useKanbanContext();

  useEffect(() => {
    listarPerfil(session.perfil_usuario).then((res) => {
      if (res.permite_lixeira_perfil == "1") {
        setActions((prev) => [...prev, { icon: <Trash />, name: "Lixeira" }]);
      }
    });
    listarTodosCargos().then((res) => {
      const Vendedor = res.find((cargo: any) => cargo.vendedor_cargo == 1);
      listarUsuarioPeloId(session.id_usuario).then((user) => {
        if (user.cargo_perfil == Vendedor.id_cargo) {
          setVendedor(user.id_usuario);
        }
      });
    });
  }, []);

  const [eventSchema, setEventSchema] = useState<
    yup.ObjectSchema<{}, yup.AnyObject, {}, "">
  >(yup.object().shape({}));
  const { ...formEvent } = GetForm(eventSchema, setEventSchema);

  const [contactSchema, setContactSchema] = useState<
    yup.ObjectSchema<{}, yup.AnyObject, {}, "">
  >(yup.object().shape({}));
  const [businessSchema, setBusinessSchema] = useState<
    yup.ObjectSchema<{}, yup.AnyObject, {}, "">
  >(yup.object().shape({}));
  const { ...formContact } = GetForm(contactSchema, setContactSchema);
  const { ...formBusiness } = GetForm(businessSchema, setBusinessSchema);

  const handleOpenModal = (info: any) => {
    setModalType(info);
    setOpenModal(true);
  };

  const handleContact = (data: any) => {
    setIsLoading(true);

    cadastrarNovoContato({
      ...data,
      cadastrarColetaDados: true,
      vendedor_coleta: vendedor,
    })
      .then((res) => {
        setOpenModal(false);
        listarDadosKanban();
      })
      .finally(() => setIsLoading(false));
  };

  const handleEvent = (data: any) => {
    // cadastrarTarefa(data);
    notificarNotificacao();
  };
  const handleRegisterBusiness = (data: any) => {
    setIsLoadingBussines(true);
    const dados = {
      id_usuario: session.id_usuario,
      id_vendedor: data.vendedor_negocio || vendedor,
      nome_negocio: data.nome_negocio,
      uc_cliente: data.uc_negocio,
      perfil_consumo_coleta: data.perfil_consumo_coleta,
      obsColeta: data.obs_negocio,
      idCliente: data.cliente,
    };
    cadastrarColetaDados(dados).then(() => {
      setIsLoadingBussines(false);
      toast.success("Negócio cadastrado com sucesso!");
      setOpenModal(false);
      listarDadosKanban();
    });
  };
  useEffect(() => {
    handleStyleDivSpeed(0);
  }, []);
  const handleStyleDivSpeed = (func: any) => {
    const classSpeedDiv = document.getElementById(
      "SpeedDialopenIconexample-actions"
    ) as any;
    if (classSpeedDiv) {
      // Iterate through each element and set display to "none"
      Array.from(classSpeedDiv.children).forEach((element: any) => {
        element.style.display = func == 0 ? "none" : "flex";
      });
    } else {
      console.error("Element not found");
    }
  };
  return (
    <Box
      sx={{
        height: "fit-content",
        width: "fit-content",
        transform: "translateZ(0px)",
        flexGrow: 1,
        position: "fixed",
        bottom: 10,
        right: 30,
        // display: "none",
        display: pagesOcultar.includes(pathname!) ? "none" : "flex",
      }}
    >
      <SpeedDial
        ariaLabel="SpeedDial openIcon example"
        sx={{
          bottom: 16,
          right: -10,
          zIndex: "999999999999999999",
          color: "#43b4db",
        }}
        onOpen={() => {
          handleStyleDivSpeed(1);
        }}
        onClose={() => {
          handleStyleDivSpeed(0);
        }}
        icon={<SpeedDialIcon openIcon={<EditIcon />} />}
      >
        {actions.map((action, index) => (
          <SpeedDialAction
            key={index}
            icon={action.icon}
            className="dark:bg-form-input dark:text-white dark:hover:bg-form-strokedark"
            onClick={() => handleOpenModal(action.name)}
            tooltipTitle={action.name}
          />
        ))}
      </SpeedDial>

      {modalType === "Nova Tarefa" && (
        <ModalComponente
          size="md"
          saved={formEvent.handleSubmit(handleEvent)}
          opened={openModal}
          onClose={() => setOpenModal(false)}
          header="Novo Agendamento"
        >
          <NewDateScheduler form={formEvent} />
        </ModalComponente>
      )}
      {modalType === "Novo Negócio" && (
        <ModalComponente
          size="md"
          hasForm={false}
          // saved={formBusiness.handleSubmit(handleRegisterBusiness)}
          header="Cadastrar Novo Negócio"
          opened={openModal}
          onClose={() => setOpenModal(false)}
          hasSaveButton={false}
        >
          <NewBusiness
            hasGerarProposta={true}
            onSubmitFunction={handleRegisterBusiness}
            vendedor={vendedor}
          >
            {" "}
            <Button
              className="text-sm px-6 rounded-lg"
              loading={isLoadingBussines}
            >
              Salvar
            </Button>
          </NewBusiness>
        </ModalComponente>
      )}
      {modalType === "Novo Contato" && (
        <ModalComponente
          hasForm={false}
          // saved={formContact.handleSubmit(handleContact)}
          header="Cadastrar Novo Contato"
          opened={openModal}
          onClose={() => setOpenModal(false)}
          hasSaveButton={false}
        >
          <NewContactScheduler
            hasGerarProposta={true}
            onSubmitFunction={handleContact}
            hasDataNegocio={true}
            dadosExtras={false}
          >
            <Button loading={isLoading} className="text-sm px-6 rounded-lg">
              Salvar
            </Button>
          </NewContactScheduler>
        </ModalComponente>
      )}
      {modalType === "Lixeira" && (
        <ModalComponente
          // size="md"
          // className="w-130"
          hasForm={false}
          header="Arquivos da Lixeira"
          opened={openModal}
          onClose={() => setOpenModal(false)}
          hasSaveButton={false}
        >
          <ModalLixeira />
        </ModalComponente>
      )}
    </Box>
  );
}
