import Link from 'next/link';
import { requireAdmin, normalizeProfile } from '@/lib/auth';
import { goalsOf } from '@/lib/data';
import { computeSummary, type Entry } from '@/lib/stats';
import { kg, dateMid, signed } from '@/lib/format';
import TopBar from '@/components/TopBar';
import NewStudentForm from './NewStudentForm';

export const dynamic = 'force-dynamic';

export default async function AdminPage() {
  const { supabase, me } = await requireAdmin();
  const [{ data: profs }, { data: rows }] = await Promise.all([
    supabase.from('profiles').select('*').eq('role', 'student').order('full_name'),
    supabase.from('entries').select('student_id, day, weight, steps, calories, protein, fat, carbs').order('day'),
  ]);
  const byStudent = new Map<string, Entry[]>();
  for (const r of rows ?? []) {
    const list = byStudent.get(r.student_id) ?? [];
    const n = (v: unknown) => (v === null ? null : Number(v));
    list.push({ day: r.day, weight: n(r.weight), steps: n(r.steps), calories: n(r.calories), protein: n(r.protein), fat: n(r.fat), carbs: n(r.carbs) });
    byStudent.set(r.student_id, list);
  }
  const students = (profs ?? []).map((p) => {
    const s = normalizeProfile(p);
    return { s, sum: computeSummary(byStudent.get(s.id) ?? [], goalsOf(s)) };
  });

  return (
    <>
      <TopBar me={me} />
      <main className="wrap">
        <div className="row between">
          <h1>Öğrenciler</h1>
          <span className="muted">{students.length} kişi</span>
        </div>

        <section className="card">
          {students.length === 0 ? (
            <p className="muted" style={{ margin: 0 }}>Henüz öğrenci yok. Aşağıdan ilk öğrenciyi ekle.</p>
          ) : (
            <div className="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Ad</th>
                    <th>Güncel</th>
                    <th>Verilen</th>
                    <th>Hedefe kalan</th>
                    <th>Son 7 gün</th>
                    <th>Son kayıt</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {students.map(({ s, sum }) => (
                    <tr key={s.id} className="link-row">
                      <td>
                        <Link href={`/admin/ogrenci/${s.id}`}>{s.full_name || s.email}</Link>
                      </td>
                      <td>{sum ? `${kg(sum.current)} kg` : '—'}</td>
                      <td className="accent">{sum ? `${kg(sum.lost)} kg` : '—'}</td>
                      <td>{sum?.remaining != null ? `${kg(sum.remaining)} kg` : '—'}</td>
                      <td className={sum?.lastWeekChange == null ? '' : sum.lastWeekChange < 0 ? 'good' : sum.lastWeekChange > 0 ? 'bad' : ''}>
                        {sum?.lastWeekChange != null ? `${signed(sum.lastWeekChange)} kg` : '—'}
                      </td>
                      <td className="muted">{sum ? dateMid(sum.lastDay) : 'Kayıt yok'}</td>
                      <td>
                        <Link href={`/ogrenci/${s.id}`}>Sayfası</Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </section>

        <section className="card">
          <h2>Yeni öğrenci</h2>
          <p className="muted" style={{ margin: '-6px 0 16px' }}>
            Öğrenciye bir davet e-postası gider. Bağlantıya tıklayınca yalnızca kendi değişim sayfasını görür.
          </p>
          <NewStudentForm />
        </section>
      </main>
    </>
  );
}
