import { useEffect, useState } from 'react'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
import { useProfile } from '../../context/ProfileContext'
import { api } from '../../utils/api'

dayjs.locale('de')

/** Produkt-Dashboard: Begrüßung + Datum + letztes Gewicht-Datum */
export default function DashboardGreetingWidget({ refreshTick = 0 }) {
  const { activeProfile } = useProfile()
  const [latestWeightDate, setLatestWeightDate] = useState(null)

  useEffect(() => {
    api
      .listWeight(1)
      .then((rows) => {
        setLatestWeightDate(rows?.[0]?.date || null)
      })
      .catch(() => setLatestWeightDate(null))
  }, [refreshTick])

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <h2 style={{ fontSize: 22, fontWeight: 800, margin: 0, color: 'var(--text1)' }}>
        Hallo, {activeProfile?.name || 'Nutzer'} 👋
      </h2>
      <div style={{ fontSize: 12, color: 'var(--text3)', marginTop: 2 }}>
        {dayjs().format('dddd, DD. MMMM YYYY')}
        {latestWeightDate && ` · Letztes Update ${dayjs(latestWeightDate).format('DD.MM.')}`}
      </div>
    </div>
  )
}
