"use client";

import { Refine, type AuthProvider } from "@refinedev/core";
import { RefineKbar, RefineKbarProvider } from "@refinedev/kbar";
import {
  RefineSnackbarProvider,
  useNotificationProvider,
} from "@refinedev/mui";
import { SessionProvider, signIn, signOut, useSession } from "next-auth/react";
import { usePathname } from "next/navigation";
import React from "react";

import routerProvider from "@refinedev/nextjs-router";

import { ColorModeContextProvider } from "@contexts/color-mode";
import { dataProvider } from "@providers/data-provider";
import { ProjectProvider } from "@/contexts/ProjectContext";

import { LiaNetworkWiredSolid } from "react-icons/lia";
import { TbDatabaseEdit } from "react-icons/tb";
import { LuReplace } from "react-icons/lu";
import { AiOutlineSecurityScan } from "react-icons/ai";
import { TbLocationPin } from "react-icons/tb";
import { AiOutlinePartition } from "react-icons/ai";
import { MdWater, MdOutlineWaterDrop, MdCleaningServices } from "react-icons/md";

type RefineContextProps = {
  defaultMode?: string;
};

export const RefineContext = (
  props: React.PropsWithChildren<RefineContextProps>
) => {
  return (
    <SessionProvider>
      <ProjectProvider>
        <App {...props} />
      </ProjectProvider>
    </SessionProvider>
  );
};

type AppProps = {
  defaultMode?: string;
};

const App = (props: React.PropsWithChildren<AppProps>) => {
  const { data, status } = useSession();
  const to = usePathname();

  if (status === "loading") {
    return <span>loading...</span>;
  }

  const authProvider: AuthProvider = {
    login: async () => {
      signIn("keycloak", {
        callbackUrl: to ? to.toString() : "/",
        redirect: true,
      });

      return {
        success: true,
      };
    },
    logout: async () => {
      signOut({
        redirect: true,
        callbackUrl: "/login",
      });

      return {
        success: true,
      };
    },
    onError: async (error) => {
      if (error.response?.status === 401) {
        return {
          logout: true,
        };
      }

      return {
        error,
      };
    },
    check: async () => {
      if (status === "unauthenticated") {
        return {
          authenticated: false,
          redirectTo: "/login",
        };
      }

      return {
        authenticated: true,
      };
    },
    getPermissions: async () => {
      return null;
    },
    getIdentity: async () => {
      if (data?.user) {
        const { user } = data;
        return {
          name: user.name,
          avatar: user.image,
        };
      }

      return null;
    },
  };

  const defaultMode = props?.defaultMode;

  return (
    <>
      <RefineKbarProvider>
        <ColorModeContextProvider defaultMode={defaultMode}>
          <RefineSnackbarProvider>
            <Refine
              routerProvider={routerProvider}
              dataProvider={dataProvider}
              notificationProvider={useNotificationProvider}
              authProvider={authProvider}
              resources={[
                {
                  name: "管网在线模拟",
                  list: "/network-simulation",
                  meta: {
                    icon: <LiaNetworkWiredSolid className="w-6 h-6" />,
                    label: "管网在线模拟",
                  },
                },
                {
                  name: "SCADA 数据清洗",
                  list: "/scada-data-cleaning",
                  meta: {
                    icon: <TbDatabaseEdit className="w-6 h-6" />,
                    label: "SCADA 数据清洗",
                  },
                },
                {
                  name: "监测点优化布置",
                  list: "/monitoring-place-optimization",
                  meta: {
                    icon: <LuReplace className="w-6 h-6" />,
                    label: "监测点优化布置",
                  },
                },
                {
                  name: "健康风险分析",
                  list: "/health-risk-analysis",
                  meta: {
                    icon: <AiOutlineSecurityScan className="w-6 h-6" />,
                    label: "健康风险分析",
                  },
                },
                {
                  name: "Hydraulic Simulation",
                  meta: {
                    icon: <MdWater className="w-6 h-6" />,
                    label: "事件模拟",
                  },
                },
                {
                  name: "爆管分析定位",
                  list: "/hydraulic-simulation/pipe-burst-analysis",
                  meta: {
                    parent: "Hydraulic Simulation",
                    icon: <TbLocationPin className="w-6 h-6" />,
                    label: "爆管分析定位",
                  },
                },
                {
                  name: "水质模拟",
                  list: "/hydraulic-simulation/water-quality-simulation",
                  meta: {
                    parent: "Hydraulic Simulation",
                    icon: <MdOutlineWaterDrop className="w-6 h-6" />,
                    label: "水质模拟",
                  },
                },
                {
                  name: "管道冲洗",
                  list: "/hydraulic-simulation/pipe-flushing",
                  meta: {
                    parent: "Hydraulic Simulation",
                    icon: <MdCleaningServices className="w-6 h-6" />,
                    label: "管道冲洗",
                  },
                },
                {
                  name: "管网优化分区",
                  list: "/network-partition-optimization",
                  meta: {
                    icon: <AiOutlinePartition className="w-6 h-6" />,
                    label: "管网优化分区",
                  },
                },
              ]}
              options={{
                syncWithLocation: true,
                warnWhenUnsavedChanges: true,
              }}
            >
              {props.children}
              <RefineKbar />
            </Refine>
          </RefineSnackbarProvider>
        </ColorModeContextProvider>
      </RefineKbarProvider>
    </>
  );
};
