import { useEffect, useMemo, useState } from 'react'
import { useLocale } from '@meshkee/dashboard-ui'
import { ApiError } from '../lib/api'
import { listAllProducts } from '../services/productService'
import { aggregateProductActivity, type ProductMonthActivity } from '../utils/productActivity'
import { useT } from '../i18n/useT'
import styles from './ProductActivityChart.module.css'

const CHART_HEIGHT = 200
const BAR_GAP = 6

export function ProductActivityChart() {
  const t = useT()
  const { locale } = useLocale()
  const [data, setData] = useState<ProductMonthActivity[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    const controller = new AbortController()
    void loadActivity(controller.signal)
    return () => controller.abort()
  }, [locale])

  async function loadActivity(signal?: AbortSignal) {
    setIsLoading(true)
    setError('')

    try {
      const products = await listAllProducts(signal)
      setData(aggregateProductActivity(products, locale))
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') return
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('products.activity.error'))
      }
    } finally {
      setIsLoading(false)
    }
  }

  const maxValue = useMemo(() => {
    const peak = Math.max(...data.flatMap((item) => [item.added, item.updated]), 0)
    return peak > 0 ? peak : 1
  }, [data])

  const totals = useMemo(
    () => ({
      added: data.reduce((sum, item) => sum + item.added, 0),
      updated: data.reduce((sum, item) => sum + item.updated, 0),
    }),
    [data],
  )

  return (
    <section className={styles.card} aria-label={t('products.activity.title')}>
      <div className={styles.header}>
        <div>
          <h3 className={styles.title}>{t('products.activity.title')}</h3>
          <p className={styles.subtitle}>{t('products.activity.subtitle')}</p>
        </div>
        <div className={styles.legend}>
          <span className={styles.legendItem}>
            <span className={`${styles.legendDot} ${styles.legendAdded}`} />
            {t('products.activity.added', { count: totals.added })}
          </span>
          <span className={styles.legendItem}>
            <span className={`${styles.legendDot} ${styles.legendUpdated}`} />
            {t('products.activity.updated', { count: totals.updated })}
          </span>
        </div>
      </div>

      {isLoading ? (
        <p className={styles.status}>{t('products.activity.loading')}</p>
      ) : error ? (
        <p className={styles.error} role="alert">
          {error}
        </p>
      ) : (
        <div className={styles.chartWrap}>
          <div
            className={styles.chart}
            style={{ height: CHART_HEIGHT + 32 }}
            role="img"
            aria-label={t('products.activity.chartAria')}
          >
            {data.map((item) => {
              const addedHeight = (item.added / maxValue) * CHART_HEIGHT
              const updatedHeight = (item.updated / maxValue) * CHART_HEIGHT

              return (
                <div key={item.monthKey} className={styles.group}>
                  <div className={styles.bars} style={{ gap: BAR_GAP }}>
                    <div
                      className={`${styles.bar} ${styles.barAdded}`}
                      style={{ height: Math.max(addedHeight, item.added > 0 ? 4 : 0) }}
                      title={t('products.activity.barAdded', {
                        month: item.label,
                        count: item.added,
                      })}
                    />
                    <div
                      className={`${styles.bar} ${styles.barUpdated}`}
                      style={{ height: Math.max(updatedHeight, item.updated > 0 ? 4 : 0) }}
                      title={t('products.activity.barUpdated', {
                        month: item.label,
                        count: item.updated,
                      })}
                    />
                  </div>
                  <span className={styles.label}>{item.label}</span>
                </div>
              )
            })}
          </div>
        </div>
      )}
    </section>
  )
}
