import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import TrainingTypeDistribution from '../TrainingTypeDistribution'
import {
  BODY_CHART_DAYS_DEFAULT,
  normalizeBodyChartDays,
} from '../../widgetSystem/bodyChartDays'
import PilotRuleCard from './PilotRuleCard'

export default function PilotActivitySection({ refreshTick = 0, chartDays = BODY_CHART_DAYS_DEFAULT }) {
  const periodDays = normalizeBodyChartDays(chartDays)
  const { activeProfile } = useProfile()
  const globalQualityLevel = activeProfile?.quality_filter_level
  const [activities, setActivities] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const limit = Math.min(50_000, Math.max(200, periodDays * 25))
        const a = await api.listActivity(limit, periodDays)
        if (!cancelled) setActivities(Array.isArray(a) ? a : [])
      } catch {
        if (!cancelled) setActivities([])
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [refreshTick, globalQualityLevel, periodDays])

  const cutoff = dayjs().subtract(periodDays, 'day').format('YYYY-MM-DD')
  const filtA = (activities || []).filter((d) => d.date >= cutoff)

  const daysWithAct = new Set(filtA.map((a) => a.date)).size
  const totalDays =
    filtA.length > 0
      ? Math.min(periodDays, dayjs().diff(dayjs(filtA[filtA.length - 1]?.date), 'day') + 1)
      : 0
  const consistency = totalDays > 0 ? Math.round((daysWithAct / totalDays) * 100) : 0

  const actRules = [
    {
      status: consistency >= 70 ? 'good' : consistency >= 40 ? 'warn' : 'bad',
      icon: '📅',
      category: 'Konsistenz',
      title: `${consistency}% aktive Tage (${daysWithAct}/${Math.min(periodDays, totalDays || periodDays)} Tage)`,
      detail:
        consistency >= 70
          ? 'Ausgezeichnete Regelmäßigkeit.'
          : consistency >= 40
            ? 'Ziel: 4–5 Einheiten/Woche.'
            : 'Mehr Regelmäßigkeit empfohlen.',
      value: `${consistency}%`,
    },
  ]

  if (loading) {
    return (
      <div className="card section-gap" style={{ textAlign: 'center', padding: 24 }}>
        <div className="spinner" />
      </div>
    )
  }

  return (
    <div className="section-gap" style={{ marginBottom: 24 }}>
      <div
        style={{
          gridColumn: '1 / -1',
          marginBottom: 12,
          paddingBottom: 8,
          borderBottom: '2px solid var(--border)',
        }}
      >
        <h2 style={{ fontSize: 17, fontWeight: 700, margin: 0, color: 'var(--text1)' }}>Bereich Aktivität</h2>
        <p style={{ fontSize: 12, color: 'var(--text2)', margin: '6px 0 0', lineHeight: 1.5 }}>
          Trainingstyp-Verteilung {periodDays} Tage · Bewertung Konsistenz wie im Verlauf
        </p>
      </div>

      {globalQualityLevel && globalQualityLevel !== 'all' && (
        <div
          style={{
            marginBottom: 12,
            padding: '8px 12px',
            borderRadius: 8,
            background: 'var(--surface2)',
            border: '1px solid var(--border)',
            fontSize: 12,
            color: 'var(--text2)',
          }}
        >
          Aktiver Qualitätsfilter im Profil – Aktivitätsdaten entsprechend gefiltert.
          <Link to="/settings" style={{ marginLeft: 8, color: 'var(--accent)' }}>
            Einstellungen
          </Link>
        </div>
      )}

      <div className="card section-gap">
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)', marginBottom: 8 }}>Trainingstyp-Verteilung</div>
        <TrainingTypeDistribution days={periodDays} />
        <div style={{ marginTop: 8, textAlign: 'right' }}>
          <Link to="/history" state={{ tab: 'activity' }} style={{ fontSize: 12, color: 'var(--accent)' }}>
            Vollständiger Verlauf Aktivität →
          </Link>
        </div>
      </div>

      <div className="card section-gap">
        <div className="card-title">Bewertung · Aktivität</div>
        {filtA.length === 0 ? (
          <p style={{ fontSize: 13, color: 'var(--text2)', margin: 0 }}>
            Noch keine Aktivitäten.{' '}
            <Link to="/activity" style={{ color: 'var(--accent)' }}>
              Training erfassen
            </Link>
          </p>
        ) : (
          actRules.map((item, i) => <PilotRuleCard key={i} item={item} />)
        )}
      </div>
    </div>
  )
}
