import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../../utils/api'
import TrendKcalWeightChart from '../TrendKcalWeightChart'
import { normalizeBodyChartDays } from '../../widgetSystem/bodyChartDays'

/**
 * @param {{ refreshTick?: number, chartDays?: number }} props
 */
export default function TrendKcalWeightWidget({ refreshTick = 0, chartDays }) {
  const nav = useNavigate()
  const windowDays = chartDays != null ? normalizeBodyChartDays(chartDays) : 30
  const fetchNutritionDays = Math.max(windowDays, 30)
  const [weights, setWeights] = useState([])
  const [nutrition, setNutrition] = useState([])

  useEffect(() => {
    Promise.all([api.listWeight(Math.max(60, windowDays + 30)), api.listNutrition(fetchNutritionDays)])
      .then(([w, n]) => {
        setWeights(w)
        setNutrition(n)
      })
      .catch(() => {
        setWeights([])
        setNutrition([])
      })
  }, [refreshTick, windowDays, fetchNutritionDays])

  if (weights.length <= 2 && nutrition.length <= 2) {
    return (
      <div className="card section-gap" style={{ marginBottom: 16, fontSize: 13, color: 'var(--text3)' }}>
        Mehr Gewichts- und Ernährungsdaten für den Trend nötig.
      </div>
    )
  }

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Trends</div>
          <div style={{ fontSize: 12, color: 'var(--text3)' }}>
            Kalorien und Gewicht ({windowDays} Tage)
          </div>
        </div>
        <button
          type="button"
          className="btn btn-secondary"
          style={{ fontSize: 12, padding: '6px 12px' }}
          onClick={() => nav('/history', { state: { tab: 'body' } })}
        >
          Details →
        </button>
      </div>
      <TrendKcalWeightChart weights={weights} nutrition={nutrition} windowDays={windowDays} />
      <div
        style={{
          display: 'flex',
          gap: 16,
          justifyContent: 'center',
          marginTop: 6,
          fontSize: 10,
          color: 'var(--text3)',
        }}
      >
        <span>
          <span
            style={{
              display: 'inline-block',
              width: 12,
              height: 2,
              background: '#EF9F27',
              verticalAlign: 'middle',
              marginRight: 3,
            }}
          />
          Ø Kalorien
        </span>
        <span>
          <span
            style={{
              display: 'inline-block',
              width: 12,
              height: 2,
              background: '#378ADD',
              verticalAlign: 'middle',
              marginRight: 3,
            }}
          />
          Gewicht
        </span>
      </div>
    </div>
  )
}
