import { useEffect, useState } from 'react'
import { NavLink, useNavigate } from 'react-router-dom'
import { Home, User, MapPin, ShoppingBag, Heart, HelpCircle, LogOut } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useAuth } from '../context/AuthContext'
import { useT } from '../i18n/useT'
import { getActiveBusinessDomain } from '../lib/businessContext'
import { isAbortError } from '../lib/api'
import { getWebsiteBusinessInfo } from '../services/websiteService'
import meshkeeLogo from '../assets/meshkee-logo.png'
import styles from './Sidebar.module.css'

export function Sidebar() {
  const navigate = useNavigate()
  const { user, logout } = useAuth()
  const { locale } = useLocale()
  const t = useT()
  const [brandName, setBrandName] = useState('')
  const [logoUrl, setLogoUrl] = useState<string | null>(null)

  const businessDomain = getActiveBusinessDomain()
  const fallbackBusinessName = user?.customerBusinesses[0]?.name ?? t('app.storeFallback')
  const displayName = brandName || fallbackBusinessName

  const navItems = [
    { icon: Home, label: t('nav.home'), to: '/' },
    { icon: User, label: t('nav.profile'), to: '/profile' },
    { icon: MapPin, label: t('nav.addresses'), to: '/addresses' },
    { icon: ShoppingBag, label: t('nav.orders'), to: '/orders' },
    { icon: Heart, label: t('nav.favorites'), to: '/favorites' },
  ]

  useEffect(() => {
    const controller = new AbortController()

    async function loadBranding() {
      try {
        const info = await getWebsiteBusinessInfo(businessDomain, controller.signal)
        if (controller.signal.aborted) return
        const localized =
          locale === 'fa'
            ? info.nameFa?.trim() || info.name.trim()
            : info.name.trim() || info.nameFa?.trim()
        setBrandName(localized || fallbackBusinessName)
        setLogoUrl(info.logoUrl?.trim() || null)
      } catch (err) {
        if (isAbortError(err)) return
        setBrandName(fallbackBusinessName)
        setLogoUrl(null)
      }
    }

    void loadBranding()

    return () => {
      controller.abort()
    }
  }, [businessDomain, fallbackBusinessName, locale])

  return (
    <aside className={styles.sidebar}>
      <div className={styles.brand}>
        <img
          src={logoUrl || meshkeeLogo}
          alt={displayName}
          className={styles.brandLogo}
        />
        <div className={styles.brandText}>
          <span className={styles.brandName}>{displayName}</span>
          <span className={styles.brandDomain}>{businessDomain}</span>
        </div>
      </div>

      <nav className={styles.nav}>
        {navItems.map((item) => (
          <NavLink
            key={item.to}
            to={item.to}
            end={item.to === '/'}
            className={({ isActive }) =>
              `${styles.navItem} ${isActive ? styles.active : ''}`
            }
          >
            <item.icon size={20} />
            <span>{item.label}</span>
          </NavLink>
        ))}
      </nav>

      <div className={styles.footer}>
        <button type="button" className={styles.navItem}>
          <HelpCircle size={20} />
          <span>{t('nav.help')}</span>
        </button>
        <button
          type="button"
          className={styles.navItem}
          onClick={() => {
            logout()
            navigate('/login')
          }}
        >
          <LogOut size={20} />
          <span>{t('nav.logout')}</span>
        </button>
      </div>
    </aside>
  )
}
