import { gray } from '@ant-design/colors';
import {
  FileProtectOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import {
  Grid,
  Layout,
  Menu,
  MenuProps,
  Space,
  Tooltip,
  Typography,
} from 'antd';
import { MenuItemGroupType } from 'rc-menu/lib/interface';
import React from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { Brand } from '../components/brand';
import { LanguageSelect } from '../components/language-select';

const headerHeight = '0px';
const contentHeight = `calc(100vh - ${headerHeight})`;

const StyledSider = styled(Layout.Sider)`
  & .ant-layout-sider-children {
    display: flex;
    flex-direction: column;
  }

  & .ant-menu .ant-menu.ant-menu-sub.ant-menu-inline {
    background: #002140;
    border-radius: 8px;
  }
`;

function getSelectedKeys(menuItems: MenuProps['items']) {
  function isMenuItemGroup(
    item: MenuProps['items'][number],
  ): item is MenuItemGroupType {
    return (item as any).children;
  }

  return menuItems.reduce<string[]>((acc, item) => {
    if (location.pathname.startsWith(String(item.key))) {
      acc.push(String(item.key));
    }

    if (isMenuItemGroup(item)) {
      acc.push(...getSelectedKeys(item.children));
    }

    return acc;
  }, []);
}

export function MainLayout() {
  const screens = Grid.useBreakpoint();
  const { i18n } = useLingui();
  const location = useLocation();
  const leftMenuItems = useLeftMenuItems();
  const [isCollapsed, setCollapsed] = React.useState(false);

  return (
    <Layout>
      <StyledSider
        hidden={!screens.lg}
        collapsible
        width={240}
        collapsed={isCollapsed}
        onCollapse={(collapsed) => setCollapsed(collapsed)}
        trigger={
          isCollapsed ? (
            <Tooltip title={t(i18n)`Expand`}>
              <RightOutlined />
            </Tooltip>
          ) : (
            <Tooltip title={t(i18n)`Collapse`}>
              <LeftOutlined />
            </Tooltip>
          )
        }
      >
        <Brand collapsed={isCollapsed} />
        <Menu
          theme="dark"
          mode="inline"
          items={leftMenuItems}
          style={{
            padding: 8,
          }}
          activeKey={location.pathname}
          selectedKeys={getSelectedKeys(leftMenuItems)}
          defaultOpenKeys={['/template']}
        />
        {!isCollapsed && (
          <Space
            direction="vertical"
            style={{
              padding: 8,
              marginTop: 'auto',
              alignItems: 'center',
            }}
          >
            {/* <LanguageSelect /> */}
            <Typography.Paragraph
              style={{
                marginBottom: 0,
                color: gray[0],
                textAlign: 'left',
              }}
              ellipsis={{
                rows: 10,
              }}
            >
              <b>NOTE: </b> This UI is only for reference. Please use swagger UI for full-option API testing.
              <br />
              <br />
              Powered by SAMSUNG SDS.
              <br />
              All rights reserved.
            </Typography.Paragraph>
          </Space>
        )}
      </StyledSider>
      <Layout
        style={{
          height: '100vh',
        }}
      >
        <Layout.Header
          style={{
            display: 'flex',
            alignItems: 'center',
            padding: 16,
            justifyContent: 'space-between',
          }}
          hidden={screens.md}
        >
          <Brand collapsed={isCollapsed} isBordered={false} />
          <Typography.Paragraph
            style={{
              marginBottom: 0,
              color: gray[0],
              textAlign: 'left',
            }}
          >
            <b>NOTE: </b> This UI is only for reference. Please use swagger UI for full-option API testing.
            <br />
            Powered by SAMSUNG SDS.
          </Typography.Paragraph>
        </Layout.Header>
        <Layout.Content
          style={{
            padding: 4,
            height: contentHeight,
            overflow: 'auto',
          }}
        >
          <React.Suspense>
            <Outlet />
          </React.Suspense>
        </Layout.Content>
      </Layout>
    </Layout>
  );
}

function useLeftMenuItems(): MenuProps['items'] {
  const { i18n } = useLingui();
  const navigate = useNavigate();

  // const templatesQuery = useTemplates(userQuery.data?.userId, {
  //   enabled: userQuery.isSuccess,
  // });

  return [
    {
      key: '/invoice',
      label: t(i18n)`Invoice`,
      icon: <FileProtectOutlined />,
      onClick() {
        navigate('/invoice');
      },
    },
    // {
    //   key: '/driver-license',
    //   label: t(i18n)`Driver License`,
    //   icon: <IdcardOutlined />,
    //   onClick() {
    //     navigate('/driver-license');
    //   },
    // },
    // {
    //   key: '/id-card',
    //   label: t(i18n)`ID Card`,
    //   icon: <IdcardOutlined />,
    //   onClick() {
    //     navigate('/id-card');
    //   },
    // },
    // {
    //   key: '/other-documents',
    //   label: t(i18n)`Other Documents`,
    //   icon: <FileTextOutlined />,
    //   onClick() {
    //     navigate('/other-documents');
    //   },
    // },
    // {
    //   key: '/template',
    //   label: t(i18n)`Templates`,
    //   icon: <FileTextOutlined />,
    //   children: templatesQuery.data?.map((temp) => {
    //     return {
    //       key: `/template/${temp.id}`,
    //       label: temp.name,
    //       title: temp.name,
    //       onClick() {
    //         navigate(`/template/${temp.id}`);
    //       },
    //     };
    //   }),
    // },
    // {
    //   key: '/template-settings',
    //   label: t(i18n)`Template Settings`,
    //   icon: <SettingOutlined />,
    //   onClick() {
    //     navigate('/template-settings');
    //   },
    // },
  ];
}
