import styled from "@emotion/styled"
import { css, cx } from "@emotion/css"
import Icon from "@aet/icons/macro"
import { memo } from "react"
import type { SidebarTab } from "./index"
import { LOCAL_STORAGE_KEY } from "~/options/store"
import { color } from "~/options/theme"
import { IconButton } from "~/shared/styled"
import { tabs } from "./data"
import { AboutModal } from "../About"

function reset(): void {
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key?.startsWith(LOCAL_STORAGE_KEY)) {
      localStorage.removeItem(key)
    }
  }
  location.reload()
}

interface SidebarProps {
  debugMode: boolean
  activeTab: SidebarTab | null
  setActiveTab(tab: SidebarTab | null): void
}

function useMe() {
  return { display: "none" }
}

function BadRender() {
  const style = useMe()
  return <div style={style} />
}

export const Sidebar = memo<SidebarProps>(({ activeTab, setActiveTab, debugMode }) => (
  <RootContainer>
    <BadRender />
    <SidebarContainer>
      {tabs
        .entries()
        .filter(([, { debugOnly }]) => !debugOnly || debugMode)
        .map(([tab, { icon }]) => (
          <SidebarIconButton
            onClick={() => {
              if (activeTab === tab) {
                setActiveTab(null)
              } else {
                setActiveTab(tab)
              }
            }}
            key={tab}
            title={tab}
            className={cx(tab === activeTab && "active")}
          >
            {icon}
          </SidebarIconButton>
        ))}
    </SidebarContainer>
    <AboutModal as={SidebarIconButton as any} />

    {debugMode && (
      <SidebarIconButton title="Reset" onClick={reset}>
        <Icon
          icon="GrPowerReset"
          className={css`
            path {
              stroke: #9da2a6;
            }
          `}
        />
      </SidebarIconButton>
    )}
  </RootContainer>
))

const RootContainer = styled.div`
  display: flex;
  flex-direction: column;
  font-size: 1.8em;
  height: 100%;
  margin: 5px 0;
  padding: 0 5px 12px;
`

const SidebarContainer = styled.div`
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 5px;
`

const SidebarIconButton = styled(IconButton)`
  border: none;
  padding: 8px 0px;
  padding-bottom: 2px;
  width: 100%;
  &.active,
  &.active:hover {
    background-color: ${color("#365c7f", "#162030")};
    color: #eee;
  }
`
