import { useCallback, useEffect, useState } from 'react';
import type { MouseEventHandler } from 'react';
import { Story, Meta } from '@storybook/react';
import { action } from '@storybook/addon-actions';

import PeopleAltOutlinedIcon from '@mui/icons-material/PeopleAltOutlined';
import Typography from '@mui/material/Typography';

import { ASSETS_URL } from '../../consts/common';
import type { MenuContentProps } from '../dropdown-menu';
import { RightSideBarProvider, RightSideBar, useRightSideBar } from '../right-sidebar';
import { Layout } from './index';
import { LayoutProps } from './types';

const sidebarItemsMap = {
  dashboard: {
    name: 'All Tenants',
    Icon: PeopleAltOutlinedIcon,
    items: [
      { name: 'All Tenants', path: '/marketing/collection-cohort' },
      { name: 'Networks', path: '/marketing/collection-cohort' },
      { name: 'Applications', path: '/marketing/collection-cohort' },
      { name: 'Cancellations', path: '/marketing/all-customers' }
    ]
  },
  cs: {
    name: 'CS',
    Icon: PeopleAltOutlinedIcon,
    items: [
      { name: 'Satisfaction Board', path: '/marketing/collection-cohort' },
      { name: 'QBRs Board', path: '/marketing/collection-cohort' },
      {
        name: 'Agent Rollout',
        subItems: [
          {
            name: 'Agent Rollout Logs',
            path: '/cs/agent-rollout/rollout-versions'
          }
        ]
      }
    ]
  },
  product: {
    name: 'Product',
    Icon: PeopleAltOutlinedIcon,
    items: [
      { name: 'Feature Adoption', path: '/marketing/collection-cohort' },
      {
        name: 'Feature Flag UI',
        subItems: [
          {
            name: 'FF UI Logs',
            path: '/cs/agent-rollout/rollout-versions'
          }
        ]
      }
    ]
  },
  arr: {
    name: 'ARR',
    Icon: PeopleAltOutlinedIcon,
    items: [
      { name: 'ARR Activity', path: '/marketing/collection-cohort' },
      { name: 'ARR Cohort', path: '/marketing/collection-cohort' },
      { name: 'Churn Cohort', path: '/marketing/all-customers' }
    ]
  },
  marketing: {
    name: 'Marketing',
    Icon: PeopleAltOutlinedIcon,
    items: [{ name: 'Collection Cohort', path: '/marketing/collection-cohort' }]
  }
};
const mockClientsData = [
  {
    value: 'someid1',
    name: 'ingrammicro',
    content: {
      src: `${ASSETS_URL}/icons/icon_msp.svg`,
      title: 'Ingram Micro Inc',
      subtitle: 'Partner'
    },
    default: true
  },
  {
    value: 'someid2',
    name: 'hpjewels',
    content: {
      src: 'https://www.google.com/s2/favicons?domain=https://www.hydeparkjewelers.com',
      title: 'Hyde Park Jewelers',
      subtitle: 'Client'
    }
  },
  {
    value: 'someid3',
    name: 'tcgsolutions',
    content: {
      src: 'https://www.google.com/s2/favicons?domain=http://tcgsolutions.pro',
      title: 'TCG Solutions',
      subtitle: 'Client'
    }
  },
  {
    value: 'someid4',
    name: 'rorona',
    content: {
      src: `${ASSETS_URL}/icons/icon_msp.svg`,
      title: '121324324233231312 32423312321321321321312 32132131232132132213',
      subtitle: 'Client'
    }
  }
];
const mockLayoutProps: LayoutProps = {
  children: 'Hello World!',
  // open and setOpen deleted in the Template
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  sidebarProps: {
    logo: (
      <>
        <PeopleAltOutlinedIcon />
        <Typography>Logo</Typography>
      </>
    ),
    closedLogo: <PeopleAltOutlinedIcon />,
    sidebarItemsMap,
    mspClientPicker: {
      isMSP: false,
      props: {
        createNewOrg: () => true,
        onClientClick: action('client click') as MenuContentProps['handleClick'],
        bottomBtnText: 'Add a New Organization',
        orgList: mockClientsData,
        selectValue: ''
      }
    }
  },
  headerProps: {
    breadcrumbsProps: {
      sidebarItemsMap,
      pathname: '/cs/agent-rollout/rollout-logs'
    },
    userControlsProps: {
      name: 'Mock User',
      userRole: 'Developer',
      avatarProps: {
        src: 'https://upload.wikimedia.org/wikipedia/commons/8/8f/Cute-kittens-12929201-1600-1200.jpg'
      },
      notificationBadgeProps: {
        badgeContent: 4
      },
      showDividers: true
    }
  },
  initLeftState: 'closed',
  disableSizeChanges: false,
  hideHeader: false
};

