import { useEffect, useState } from 'react'
import { CalendarDays, User, MapPin, ShoppingBag, Heart, Package } from 'lucide-react'
import { SectionCard, useLocale } from '@meshkee/dashboard-ui'
import { useAuth } from '../context/AuthContext'
import { useTenantBranding } from '../context/TenantBrandingContext'
import { useT } from '../i18n/useT'
import type { CustomerMessageKey } from '../i18n/messages'
import { listAddresses } from '../services/addressService'
import { listFavorites } from '../services/favoritesService'
import { listOrders } from '../services/orderService'
import { listMyUserProducts } from '../services/userProductsService'
import { hasBusinessModule } from '../utils/businessModules'
import styles from '../components/PageContent.module.css'

type CountKey = 'myProducts' | 'addresses' | 'orders' | 'favorites'

type HomeSection = {
  icon: typeof User
  titleKey: CustomerMessageKey
  descKey: CustomerMessageKey
  countLabelKey?: CustomerMessageKey
  href: string
  countKey?: CountKey
  colClass: string
  moduleGated?: boolean
}

const baseSections: HomeSection[] = [
  {
    icon: Package,
    titleKey: 'home.card.myProducts.title',
    descKey: 'home.card.myProducts.desc',
    countLabelKey: 'home.card.myProducts.count',
    href: '/my-products',
    countKey: 'myProducts',
    colClass: styles.col6,
    moduleGated: true,
  },
  {
    icon: User,
    titleKey: 'home.card.profile.title',
    descKey: 'home.card.profile.desc',
    href: '/profile',
    colClass: styles.col3,
  },
  {
    icon: MapPin,
    titleKey: 'home.card.addresses.title',
    descKey: 'home.card.addresses.desc',
    countLabelKey: 'home.card.addresses.count',
    href: '/addresses',
    countKey: 'addresses',
    colClass: styles.col3,
  },
  {
    icon: ShoppingBag,
    titleKey: 'home.card.orders.title',
    descKey: 'home.card.orders.desc',
    countLabelKey: 'home.card.orders.count',
    href: '/orders',
    countKey: 'orders',
    colClass: styles.col3,
  },
  {
    icon: Heart,
    titleKey: 'home.card.favorites.title',
    descKey: 'home.card.favorites.desc',
    countLabelKey: 'home.card.favorites.count',
    href: '/favorites',
    countKey: 'favorites',
    colClass: styles.col3,
  },
]

type SectionCounts = Partial<Record<CountKey, number>>

async function loadSectionCounts(signal: AbortSignal): Promise<SectionCounts> {
  const [myProducts, addresses, orders, favorites] = await Promise.all([
    listMyUserProducts({ page: 1, pageSize: 1 }, signal)
      .then((r) => r.total)
      .catch(() => null),
    listAddresses(signal)
      .then((r) => r.items.length)
      .catch(() => null),
    listOrders({ page: 1, pageSize: 1 }, signal)
      .then((r) => r.total)
      .catch(() => null),
    listFavorites({ page: 1, pageSize: 1 }, signal)
      .then((r) => r.total)
      .catch(() => null),
  ])

  const counts: SectionCounts = {}
  if (myProducts !== null) counts.myProducts = myProducts
  if (addresses !== null) counts.addresses = addresses
  if (orders !== null) counts.orders = orders
  if (favorites !== null) counts.favorites = favorites
  return counts
}

export function HomePage() {
  const { user } = useAuth()
  const { locale } = useLocale()
  const { enabledModules } = useTenantBranding()
  const t = useT()
  const [counts, setCounts] = useState<SectionCounts>({})

  const showMyProducts = hasBusinessModule(enabledModules, 'customer_products')

  useEffect(() => {
    const controller = new AbortController()
    void loadSectionCounts(controller.signal).then((next) => {
      if (!controller.signal.aborted) setCounts(next)
    })
    return () => controller.abort()
  }, [])

  const firstName =
    (locale === 'en' ? user?.firstNameEn : user?.firstName) ||
    user?.firstName ||
    user?.firstNameEn ||
    t('home.welcomeFallback')

  const sections = baseSections.filter(
    (section) => !section.moduleGated || showMyProducts,
  )

  const formattedDate = new Intl.DateTimeFormat(locale === 'fa' ? 'fa-IR' : 'en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    weekday: 'long',
  }).format(new Date())

  return (
    <main className={styles.content}>
      <div className={styles.pageHeader}>
        <div>
          <h2 className={styles.pageTitle}>
            {t('home.welcome', { name: firstName })}
          </h2>
          <p className={styles.pageSubtitle}>{t('home.subtitle')}</p>
        </div>

        <div className={styles.dateBadge}>
          <CalendarDays size={16} />
          <span>{formattedDate}</span>
        </div>
      </div>

      <div className={styles.grid12}>
        {sections.map((section) => (
          <div key={section.href} className={section.colClass}>
            <SectionCard
              icon={section.icon}
              title={t(section.titleKey)}
              description={t(section.descKey)}
              href={section.href}
              count={section.countKey ? counts[section.countKey] : undefined}
              countLabel={
                section.countLabelKey ? t(section.countLabelKey) : undefined
              }
            />
          </div>
        ))}
      </div>
    </main>
  )
}
