"use client";

import { FC, useEffect, useState } from "react";
import { Admin, Resource } from "react-admin";
import { useApolloClient } from "@apollo/client";
import polyglotI18nProvider from "ra-i18n-polyglot";
import { ThemeProvider, createTheme } from "@mui/material";
import { metamigoDataProvider } from "../_lib/dataprovider";
import { theme } from "./layout/themes";
import { Layout } from "./layout";
import englishMessages from "../_i18n/en";
import users from "./users";
import accounts from "./accounts";
import whatsappBots from "./whatsapp/bots";
import whatsappMessages from "./whatsapp/messages";
import whatsappAttachments from "./whatsapp/attachments";
import voiceLines from "./voice/voicelines";
import signalBots from "./signal/bots";
import voiceProviders from "./voice/providers";
import webhooks from "./webhooks";
import { AdminLogin, authProvider } from "./AdminLogin";

const i18nProvider = polyglotI18nProvider(
  (_locale: any) => englishMessages,
  "en"
);

const MetamigoAdmin: FC = () => {
  // eslint-disable-next-line unicorn/no-null
  const [dataProvider, setDataProvider] = useState(null);
  const client = useApolloClient();
  const muiTheme = createTheme(theme);

  useEffect(() => {
    (async () => {
      const dataProvider = await metamigoDataProvider(client);
      // @ts-ignore
      setDataProvider(() => dataProvider);
    })();
  }, [client]);
  return (
    dataProvider && (
      <ThemeProvider theme={muiTheme}>
        <Admin
          disableTelemetry
          dataProvider={dataProvider}
          layout={Layout}
          i18nProvider={i18nProvider}
          loginPage={AdminLogin}
          // @ts-ignore
          authProvider={authProvider}
        >
          <Resource name="webhooks" {...webhooks} />
          <Resource name="whatsappBots" {...whatsappBots} />
          <Resource name="whatsappMessages" {...whatsappMessages} />
          <Resource name="whatsappAttachments" {...whatsappAttachments} />
          <Resource name="signalBots" {...signalBots} />
          <Resource name="voiceProviders" {...voiceProviders} />
          <Resource name="voiceLines" {...voiceLines} />
          <Resource name="users" {...users} />
          <Resource name="accounts" {...accounts} />
          <Resource name="languages" />
        </Admin>
      </ThemeProvider>
    )
  );
};

export default MetamigoAdmin;
