import { useNotifications } from "@/hooks/useNotifications";
import { editarNotificacao } from "@/requests/CRUD/Notificacoes/editarNotificacao";
import { listarAcoesNotificacoes } from "@/requests/CRUD/Notificacoes/listarNotificacoes";
import { listarContatos } from "@/requests/CRUD/Cliente/listarClientes";
import { useColorContext } from "@/src/contexts/ColorContext";
import { useScreenContext } from "@/src/contexts/ScreenContext";
import { Notification } from "@/src/contexts/SocketContext";
import { useAuth } from "@/src/contexts/authContext";
import { Desc_TipoTarefa, Desc_Urgencia, TipoTarefa, Urgencia, getOptionsFromEnum } from "@/enums/enums";
import { DateRangePicker } from "@/components/dateRangePicker";
import { DateRange } from "react-day-picker";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { BsSearch, BsSliders, BsX } from "react-icons/bs";
import { toast } from "react-toastify";

const CampoDetalhe = ({ label, value }: { label: string; value?: any }) =>
  value ? (
    <div className="flex flex-col">
      <span className="text-[11px] uppercase tracking-wide text-body-color">
        {label}
      </span>
      <span className="text-sm text-black dark:text-white">{value}</span>
    </div>
  ) : null;

const NotificationsPage = () => {
  const router = useRouter();

  const { colorMode } = useColorContext();
  const { isMobile } = useScreenContext();
  const { usuario } = useAuth();
  const { notifications, setNotifications, filtros, setFiltros } =
    useNotifications();

  const [filteredNotifications, setFilteredNotifications] =
    useState<any[]>(notifications);
  const [searchInputText, setSearchInputText] = useState("");

  const [selectedNotification, setSelectedNotification] = useState<Notification | any
  >();

  const [filtrosAbertos, setFiltrosAbertos] = useState(false);
  const [acoesDisponiveis, setAcoesDisponiveis] = useState<any[]>([]);
  const [clientesDisponiveis, setClientesDisponiveis] = useState<any[]>([]);
  const [rascunhoFiltros, setRascunhoFiltros] = useState<typeof filtros>({});
  const [periodo, setPeriodo] = useState<DateRange | string | undefined>("*");

  const toYMD = (d?: Date) =>
    d
      ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
        d.getDate()
      ).padStart(2, "0")}`
      : "";

  const optionsUrgencia = getOptionsFromEnum(Urgencia, Desc_Urgencia);
  const optionsTipoAgendamento = getOptionsFromEnum(TipoTarefa, Desc_TipoTarefa);

  useEffect(() => {
    listarAcoesNotificacoes().then(setAcoesDisponiveis);
    if (usuario?.id_usuario) {
      listarContatos({ id_usuario: usuario.id_usuario }).then(
        setClientesDisponiveis
      );
    }
  }, [usuario?.id_usuario]);

  const aplicarFiltros = () => {
    setFiltros(rascunhoFiltros);
    setFiltrosAbertos(false);
  };

  const limparFiltros = () => {
    setRascunhoFiltros({});
    setPeriodo("*");
    setFiltros({});
    setFiltrosAbertos(false);
  };

  const quantidadeFiltrosAtivos = Object.values(filtros || {}).filter(
    (valor) => (Array.isArray(valor) ? valor.length > 0 : !!valor)
  ).length;

  useEffect(() => {
    if (isMobile) {
      toast.info("Para melhor visualização gire o seu celular");
    }
  }, []);

  function formatarHorario(dataHora: string) {
    try {
      let [data, hora] = dataHora.split(" ");

      const horaArr = hora.split(":");
      let horario = "";

      if (+horaArr[0] > 12) {
        horario = +horaArr[0] - 12 + ":" + horaArr[1] + " PM";
      } else {
        horario = +horaArr[0] + ":" + horaArr[1] + " AM";
      }
      return `${data.split("-").reverse().join("/")} ${horario}`;
    } catch (error) {
      return dataHora;
    }
  }

  function expandNotification(notification: Notification) {
    setSelectedNotification(notification);
    const index = notifications.findIndex(
      (e: Notification) => e?.id == notification?.id
    );
    if (notification && notification?.id) {
      setNotifications((prev) => {
        prev.splice(index, 1, {
          ...notification,
          status_notificacao: "lida",
        });
        return prev;
      });
    }
    if (notification && notification?.status_notificacao != "lida") {
      editarNotificacao({
        id: notification.id,
        status_notificacao: "lida",
      });
    }
  }

  useEffect(() => {
    expandNotification(
      notifications.find(
        (notification) => notification.id_notificacao == router.query.id
      ) as Notification
    );
  }, [router]);

  useEffect(() => {
    setFilteredNotifications(notifications);
  }, [notifications]);

  return (
    <div
      id="notificationsMain"
      className="flex flex-row flex-nowrap h-[92vh] min-w-[690px] overflow-hidden rounded-lg border border-stroke bg-white shadow-sm dark:border-strokedark dark:bg-boxdark"
    >
      {/* Coluna da lista */}
      <div
        id="notificationsPreviewSection"
        className="flex h-full w-[380px] flex-shrink-0 flex-col border-r border-stroke dark:border-strokedark"
      >
        <header
          id="notificationsPreviewSectionHeader"
          className="flex h-14 items-center justify-between border-b border-stroke px-4 dark:border-strokedark"
        >
          <span className="text-sm font-semibold text-black dark:text-white">
            Notificações
          </span>
          <img
            src={
              colorMode == "light"
                ? "/images/logo/backgorundLinksunBlack.png"
                : "/images/logo/backgorundLinksun.png"
            }
            alt="Linksun"
            className="h-6 w-6 opacity-60"
          />
        </header>

        <div
          id="searchNotificationArea"
          className="flex items-center gap-2 border-b border-stroke px-3 py-2.5 dark:border-strokedark"
        >
          <div id="searchNotification" className="relative flex-1">
            <BsSearch
              id="searchNotificationIcon"
              className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-body-color"
              size={13}
            />
            <input
              id="notificationInputFilter"
              placeholder="Pesquisar notificação"
              className="h-8 w-full rounded-md border border-stroke bg-transparent pl-8 pr-3 text-sm text-black outline-none transition-colors placeholder:text-body-color focus:border-primary dark:border-strokedark dark:text-white"
              onInput={(e: any) =>
                setSearchInputText(e.target.value.toLowerCase())
              }
            />
          </div>
          <button
            type="button"
            title="Filtros"
            onClick={() => {
              setRascunhoFiltros(filtros);
              setFiltrosAbertos((prev) => !prev);
            }}
            className={`relative flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border transition-colors ${filtrosAbertos
              ? "border-primary text-primary"
              : "border-stroke text-body-color hover:border-primary hover:text-primary dark:border-strokedark"
              }`}
          >
            <BsSliders size={14} />
            {quantidadeFiltrosAtivos > 0 && (
              <span className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-white">
                {quantidadeFiltrosAtivos}
              </span>
            )}
          </button>
        </div>

        {filtrosAbertos && (
          <div
            id="notificationFiltersPanel"
            className="flex max-h-[45vh] flex-col gap-3 overflow-y-auto border-b border-stroke bg-gray px-3 py-3 dark:border-strokedark dark:bg-meta-4"
          >
            <div className="flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wide text-body-color">
                Filtros
              </span>
              <button
                type="button"
                onClick={() => setFiltrosAbertos(false)}
                className="text-body-color hover:text-black dark:hover:text-white"
              >
                <BsX size={16} />
              </button>
            </div>

            <div className="flex flex-col gap-1">
              <label className="text-xs text-body-color">Período</label>
              <DateRangePicker
                value={periodo}
                onChange={(range) => {
                  if (!range || (range as any) === "*") {
                    setPeriodo("*");
                    setRascunhoFiltros((prev) => ({
                      ...prev,
                      data_inicio: "",
                      data_fim: "",
                    }));
                  } else {
                    setPeriodo(range);
                    setRascunhoFiltros((prev) => ({
                      ...prev,
                      data_inicio: toYMD(range.from),
                      data_fim: toYMD(range.to),
                    }));
                  }
                }}
              />
            </div>

            <div className="flex flex-col gap-1">
              <label className="text-xs text-body-color">Status</label>
              <select
                className="rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                value={rascunhoFiltros.status ?? ""}
                onChange={(e) =>
                  setRascunhoFiltros((prev) => ({
                    ...prev,
                    status: e.target.value,
                  }))
                }
              >
                <option value="">Todas</option>
                <option value="não lida">Não lidas</option>
                <option value="lida">Lidas</option>
              </select>
            </div>

            <div className="flex flex-col gap-1">
              <div className="flex items-center justify-between">
                <label className="text-xs text-body-color">Ação</label>
                <button
                  type="button"
                  className="text-xs font-medium text-primary hover:underline"
                  onClick={() =>
                    setRascunhoFiltros((prev) => ({ ...prev, acao: [] }))
                  }
                >
                  Selecionar todas
                </button>
              </div>
              <select
                multiple
                className="h-20 rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                value={rascunhoFiltros.acao || []}
                onChange={(e) => {
                  const selecionadas = Array.from(
                    e.target.selectedOptions
                  ).map((opt) => opt.value);
                  setRascunhoFiltros((prev) => ({
                    ...prev,
                    acao: selecionadas,
                  }));
                }}
              >
                {acoesDisponiveis.map((acao: any) => (
                  <option
                    key={acao.id_acao_notificacao}
                    value={acao.nome_acao_notificacao}
                  >
                    {acao.nome_acao_notificacao}
                  </option>
                ))}
              </select>
            </div>

            <div className="grid grid-cols-2 gap-2">
              <div className="flex flex-col gap-1">
                <label className="text-xs text-body-color">Negócio de</label>
                <input
                  type="number"
                  className="rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                  value={rascunhoFiltros.negocio_de ?? ""}
                  onChange={(e) =>
                    setRascunhoFiltros((prev) => ({
                      ...prev,
                      negocio_de: e.target.value,
                    }))
                  }
                />
              </div>
              <div className="flex flex-col gap-1">
                <label className="text-xs text-body-color">Até</label>
                <input
                  type="number"
                  className="rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                  value={rascunhoFiltros.negocio_ate ?? ""}
                  onChange={(e) =>
                    setRascunhoFiltros((prev) => ({
                      ...prev,
                      negocio_ate: e.target.value,
                    }))
                  }
                />
              </div>
            </div>

            <div className="flex flex-col gap-1">
              <label className="text-xs text-body-color">Urgência</label>
              <select
                className="rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                value={rascunhoFiltros.urgencia ?? ""}
                onChange={(e) =>
                  setRascunhoFiltros((prev) => ({
                    ...prev,
                    urgencia: e.target.value,
                  }))
                }
              >
                <option value="">Todas</option>
                {optionsUrgencia.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex flex-col gap-1">
              <label className="text-xs text-body-color">
                Tipo de agendamento
              </label>
              <select
                className="rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                value={rascunhoFiltros.tipo_agendamento ?? ""}
                onChange={(e) =>
                  setRascunhoFiltros((prev) => ({
                    ...prev,
                    tipo_agendamento: e.target.value,
                  }))
                }
              >
                <option value="">Todos</option>
                {optionsTipoAgendamento.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex flex-col gap-1">
              <label className="text-xs text-body-color">Cliente</label>
              <select
                className="rounded-md border border-stroke bg-white p-1.5 text-sm text-black dark:border-strokedark dark:bg-form-input dark:text-white"
                value={rascunhoFiltros.cliente ?? ""}
                onChange={(e) =>
                  setRascunhoFiltros((prev) => ({
                    ...prev,
                    cliente: e.target.value,
                  }))
                }
              >
                <option value="">Todos</option>
                {clientesDisponiveis.map((cliente: any) => (
                  <option key={cliente.id_cliente} value={cliente.id_cliente}>
                    {cliente.nome_cliente}
                  </option>
                ))}
              </select>
            </div>

            <div className="mt-1 flex justify-end gap-2 border-t border-stroke pt-3 dark:border-strokedark">
              <button
                type="button"
                onClick={limparFiltros}
                className="rounded-md px-3 py-1.5 text-sm text-body-color hover:bg-black-2 hover:bg-opacity-10"
              >
                Limpar
              </button>
              <button
                type="button"
                onClick={aplicarFiltros}
                className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-white hover:opacity-90"
              >
                Aplicar filtros
              </button>
            </div>
          </div>
        )}

        <div id="notificationsDataMain" className="flex-1 overflow-y-auto">
          <ul id="notificationDataArea" className="flex flex-col">
            {filteredNotifications
              .filter((notification) => {
                if (searchInputText != "") {
                  return (
                    notification.tipo_notificacao
                      ?.toLowerCase()
                      .includes(searchInputText.trim()) ||
                    notification.titulo_notificacao
                      ?.toLowerCase()
                      .includes(searchInputText.trim()) ||
                    notification.conteudo_notificacao
                      ?.toLowerCase()
                      .includes(searchInputText.trim())
                  );
                } else {
                  return true;
                }
              })
              .map((notification, index) => {
                const isSelected = selectedNotification?.id == notification?.id;
                const isUnread = notification.status_notificacao == "não lida";

                return (
                  <li
                    key={index}
                    className={`notificationDataPreviewMain relative cursor-pointer border-b border-stroke last:border-b-0 transition-colors dark:border-strokedark ${isSelected
                      ? "bg-black-2 bg-opacity-[0.06]"
                      : "hover:bg-black-2 hover:bg-opacity-[0.04]"
                      }`}
                    onClick={() => expandNotification(notification)}
                  >
                    {isSelected && (
                      <span className="absolute left-0 top-0 h-full w-0.5 bg-primary" />
                    )}
                    <div className="flex items-start gap-3 px-4 py-3">
                      <span
                        className={`mt-1.5 h-1.5 w-1.5 flex-shrink-0 rounded-full ${isUnread ? "bg-primary" : "bg-transparent"
                          }`}
                      />
                      <div className="min-w-0 flex-1">
                        <div className="flex items-baseline justify-between gap-2">
                          <h5
                            className={`truncate text-sm ${isUnread
                              ? "font-semibold text-black dark:text-white"
                              : "font-medium text-black dark:text-white"
                              }`}
                          >
                            {notification.titulo_notificacao}
                          </h5>
                          <span className="flex-shrink-0 text-[11px] text-body-color">
                            {formatarHorario(
                              notification.data_hora_criacao_formatada ||
                              notification.data_hora_criacao
                            )}
                          </span>
                        </div>
                        <p className="mt-0.5 line-clamp-2 text-sm text-body-color">
                          {notification.conteudo_notificacao}
                        </p>
                        <div className="mt-1 flex flex-wrap items-center gap-1.5">
                          {notification.tipo_notificacao && (
                            <span className="rounded bg-black-2 bg-opacity-[0.06] px-1.5 py-0.5 text-[10px] text-body-color dark:bg-white dark:bg-opacity-10">
                              {notification.tipo_notificacao}
                            </span>
                          )}
                          {notification.nome_cliente && (
                            <span className="truncate text-[10px] text-body-color">
                              {notification.nome_cliente}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  </li>
                );
              })}

            {filteredNotifications.length === 0 && (
              <li className="px-4 py-10 text-center text-sm text-body-color">
                Nenhuma notificação encontrada
              </li>
            )}
          </ul>
        </div>
      </div>

      {/* Coluna de leitura */}
      <div className="notificationsMainSection flex h-full w-full flex-col">
        {selectedNotification && selectedNotification?.id ? (
          <>
            <header className="flex h-14 flex-shrink-0 items-center gap-3 border-b border-stroke px-5 dark:border-strokedark">
              <span className="h-1.5 w-1.5 rounded-full bg-success" />
              <h4 className="text-sm font-semibold text-black dark:text-white">
                {selectedNotification.tipo_notificacao}
              </h4>
            </header>

            <div className="flex-1 overflow-y-auto px-6 py-6">
              <div className="mx-auto flex max-w-xl flex-col rounded-lg border border-stroke bg-white p-5 dark:border-strokedark dark:bg-[rgb(28,36,52)]">
                <h5 className="text-base font-semibold text-black dark:text-white">
                  {selectedNotification.titulo_notificacao}
                </h5>
                <p className="mt-2 text-sm leading-relaxed text-body-color">
                  {selectedNotification.conteudo_notificacao}
                </p>

                <div className="mt-4 grid grid-cols-2 gap-x-6 gap-y-3 border-t border-stroke pt-4 dark:border-strokedark">
                  <CampoDetalhe
                    label="Status"
                    value={
                      selectedNotification.status_notificacao === "lida"
                        ? "Lida"
                        : "Não lida"
                    }
                  />
                  <CampoDetalhe
                    label="Ação"
                    value={selectedNotification.tipo_notificacao}
                  />
                  <CampoDetalhe
                    label="Projeto"
                    value={[
                      selectedNotification.id_negocio,
                      selectedNotification.nome_negocio_coleta,
                    ]
                      .filter(Boolean)
                      .join(" - ")}
                  />
                  <CampoDetalhe
                    label="Cliente"
                    value={selectedNotification.nome_cliente}
                  />
                  <CampoDetalhe
                    label="Urgência"
                    value={
                      (Desc_Urgencia as any)[
                      String(selectedNotification.urgencia_agendamento)
                      ]
                    }
                  />
                  <CampoDetalhe
                    label="Tipo de agendamento"
                    value={
                      (Desc_TipoTarefa as any)[
                      String(selectedNotification.tipo_agendamento)
                      ]
                    }
                  />
                  <CampoDetalhe
                    label="Usuário que Movimentou:"
                    value={selectedNotification.nome_usuario_movimento}
                  />
                  <CampoDetalhe
                    label="Data do Movimento:"
                    value={formatarHorario(
                      selectedNotification.data_hora_criacao
                    )}
                  />

                  <CampoDetalhe
                    label="ID da Notificação (Ação):"
                    value={selectedNotification.id_automatizacao_notificacao}
                  />

                  {/* Item 06: origem das notificações geradas por uma
                      Notificação de Etapa. */}
                  <CampoDetalhe
                    label="Fluxo:"
                    value={selectedNotification.nome_fluxo_notificacao}
                  />
                  <CampoDetalhe
                    label="Etapa:"
                    value={selectedNotification.nome_etapa_notificacao}
                  />

                  {/* Fluxo/Etapa de onde o card saiu na movimentação. */}
                  <CampoDetalhe
                    label="Fluxo de Origem:"
                    value={selectedNotification.nome_fluxo_saida_notificacao}
                  />
                  <CampoDetalhe
                    label="Etapa de Origem:"
                    value={selectedNotification.nome_etapa_saida_notificacao}
                  />
                </div>
              </div>
            </div>
          </>
        ) : (
          <div className="flex h-full w-full flex-col items-center justify-center gap-2 px-6 text-center">
            <img
              src={
                colorMode == "light"
                  ? "/images/logo/backgorundLinksunBlack.png"
                  : "/images/logo/backgorundLinksun.png"
              }
              alt=""
              className="h-10 w-10 opacity-30"
            />
            <p className="text-sm text-body-color">
              Selecione uma notificação para visualizá-la
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default NotificationsPage;