import { App, Avatar, Dropdown, Flex, Image, Layout } from 'antd';
import { ReactNode, useState } from 'react';
import { Content, Header } from 'antd/es/layout/layout';
import { ACCESS_SETTING, API_URL, getInitialName, handleLogout, UserDataState } from '@pos/base';
import { FaUser } from 'react-icons/fa';
import axios from 'axios';
import Logo from '../../../base/presentation/assets/images/we-logo.png';
import { useRecoilValue } from 'recoil';
import LocalDataConfiguration from './components/local-data-configuration';
import { FileProtectOutlined, FileTextOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

interface AdminLayoutProps {
  children: ReactNode;
}

export default function AdminLayout(props: AdminLayoutProps) {
  const { children } = props;
  const user = useRecoilValue(UserDataState);
  const initialName = getInitialName(user?.name ?? '');

  const { modal } = App.useApp();
  const navigate = useNavigate();

  const [openModalConfig, setOpenModalConfig] = useState(false);
  const onCancelModalConfig = () => setOpenModalConfig(false);
  // const onOpenModalConfig = () => setOpenModalConfig(true);

  async function handleClickLogout() {
    try {
      await axios({ url: `${API_URL.LOGOUT}`, method: 'delete' });
      await handleLogout();
    } catch (err: any) {
      console.error(err);
    }
  }

  function checkAllowAccessSetting() {
    const username = user?.username;
    const accessSetting = ACCESS_SETTING ?? '';

    const allowList = accessSetting.split('|');
    if (allowList.includes(username)) return true;
    return false;
  }

  function gotoHome() {
    navigate('/app');
  }

  function gotoSetting() {
    navigate('/app/setting');
  }

  function gotoLogSetting() {
    navigate('/app/log-setting');
  }

  return (
    <Layout>
      <Header
        style={{
          position: 'sticky',
          top: 0,
          zIndex: 1,
          width: '100%',
          display: 'flex',
          alignItems: 'center',
          background: '#fff',
          borderBottom: '1px solid #ddd',
        }}
      >
        <Flex style={{ width: '100%' }} align="center">
          <Flex>
            <Image src={Logo} width={50} preview={false} onClick={gotoHome} style={{ cursor: 'pointer' }} />
          </Flex>
          <Flex style={{ marginLeft: 'auto' }} gap={15} align="center">
            <Dropdown
              trigger={['click']}
              overlayStyle={{ width: 150 }}
              menu={{
                items: [
                  {
                    key: '1',
                    label: 'Report',
                    icon: <FileTextOutlined />,
                    onClick: () => gotoHome(),
                  },
                  {
                    type: 'divider',
                    key: 'divider_1',
                  },
                  {
                    key: '2',
                    label: 'Setting',
                    icon: <SettingOutlined />,
                    onClick: () => gotoSetting(),
                  },
                  {
                    type: 'divider',
                    key: 'divider_2',
                  },
                  {
                    key: '3',
                    label: 'Log Setting',
                    icon: <FileProtectOutlined />,
                    onClick: () => gotoLogSetting(),
                  },
                  {
                    type: 'divider',
                    key: 'divider_3',
                  },
                  {
                    key: '4',
                    label: 'Logout',
                    icon: <LogoutOutlined />,
                    onClick: () => {
                      modal.confirm({
                        icon: null,
                        cancelText: 'Batal',
                        cancelButtonProps: { style: { width: 100 } },
                        okButtonProps: { style: { width: 100 } },
                        content: <div>Apakah anda yakin ingin keluar dari aplikasi?</div>,
                        onOk: () => handleClickLogout(),
                      });
                    },
                  },
                ]
                  .map((item) => {
                    const isAllowSetting = checkAllowAccessSetting();
                    if (!isAllowSetting && ['1', '2', '3', 'divider_1', 'divider_2', 'divider_3'].includes(item.key)) {
                      return undefined;
                    }
                    return item;
                  })
                  .filter(Boolean) as any,
              }}
            >
              <Avatar size={35} style={{ cursor: 'pointer' }}>
                {initialName ? (
                  <div style={{ fontSize: 13 }}>{initialName?.toUpperCase()}</div>
                ) : (
                  <FaUser style={{ fontSize: 14 }} />
                )}
              </Avatar>
            </Dropdown>
          </Flex>
        </Flex>
      </Header>
      <LocalDataConfiguration open={openModalConfig} onCancel={onCancelModalConfig} />
      <Content style={{ overflow: 'initial', background: '#fff', padding: 10 }}>{children}</Content>
    </Layout>
  );
}
