import { useEffect, useMemo, useState } from 'react'
import { Container } from 'react-bootstrap'
import { Link } from 'react-router-dom'
import { listAllForums } from '../api/client'
import { useTranslation } from 'react-i18next'

export default function Home() {
  const [forums, setForums] = useState([])
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)
  const { t } = useTranslation()

  useEffect(() => {
    listAllForums()
      .then(setForums)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }, [])

  const getParentId = (forum) => {
    if (!forum.parent) return null
    if (typeof forum.parent === 'string') {
      return forum.parent.split('/').pop()
    }
    return forum.parent.id ?? null
  }

  const forumTree = useMemo(() => {
    const map = new Map()
    const roots = []

    forums.forEach((forum) => {
      map.set(String(forum.id), { ...forum, children: [] })
    })

    forums.forEach((forum) => {
      const parentId = getParentId(forum)
      const node = map.get(String(forum.id))
      if (parentId && map.has(String(parentId))) {
        map.get(String(parentId)).children.push(node)
      } else {
        roots.push(node)
      }
    })

    const sortNodes = (nodes) => {
      nodes.sort((a, b) => {
        if (a.position !== b.position) return a.position - b.position
        return a.name.localeCompare(b.name)
      })
      nodes.forEach((node) => sortNodes(node.children))
    }

    sortNodes(roots)

    return roots
  }, [forums])

  const renderTree = (nodes, depth = 0) =>
    nodes.map((node) => (
      <div key={node.id}>
        <div
          className="bb-forum-row border rounded p-3 mb-2 d-flex align-items-center justify-content-between"
          style={{ marginLeft: depth * 16 }}
        >
          <div className="d-flex align-items-start gap-3">
            <span className={`bb-icon ${node.type === 'forum' ? 'bb-icon--forum' : ''}`}>
              <i className={`bi ${node.type === 'category' ? 'bi-folder2' : 'bi-chat-left-text'}`} />
            </span>
            <div>
              <Link to={`/forum/${node.id}`} className="bb-forum-link fw-semibold">
                {node.name}
              </Link>
              <div className="bb-muted">{node.description || t('forum.no_description')}</div>
            </div>
          </div>
        </div>
        {node.children?.length > 0 && (
          <div className="mb-2">{renderTree(node.children, depth + 1)}</div>
        )}
      </div>
    ))

  return (
    <Container className="py-5">
      <div className="bb-hero mb-4">
        <p className="bb-chip">{t('app.brand')}</p>
        <h1 className="mt-3">{t('home.hero_title')}</h1>
        <p className="bb-muted mb-0">
          {t('home.hero_body')}
        </p>
      </div>

      <h3 className="bb-section-title mb-3">{t('home.browse')}</h3>
      {loading && <p className="bb-muted">{t('home.loading')}</p>}
      {error && <p className="text-danger">{error}</p>}
      {!loading && forumTree.length === 0 && (
        <p className="bb-muted">{t('home.empty')}</p>
      )}
      {forumTree.length > 0 && <div className="mt-2">{renderTree(forumTree)}</div>}
    </Container>
  )
}
