import type { Preview } from "@storybook/react";
import React from "react";
import { themes } from '@storybook/theming';
import { ThemeProvider } from "../src/app/[lang]/dashboard/components/client/theme-provider/theme-provider";
import { DARK_MODE_EVENT_NAME, UPDATE_DARK_MODE_EVENT_NAME } from 'storybook-dark-mode';
import { addons } from '@storybook/preview-api';
import "../src/app/globals.css"


const channel = addons.getChannel();
/**
 *
 * This function will expand the object with nested properties
 * @param obj refrence Object to that
 * @param leftKeys keys to be nested object keys
 * @param value value to be nested
 *
 */
export const recursiveNestedProps = (
  obj: Record<string, unknown>,
  leftKeys: string[],
  value: unknown,
): Record<string, unknown> => {
  if (leftKeys.length <= 0) return obj;
  if (leftKeys.length === 1) {
    // eslint-disable-next-line no-param-reassign
    obj[leftKeys[0]] = value;
    return obj;
  }
  const key = leftKeys.shift();
  if (!key) return obj;

  if (!obj[key]) {
    // eslint-disable-next-line no-param-reassign
    obj[key] = {};
  }

  return recursiveNestedProps(
    obj[key] as Record<string, unknown>,
    leftKeys,
    value,
  );
};

const preview = {
    decorators: [
    (Story, data) => {
      const [isDark, setDark] = React.useState(true);

      const parsedProps = {} as Record<string, unknown>;
      const props = data.allArgs;
      Object.entries(props).forEach((prop) => {
        const [key, value] = prop;
        if (!key.includes("vm")) {
          parsedProps[key] = value;
          return;
        }
        const splitedKey = key.split(".");

        recursiveNestedProps(parsedProps, splitedKey, value);
      });


      React.useEffect(() => {
        channel.on(DARK_MODE_EVENT_NAME, setDark);
        return () => channel.removeListener(DARK_MODE_EVENT_NAME, setDark);
      }, [channel, setDark]);


      return (
        <ThemeProvider
          attribute="class"
          forcedTheme={isDark ? "dark" : "light"}
          enableSystem
          disableTransitionOnChange
       >
         <Story parsedProps={parsedProps} />
       </ThemeProvider> 
      );
    },
  ],
  darkMode: {
    // Override the default dark theme
    dark: { ...themes.dark, appBg: 'black' },
    // Override the default light theme
    classTarget: 'html',
    light: { ...themes.normal, appBg: 'red' },
  },
  parameters: {
    nextjs: {
      appDirectory: true,
    },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
  },
};

export default preview;
