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, createMuiTheme } from "@material-ui/core/styles";
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) => englishMessages, "en");

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

  useEffect(() => {
    (async () => {
      const dataProvider = await metamigoDataProvider(client);
      // @ts-ignore
      setDataProvider(() => dataProvider);
    })();
  }, [client]);
  return (
    dataProvider && (
      <ThemeProvider theme={createMuiTheme(theme)}>
        <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;
