import Link from 'next/link';
import { requireCanView } from '@/lib/auth';
import { loadStudent } from '@/lib/data';
import { computeSummary, computeTrend, sortEntries } from '@/lib/stats';
import { kg, int, pct, signed, dateMid, dateLong, dateShort } from '@/lib/format';
import TopBar from '@/components/TopBar';
import { WeightChart, GoalBarChart, MacroChart } from '@/components/Charts';

export const dynamic = 'force-dynamic';

export default async function StudentPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { supabase, me } = await requireCanView(id);
  const { student, goals, entries, photos } = await loadStudent(supabase, id);
  const sum = computeSummary(entries, goals);
  const trend = computeTrend(entries, goals);
  const rows = sortEntries(entries);
  const first = photos[0];
  const latest = photos.length > 1 ? photos[photos.length - 1] : null;
  const isAdmin = me.role === 'admin';
  const name = student.full_name || student.email;

  return (
    <>
      <TopBar me={me} />
      <main className="wrap">
        <header className="stack" style={{ gap: 8 }}>
          {isAdmin && (
            <Link href={`/admin/ogrenci/${id}`} className="muted" style={{ fontSize: 14 }}>
              ← Veri girişi
            </Link>
          )}
          <div className="row between">
            <h1>{isAdmin ? name : 'Değişimin'}</h1>
            {sum && (
              <Link className="btn" href={`/ogrenci/${id}/gorsel`}>
                Değişim görseli
              </Link>
            )}
          </div>
          {sum ? (
            <p className="muted" style={{ margin: 0, maxWidth: '62ch' }}>
              {dateMid(goals.start_date ?? rows[0]?.day)} tarihinden bu yana <b className="accent">{kg(sum.lost)} kg</b> verildi
              {sum.remaining != null && (
                <>
                  , hedefe <b style={{ color: 'var(--fg)' }}>{kg(sum.remaining)} kg</b> kaldı
                </>
              )}
              .
              {sum.planDiff != null && (
                <>
                  {' '}7 günlük ortalamayla plandan <b style={{ color: 'var(--fg)' }}>{kg(Math.abs(sum.planDiff))} kg</b>{' '}
                  {sum.planDiff <= 0 ? 'öndesin.' : 'gerideysin.'}
                </>
              )}
            </p>
          ) : (
            <p className="muted" style={{ margin: 0 }}>
              Henüz kayıt yok. İlk veriler girildiğinde değişimin burada görünecek.
            </p>
          )}
        </header>

        {sum && (
          <>
            <section className="kpis" aria-label="Özet">
              <div className="kpi">
                <span className="kpi-label">Güncel kilo</span>
                <span className="kpi-value num">{kg(sum.current)}<small>kg</small></span>
                <span className="kpi-sub">7 günlük ort. {kg(sum.avg7)} kg</span>
              </div>
              <div className="kpi">
                <span className="kpi-label">Verilen</span>
                <span className="kpi-value num accent">{kg(sum.lost)}<small>kg</small></span>
                <span className="kpi-sub">Başlangıç {kg(sum.startWeight)} kg</span>
              </div>
              <div className="kpi">
                <span className="kpi-label">Hedefe kalan</span>
                <span className="kpi-value num">{kg(sum.remaining)}<small>kg</small></span>
                <span className="kpi-sub">
                  Hedef {kg(goals.goal_weight)} kg{sum.daysLeft != null && sum.daysLeft > 0 ? ` · ${int(sum.daysLeft)} gün` : ''}
                </span>
              </div>
              <div className="kpi">
                <span className="kpi-label">Son 7 gün (ortalamaya göre)</span>
                <span className={`kpi-value num ${sum.lastWeekChange == null ? '' : sum.lastWeekChange < 0 ? 'good' : sum.lastWeekChange > 0 ? 'bad' : ''}`}>
                  {signed(sum.lastWeekChange)}<small>kg</small>
                </span>
                <span className="kpi-sub">Gereken tempo {kg(sum.requiredPerWeek)} kg/hafta</span>
              </div>
            </section>

            {(sum.progressPct != null || sum.timePct != null) && (
              <section className="section stack">
                <h2>Yolculuk</h2>
                {sum.progressPct != null && (
                  <div className="stack" style={{ gap: 6 }}>
                    <div className="row between muted" style={{ fontSize: 13 }}>
                      <span>Kilo hedefi</span>
                      <b style={{ color: 'var(--fg)' }}>{pct(sum.progressPct)}</b>
                    </div>
                    <div className="bar"><i style={{ width: `${Math.max(0, Math.min(100, sum.progressPct))}%` }} /></div>
                  </div>
                )}
                {sum.timePct != null && (
                  <div className="stack" style={{ gap: 6 }}>
                    <div className="row between muted" style={{ fontSize: 13 }}>
                      <span>Geçen süre ({dateLong(goals.goal_date)} hedefine)</span>
                      <b style={{ color: 'var(--fg)' }}>{pct(sum.timePct)}</b>
                    </div>
                    <div className="bar time"><i style={{ width: `${sum.timePct}%` }} /></div>
                  </div>
                )}
              </section>
            )}
          </>
        )}

        <section className="section">
          <h2>Önce ve şimdi</h2>
          <p className="lead">En eski ve en yeni fotoğraf.</p>
          <div className="photos">
            <figure className="photo" style={{ margin: 0 }}>
              <div className={`photo-box ${first?.url ? 'filled' : ''}`}>
                {first?.url ? <img src={first.url} alt="Başlangıç fotoğrafı" /> : 'Başlangıç fotoğrafı henüz yüklenmedi.'}
              </div>
              <figcaption className="photo-cap">
                <span>Önce{first ? ` · ${dateMid(first.taken_on)}` : ''}</span>
                {sum && <b>{kg(sum.startWeight)} kg</b>}
              </figcaption>
            </figure>
            <figure className="photo" style={{ margin: 0 }}>
              <div className={`photo-box ${latest?.url ? 'filled' : ''}`}>
                {latest?.url ? <img src={latest.url} alt="Güncel fotoğraf" /> : 'Güncel fotoğraf yüklendiğinde burada görünecek.'}
              </div>
              <figcaption className="photo-cap">
                <span>Şimdi{latest ? ` · ${dateMid(latest.taken_on)}` : ''}</span>
                {sum && <b className="accent">{kg(sum.current)} kg</b>}
              </figcaption>
            </figure>
          </div>
        </section>

        {sum && trend.length > 0 && (
          <>
            <section className="section">
              <h2>Kilo, güne göre</h2>
              <p className="lead">
                Noktalar günlük tartı, kalın çizgi 7 günlük ortalama
                {goals.goal_date && goals.goal_weight != null ? `, kesikli çizgi ${dateLong(goals.goal_date)} tarihinde ${kg(goals.goal_weight)} kg’a götüren düz plan` : ''}.
              </p>
              <WeightChart data={trend} />
            </section>

            <section className="section">
              <h2>Günlük adım</h2>
              <p className="lead">
                Son 7 günün ortalaması <b>{int(sum.steps.avg7)} adım</b>.
                {goals.step_goal ? (
                  <>
                    {' '}{sum.steps.logged} günün <b>{sum.steps.hit}</b> gününde en az {int(goals.step_goal)} adım hedefi tuttu.
                  </>
                ) : null}
              </p>
              <GoalBarChart data={rows} field="steps" goal={goals.step_goal} mode="min" unit="adım" label="Günlük adım sayısı ve hedefi" />
            </section>

            <section className="section">
              <h2>Günlük kalori</h2>
              <p className="lead">
                Son 7 günün ortalaması <b>{int(sum.calories.avg7)} kcal</b>.
                {goals.calorie_goal ? (
                  <>
                    {' '}{sum.calories.logged} günün <b>{sum.calories.hit}</b> gününde {int(goals.calorie_goal)} kcal hedefinin altında kalındı. Hedefi aşan günler kırmızı.
                  </>
                ) : null}
              </p>
              <GoalBarChart data={rows} field="calories" goal={goals.calorie_goal} mode="max" unit="kcal" label="Günlük kalori ve hedefi" />
            </section>

            <section className="section">
              <h2>Protein, yağ, karbonhidrat</h2>
              <p className="lead">
                Son 7 günün ortalaması: protein <b>{int(sum.macros.protein)} g</b> ({pct(sum.macros.proteinPct)}), yağ <b>{int(sum.macros.fat)} g</b> (
                {pct(sum.macros.fatPct)}), karbonhidrat <b>{int(sum.macros.carbs)} g</b> ({pct(sum.macros.carbsPct)}). Yüzdeler, kalorinin hangi makrodan geldiğini gösterir.
                {goals.protein_goal ? ` Protein hedefi ${int(goals.protein_goal)} g.` : ''}
              </p>
              <div className="legend">
                <span style={{ ['--c' as string]: 'var(--protein)' }}>Protein</span>
                <span style={{ ['--c' as string]: 'var(--fat)' }}>Yağ</span>
                <span style={{ ['--c' as string]: 'var(--carbs)' }}>Karbonhidrat</span>
              </div>
              <MacroChart data={rows} />
            </section>

            <section className="section">
              <h2>Günlük kayıtlar</h2>
              <div className="table-wrap">
                <table>
                  <thead>
                    <tr>
                      <th>Tarih</th>
                      <th>Kilo (kg)</th>
                      <th>Adım</th>
                      <th>Kalori</th>
                      <th>Protein</th>
                      <th>Yağ</th>
                      <th>Karb.</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[...rows].reverse().map((e) => (
                      <tr key={e.day}>
                        <td>{dateShort(e.day)}</td>
                        <td>{kg(e.weight)}</td>
                        <td>{int(e.steps)}</td>
                        <td>{int(e.calories)}</td>
                        <td>{int(e.protein)}</td>
                        <td>{int(e.fat)}</td>
                        <td>{int(e.carbs)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          </>
        )}
      </main>
    </>
  );
}
