import { useEffect, useMemo, useState } from 'react'
import { Link, NavLink, Outlet, useLocation } from 'react-router-dom'
import { api } from '../api/client.js'

function useMailboxAccountId() {
  const loc = useLocation()
  return useMemo(() => {
    const m = loc.pathname.match(/\/admin\/mailbox\/(\d+)/)
    return m ? Number(m[1]) : null
  }, [loc.pathname])
}

function accountActive(location, id) {
  return (
    location.pathname === `/admin/mailbox/${id}` || location.pathname === `/admin/compose/${id}`
  )
}

function SidebarMailboxLink({ accountId, name }) {
  const location = useLocation()
  const current = new URLSearchParams(location.search).get('mailbox') || 'INBOX'
  const active =
    location.pathname === `/admin/mailbox/${accountId}` && current === name
  return (
    <Link
      to={`/admin/mailbox/${accountId}?mailbox=${encodeURIComponent(name)}`}
      className={'sidebar-item' + (active ? ' active' : '')}
    >
      {name}
    </Link>
  )
}

export default function MainLayout() {
  const location = useLocation()
  const [accounts, setAccounts] = useState([])
  const [boxes, setBoxes] = useState([])
  const accountId = useMailboxAccountId()

  useEffect(() => {
    api
      .listAccounts()
      .then((rows) => setAccounts(Array.isArray(rows) ? rows : []))
      .catch(() => setAccounts([]))
  }, [location.pathname])

  useEffect(() => {
    if (!accountId) {
      setBoxes([])
      return
    }
    api
      .listMailboxes(accountId)
      .then((b) => setBoxes(Array.isArray(b) ? b : []))
      .catch(() => setBoxes([]))
  }, [accountId])

  return (
    <div className="app-shell">
      <aside className="sidebar">
        <div className="sidebar-section">
          <div className="sidebar-label">邮箱</div>
          {accounts.map((a) => (
            <NavLink
              key={a.id}
              to={`/admin/mailbox/${a.id}`}
              className={() =>
                'sidebar-item' + (accountActive(location, a.id) ? ' active' : '')
              }
            >
              <span className="sidebar-item-title">{a.name || '未命名'}</span>
              <span className="sidebar-item-sub muted">{a.email}</span>
            </NavLink>
          ))}
          {accounts.length === 0 && <p className="sidebar-muted">暂无账户</p>}
          <Link to="/admin/accounts" className="sidebar-foot">
            管理账户
          </Link>
        </div>

        {accountId != null && (
          <div className="sidebar-section">
            <div className="sidebar-label">邮件夹</div>
            {boxes.map((b) => (
              <SidebarMailboxLink key={b} accountId={accountId} name={b} />
            ))}
            {boxes.length === 0 && <p className="sidebar-muted">暂无或加载中</p>}
            <Link to={`/admin/compose/${accountId}`} className="sidebar-foot">
              写邮件
            </Link>
          </div>
        )}
      </aside>
      <main className="main-area">
        <Outlet />
      </main>
    </div>
  )
}
