import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { ApiError } from '../api/client'
import { Card, PageTitle, Table, TablePanel, TableShell } from '../components/ui'
import type { PermissionNode } from '../types/api'

function Tree({ nodes, depth = 0 }: { nodes: PermissionNode[]; depth?: number }) {
  return (
    <ul className={depth ? 'ml-4 border-l border-line pl-3' : ''}>
      {nodes.map((n) => (
        <li key={n.id} className="py-1 text-sm">
          <span className="font-medium">{n.name}</span>
          {n.http_path ? (
            <span className="ml-2 text-xs text-ink-secondary">
              {n.http_methods} {n.http_path}
            </span>
          ) : null}
          {n.children?.length ? <Tree nodes={n.children} depth={depth + 1} /> : null}
        </li>
      ))}
    </ul>
  )
}

export function PermissionsPage() {
  const [catalog, setCatalog] = useState<PermissionNode[]>([])
  const [me, setMe] = useState<Record<string, string>>({})
  const [roles, setRoles] = useState<string[]>([])
  const [error, setError] = useState('')

  useEffect(() => {
    Promise.all([
      api.get<{ tree?: PermissionNode[] }>('/api/v1/permissions/catalog', {
        auth: true,
        query: { tree: true },
      }),
      api.get<{ permissions: Record<string, string>; roles: string[]; tree?: PermissionNode[] }>(
        '/api/v1/permissions/me',
        { auth: true, query: { include_tree: true } },
      ),
    ])
      .then(([cat, mine]) => {
        setCatalog(cat.tree ?? [])
        setMe(mine.permissions)
        setRoles(mine.roles)
      })
      .catch((e: ApiError) => setError(e.message))
  }, [])

  return (
    <div>
      <PageTitle title="權限" subtitle="Catalog 與目前會員權限" />
      {error ? <p className="mb-4 text-sm text-rose-600">{error}</p> : null}
      <div className="grid gap-4 lg:grid-cols-2">
        <Card>
          <h2 className="font-medium">Catalog（tree）</h2>
          <div className="mt-3 max-h-[28rem] overflow-auto">
            <Tree nodes={catalog} />
          </div>
        </Card>
        <Card>
          <h2 className="font-medium">我的權限</h2>
          <p className="mt-2 text-sm text-ink-secondary">Roles: {roles.join(', ') || '—'}</p>
          <TablePanel title="通行證清單" count={Object.keys(me).length} className="mt-4">
            <TableShell>
              <Table minWidth="24rem">
                <thead>
                  <tr>
                    <th>路徑</th>
                    <th>方法</th>
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(me).map(([path, methods]) => (
                    <tr key={path}>
                      <td className="font-mono text-xs">{path}</td>
                      <td className="font-semibold">{methods}</td>
                    </tr>
                  ))}
                </tbody>
              </Table>
            </TableShell>
          </TablePanel>
        </Card>
      </div>
    </div>
  )
}