import { useMemo, useState } from 'react';
import styled from '@emotion/styled';
import PropTypes from 'prop-types';
import { useReactive } from 'ahooks';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import IconButton from '@mui/material/IconButton';
import GeneralIcon from '@mui/icons-material/TuneRounded';
import KeyIcon from '@mui/icons-material/Key';
import LockIcon from '@mui/icons-material/Lock';
import LoginIcon from '@mui/icons-material/Login';
import NotificationsNoneIcon from '@mui/icons-material/NotificationsNone';
import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import MenuIcon from '@mui/icons-material/Menu';
import { useSearchParams } from 'react-router-dom';
import { Icon } from '@iconify/react';
import iconViewHeadlineRounded from '@iconify-icons/material-symbols/view-headline-rounded';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Tabs from '@arcblock/ux/lib/Tabs';
import { getDisplayName } from '@blocklet/meta/lib/util';
import BlockletBundleAvatar from '../bundle-avatar';
import BlockletAppAvatar from '../app-avatar';
import BlockletConfiguration from '../configuration';
import BlockletNotification from '../notification';
import Authentication from '../authentication';
import BlockletSecurity from '../security';
import BlockletAccessPolicy from '../security/access-policy';
import BlockletResponseHeaderPolicy from '../security/response-header-policy';
import BlockletPreference from './preference';
import useMobile from '../../hooks/use-mobile';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const addComponentTabs = ({
  tabs,
  blocklet,
  ancestors = [],
  depth = 1,
  t
}) => {
  const key = [...ancestors.map(x => x.meta.did), blocklet.meta.did].join('/');
  const isContainer = !ancestors?.length;
  tabs.push({
    label: /*#__PURE__*/_jsxs(Box, {
      sx: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-start',
        pl: Math.max(1, depth - 1) * 2
      },
      children: [isContainer ? /*#__PURE__*/_jsx(BlockletAppAvatar, {
        size: 24,
        blocklet: blocklet,
        style: {
          borderRadius: 0
        }
      }) : /*#__PURE__*/_jsx(BlockletBundleAvatar, {
        size: 24,
        blocklet: blocklet,
        ancestors: ancestors,
        style: {
          borderRadius: 0
        }
      }), /*#__PURE__*/_jsx(Box, {
        sx: {
          ml: 2
        },
        children: /*#__PURE__*/_jsx(Box, {
          sx: {
            color: 'text.primary'
          },
          children: isContainer ? t('blocklet.component.container') : getDisplayName(blocklet, true)
        })
      })]
    }, key),
    value: key
  });
  if (blocklet.children.length > 0) {
    blocklet.children.forEach(x => {
      addComponentTabs({
        tabs,
        blocklet: x,
        ancestors: [...ancestors, blocklet],
        depth: depth + 1,
        t
      });
    });
  }
};
export default function BlockletPreferences({
  blocklet,
  onUpdate = () => {},
  ...rest
}) {
  const {
    t
  } = useLocaleContext();
  const currentState = useReactive({
    expandPref: true,
    expandSecurity: true
  });
  const [searchParams, setSearchParams] = useSearchParams();
  const current = searchParams.get('tab') || 'general';
  const isMobile = useMobile();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const tabs = [];
  tabs.push({
    label: /*#__PURE__*/_jsxs(Box, {
      "data-cy": "configuration-tab-general",
      sx: {
        display: 'flex',
        alignItems: 'center'
      },
      children: [/*#__PURE__*/_jsx(GeneralIcon, {
        sx: {
          fontSize: 24
        }
      }), /*#__PURE__*/_jsx(Box, {
        sx: {
          ml: 2,
          color: 'text.primary'
        },
        children: t('common.general')
      })]
    }, "general"),
    value: 'general'
  });
  tabs.push({
    label: /*#__PURE__*/_jsxs(Box, {
      "data-cy": "configuration-tab-security-group",
      sx: {
        display: 'flex',
        alignItems: 'center'
      },
      children: [/*#__PURE__*/_jsx(Box, {
        sx: {
          ml: -2,
          transform: 'translateY(2px)'
        },
        children: currentState.expandSecurity ? /*#__PURE__*/_jsx(ExpandMoreIcon, {
          fontSize: "inherit"
        }) : /*#__PURE__*/_jsx(ChevronRightIcon, {
          fontSize: "inherit"
        })
      }), /*#__PURE__*/_jsx(LockIcon, {
        sx: {
          fontSize: 24
        }
      }), /*#__PURE__*/_jsx(Box, {
        sx: {
          ml: 2,
          color: 'text.primary'
        },
        children: t('common.security')
      })]
    }, "securityGroup"),
    value: 'securityGroup'
  });
  if (currentState.expandSecurity) {
    tabs.push({
      label: /*#__PURE__*/_jsxs(Box, {
        sx: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'flex-start',
          pl: 2
        },
        children: [/*#__PURE__*/_jsx(LockIcon, {
          sx: {
            fontSize: 24
          }
        }), /*#__PURE__*/_jsx(Box, {
          sx: {
            ml: 2,
            color: 'text.primary'
          },
          children: t('securityRule.title')
        })]
      }, "security"),
      value: 'security'
    });
    tabs.push({
      label: /*#__PURE__*/_jsxs(Box, {
        sx: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'flex-start',
          pl: 2
        },
        children: [/*#__PURE__*/_jsx(KeyIcon, {
          sx: {
            fontSize: 24
          }
        }), /*#__PURE__*/_jsx(Box, {
          sx: {
            ml: 2,
            color: 'text.primary'
          },
          children: t('accessPolicy.title')
        })]
      }, "accessPolicy"),
      value: 'accessPolicy'
    });
    tabs.push({
      label: /*#__PURE__*/_jsxs(Box, {
        sx: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'flex-start',
          pl: 2
        },
        children: [/*#__PURE__*/_jsx(Icon, {
          fontSize: 24,
          style: {
            flexShrink: 0
          },
          icon: iconViewHeadlineRounded
        }), /*#__PURE__*/_jsx(Box, {
          sx: {
            ml: 2,
            color: 'text.primary'
          },
          children: t('responseHeaderPolicy.title')
        })]
      }, "responseHeaderPolicy"),
      value: 'responseHeaderPolicy'
    });
  }
  tabs.push({
    label: /*#__PURE__*/_jsxs(Box, {
      sx: {
        display: 'flex',
        alignItems: 'center'
      },
      "data-cy": "configuration-tab-authentication",
      children: [/*#__PURE__*/_jsx(LoginIcon, {
        sx: {
          fontSize: 24
        }
      }), /*#__PURE__*/_jsx(Box, {
        sx: {
          ml: 2,
          color: 'text.primary'
        },
        children: t('common.login')
      })]
    }, "authentication"),
    value: 'authentication'
  });
  tabs.push({
    label: /*#__PURE__*/_jsxs(Box, {
      "data-cy": "configuration-tab-notification",
      sx: {
        display: 'flex',
        alignItems: 'center'
      },
      children: [/*#__PURE__*/_jsx(NotificationsNoneIcon, {
        sx: {
          fontSize: 24
        }
      }), /*#__PURE__*/_jsx(Box, {
        sx: {
          ml: 2,
          color: 'text.primary'
        },
        children: t('common.notification')
      })]
    }, "notification"),
    value: 'notification'
  });
  tabs.push({
    label: /*#__PURE__*/_jsxs(Box, {
      "data-cy": "configuration-tab-preference",
      sx: {
        display: 'flex',
        alignItems: 'center'
      },
      children: [/*#__PURE__*/_jsx(Box, {
        sx: {
          ml: -2,
          transform: 'translateY(2px)'
        },
        children: currentState.expandPref ? /*#__PURE__*/_jsx(ExpandMoreIcon, {
          fontSize: "inherit"
        }) : /*#__PURE__*/_jsx(ChevronRightIcon, {
          fontSize: "inherit"
        })
      }), /*#__PURE__*/_jsx(SettingsOutlinedIcon, {
        sx: {
          fontSize: 24
        }
      }), /*#__PURE__*/_jsx(Box, {
        sx: {
          ml: 2,
          color: 'text.primary'
        },
        children: t('common.preferences')
      })]
    }, "preference"),
    value: 'preference'
  });
  const currentTab = tabs.find(tab => tab.value === current);
  if (currentState.expandPref) {
    addComponentTabs({
      tabs,
      blocklet,
      t
    });
  }
  const onTabChange = x => {
    if (x === 'preference') {
      currentState.expandPref = !currentState.expandPref;
    } else if (x === 'securityGroup') {
      currentState.expandSecurity = !currentState.expandSecurity;
    } else {
      setSearchParams(prev => {
        if (x === 'general') {
          prev.delete('tab');
        } else {
          prev.set('tab', x);
        }
        return prev;
      });
    }
    setDrawerOpen(false);
  };
  let content = null;
  if (current === 'general') {
    content = /*#__PURE__*/_jsx(BlockletConfiguration, {
      blocklet: blocklet,
      onUpdate: onUpdate
    });
  } else if (current === 'security') {
    content = /*#__PURE__*/_jsx(BlockletSecurity, {});
  } else if (current === 'accessPolicy') {
    content = /*#__PURE__*/_jsx(BlockletAccessPolicy, {});
  } else if (current === 'responseHeaderPolicy') {
    content = /*#__PURE__*/_jsx(BlockletResponseHeaderPolicy, {});
  } else if (current === 'authentication') {
    content = /*#__PURE__*/_jsx(Authentication, {});
  } else if (current === 'notification') {
    content = /*#__PURE__*/_jsx(BlockletNotification, {});
  } else {
    content = /*#__PURE__*/_jsx(BlockletPreference, {
      id: current
    });
  }
  const tabBodyStyle = useMemo(() => {
    return {
      position: 'relative',
      minHeight: '66vh',
      height: '100%',
      overflow: 'hidden'
    };
  }, []);
  return /*#__PURE__*/_jsxs(Div, {
    ...rest,
    children: [isMobile && /*#__PURE__*/_jsxs(_Fragment, {
      children: [/*#__PURE__*/_jsxs(Box, {
        sx: {
          color: 'primary.main',
          position: 'sticky',
          top: 0,
          zIndex: 2,
          bgcolor: 'background.default',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          mb: 2
        },
        children: [/*#__PURE__*/_jsx(IconButton, {
          onClick: () => setDrawerOpen(true),
          sx: {
            mr: 1
          },
          children: /*#__PURE__*/_jsx(MenuIcon, {})
        }), /*#__PURE__*/_jsx(Box, {
          children: currentTab?.label
        })]
      }), /*#__PURE__*/_jsx(Drawer, {
        anchor: "left",
        open: drawerOpen,
        onClose: () => setDrawerOpen(false),
        slotProps: {
          paper: {
            sx: {
              width: 260,
              '.MuiTab-root': {
                textAlign: 'left',
                alignItems: 'flex-start',
                fontWeight: 'normal'
              }
            }
          }
        },
        children: /*#__PURE__*/_jsx(Tabs, {
          tabs: tabs,
          current: current,
          orientation: "vertical",
          onChange: onTabChange,
          sx: {
            borderRight: 1,
            height: '100%',
            borderColor: 'divider'
          }
        })
      })]
    }), /*#__PURE__*/_jsxs(Grid, {
      container: true,
      spacing: 4,
      columns: 24,
      children: [!isMobile && /*#__PURE__*/_jsx(Grid, {
        size: {
          xs: 24,
          sm: 7,
          md: 5
        },
        children: /*#__PURE__*/_jsx(Tabs, {
          tabs: tabs,
          current: current,
          orientation: "vertical",
          onChange: onTabChange,
          sx: {
            borderRight: 1,
            height: '100%',
            borderColor: 'divider'
          }
        })
      }), /*#__PURE__*/_jsx(Grid, {
        size: {
          xs: 24,
          sm: 17,
          md: 19
        },
        children: /*#__PURE__*/_jsx(Box, {
          style: tabBodyStyle,
          children: content
        })
      })]
    })]
  });
}
BlockletPreferences.propTypes = {
  blocklet: PropTypes.object.isRequired,
  onUpdate: PropTypes.func
};
const Div = styled.div`
  .MuiTab-root {
    text-align: left;
    align-items: flex-start;
    font-weight: normal;
  }
  .Mui-selected {
    font-weight: bold;
  }
`;