export default {
  component: Layout,
  title: 'Layout/Layout Frame',
  decorators: [
    Story => (
      <RightSideBarProvider>
        <Story />
      </RightSideBarProvider>
    )
  ],
  parameters: {
    layout: 'fullscreen'
  },
  argTypes: {
    children: {
      description: 'Content of the page.'
    },
    headerProps: {
      description: 'Props which will be supplied to the header component.'
    },
    sidebarProps: {
      description: 'Props which will be supplied to the navigation sidebar component.'
    },
    initLeftState: {
      description: 'Initial state of the left sidebar, used for disabling state changes.',
      options: ['closed', 'open', 'locked'],
      control: {
        type: 'select'
      },
      table: {
        defaultValue: {
          summary: 'closed'
        }
      }
    },
    disableSizeChanges: {
      description: 'If true, then the sidebars wont change according to screen size.',
      table: {
        defaultValue: {
          summary: false
        }
      }
    },
    hideHeader: {
      description:
        "If true, the client is running inside CP's infinity portal and header and logo will not be visible.",
      table: {
        defaultValue: {
          summary: false
        }
      }
    }
  }
} as Meta;

const Template: Story<LayoutProps> = args => {
  const {
    displayDifComponent,
    setDrawerBehavior,
    setShowDrawer,
    setComponentSecondaryDrawer,
    setOpenSecondary,
    addEventListener,
    dispatchEvent
  } = useRightSideBar();

  const [listenerAttached, setListenerAttached] = useState(false);
  useEffect(() => {
    if (!listenerAttached) {
      addEventListener('open', e => {
        action('open')(e);
      });
      addEventListener('locked', e => {
        action('locked')(e);
      });
      addEventListener('closed', e => {
        action('closed')(e);
      });
      addEventListener('openSecondary', e => {
        action('openSecondary')(e);
      });
      addEventListener('closedSecondary', e => {
        action('closedSecondary')(e);
      });
      setListenerAttached(true);
    }
  }, [addEventListener, listenerAttached]);

  useEffect(() => {
    displayDifComponent(
      <>
        <Typography variant="h2" mb={3}>
          Main Drawer
        </Typography>
        <Typography variant="body2">
          Use <code>displayDifComponent()</code>
          <br />
          from <code>useRightSideBar()</code>
        </Typography>
      </>
    );
  }, [displayDifComponent]);

  useEffect(() => {
    setShowDrawer(true);
    setDrawerBehavior();
  }, [setDrawerBehavior, setShowDrawer]);

  const handleNotificationClick: MouseEventHandler<HTMLButtonElement> | ((event?: Event) => void) =
    useCallback(
      (event?: Event) => {
        dispatchEvent('openSecondary', event);
        setComponentSecondaryDrawer(
          <>
            <Typography variant="h2" mb={3}>
              Secondary Drawer
            </Typography>
            <Typography variant="body2">
              Use <code>setComponentSecondaryDrawer()</code>
              <br />
              from <code>useRightSideBar()</code>
            </Typography>
          </>
        );
        setOpenSecondary(true);
      },
      [setComponentSecondaryDrawer, setOpenSecondary, dispatchEvent]
    );

  if (args.headerProps.userControlsProps) {
    args.headerProps.userControlsProps.handleNotificationClick = event =>
      handleNotificationClick(event as unknown as Event);
  }

  return (
    <>
      <RightSideBar />
      <Layout {...args} />
    </>
  );
};

export const Primary = Template.bind({});
Primary.args = mockLayoutProps;
