"use client";

import { Suspense } from "react";
import { Refine } from "@refinedev/core";
import { App as AntdApp, ConfigProvider } from "antd";
import type { ThemeConfig } from "antd";
import routerProvider from "@refinedev/nextjs-router";

import { authProvider } from "./auth-provider";
import { dataProvider } from "./data-provider";

import "@refinedev/antd/dist/reset.css";

const antdTheme: ThemeConfig = {
  token: {
    /* Aligns with globals --cms-accent-indigo */
    colorPrimary: "#4f46e5",
    borderRadius: 12,
    borderRadiusLG: 16,
    fontSize: 15,
    lineHeight: 1.55,
    fontFamily:
      'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
    fontSizeHeading4: 20,
    fontSizeHeading5: 16,
    colorBgLayout: "transparent",
  },
  components: {
    Button: {
      borderRadius: 14,
      controlHeight: 42,
      controlHeightLG: 46,
      paddingInline: 20,
      paddingInlineLG: 24,
      fontWeight: 600,
    },
    Card: {
      borderRadiusLG: 16,
    },
    Table: {
      cellPaddingBlock: 15,
      cellPaddingInline: 20,
      headerBorderRadius: 12,
    },
    Form: {
      labelFontSize: 14,
      verticalLabelPadding: "0 0 6px",
    },
    Typography: {
      titleMarginBottom: "0.5em",
    },
  },
};

export function RefineRoot({ children }: { children: React.ReactNode }) {
  return (
    <ConfigProvider theme={antdTheme}>
      <AntdApp>
        <Suspense fallback={null}>
          <Refine
            routerProvider={routerProvider}
            dataProvider={dataProvider}
            authProvider={authProvider}
            resources={[
              {
                name: "posts",
                list: "/dashboard/posts",
                create: "/dashboard/posts/new",
                edit: "/dashboard/posts/:id/edit",
                meta: { label: "Posts" },
              },
              {
                name: "categories",
                list: "/dashboard/categories",
                create: "/dashboard/categories/new",
                edit: "/dashboard/categories/:id/edit",
                meta: { label: "Categories" },
              },
            ]}
            options={{ syncWithLocation: true }}
          >
            {children}
          </Refine>
        </Suspense>
      </AntdApp>
    </ConfigProvider>
  );
}
