import Link from "next/link";
import { db } from "@/db";
import {
  users, exams, examAttempts, examQuestions, scores, attendance, discipline,
  certificates, announcements, schedules, books, grades, classes,
} from "@/db/schema";
import { eq, and, asc, desc, sql, inArray } from "drizzle-orm";
import {
  GraduationCap, FileQuestion, CalendarDays, ShieldCheck, Award, Megaphone,
  TrendingUp, BellRing, BookOpenText,
} from "lucide-react";
import { StatCard, Card, PageTitle, SectionTitle, Table, Th, Td, Empty, Badge } from "@/components/ui";
import { requireRole } from "@/lib/auth";
import { faNum, jKey, J_MONTHS, WEEKDAYS, g2j, fmtJ, fmtJFull } from "@/lib/jalali";

export const metadata = { title: "پنل دانش‌آموز" };

export default async function StudentDashboard({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
  const s = await requireRole("student");
  const sp = await searchParams;
  const me = (await db.select().from(users).where(eq(users.id, s.id)).limit(1))[0];
  const gradeName = me?.gradeId ? (await db.select().from(grades).where(eq(grades.id, me.gradeId)).limit(1))[0]?.name : "—";
  const className = me?.classId ? (await db.select().from(classes).where(eq(classes.id, me.classId)).limit(1))[0]?.name : "—";

  const [myScores, myAtt, myDis, myCerts, annList, schedRows] = await Promise.all([
    db.select({ s: scores, book: books.title }).from(scores).innerJoin(books, eq(scores.bookId, books.id)).where(eq(scores.studentId, s.id)).orderBy(asc(scores.jdate)),
    db.select().from(attendance).where(eq(attendance.studentId, s.id)).orderBy(desc(attendance.jdate)),
    db.select().from(discipline).where(eq(discipline.studentId, s.id)).orderBy(desc(discipline.createdAt)).limit(10),
    db.select().from(certificates).where(eq(certificates.studentId, s.id)).orderBy(desc(certificates.createdAt)),
    db.select().from(announcements).where(eq(announcements.active, true)).orderBy(desc(announcements.createdAt)).limit(5),
    me?.classId ? db.select().from(schedules).where(eq(schedules.classId, me.classId)) : Promise.resolve([]),
  ]);

  // آزمون‌های فعال مرتبط با پایهٔ من
  const allExams = await db.select().from(exams).where(eq(exams.active, true)).orderBy(desc(exams.startAt));
  const now = Date.now();
  const myAttempts = await db.select().from(examAttempts).where(eq(examAttempts.studentId, s.id));
  const attempted = new Set(myAttempts.map((a) => a.examId));
  const questionCounts = await db.select({ examId: examQuestions.examId, c: sql<number>`count(*)::int` }).from(examQuestions).groupBy(examQuestions.examId);
  const qMap = new Map(questionCounts.map((x) => [x.examId, x.c]));
  const available = allExams.filter((e) => {
    if (attempted.has(e.id)) return false;
    if (e.gradeId && me?.gradeId && e.gradeId !== me.gradeId) return false;
    const start = e.startAt.getTime();
    return now >= start && now <= start + (e.durationMin + 8 * 60) * 60_000;
  });

  // محاسبات کارنامه
  const avgOf = (list: typeof myScores) => list.length ? Math.round((list.reduce((a, b) => a + b.s.score, 0) / list.length) * 10) / 10 : null;
  const period = sp.period ?? "all";
  const [jy, jm] = jKey().split("-").map(Number);
  const filtered = myScores.filter((x) => {
    if (period === "all") return true;
    const [yy, mm] = x.s.jdate.split("-").map(Number);
    if (period === "month") return yy === jy && mm === jm;
    if (period === "term2") return mm >= 1 && mm <= 6;
    if (period === "term2s") return mm >= 7;
    return true;
  });
  const daily = filtered.filter((x) => x.s.kind === "daily");
  const monthly = filtered.filter((x) => x.s.kind === "monthly");
  const avgAll = avgOf(filtered);
  const absentCount = myAtt.filter((a) => a.status === "absent").length;
  const lateCount = myAtt.filter((a) => a.status === "late").length;
  const presentPct = myAtt.length ? Math.round(((myAtt.length - absentCount) / myAtt.length) * 100) : 100;
  const disScore = myDis.reduce((acc, d) => acc + (d.kind === "positive" ? d.points : -d.points), 0);

  // گروه‌بندی نمرات بر اساس کتاب
  const byBook = new Map<string, { daily: number[]; monthly: number[] }>();
  for (const x of filtered) {
    const cur = byBook.get(x.book) ?? { daily: [], monthly: [] };
    cur[x.s.kind === "daily" ? "daily" : "monthly"].push(x.s.score);
    byBook.set(x.book, cur);
  }

  return (
    <div>
      <PageTitle title={`سلام ${me?.firstName}!`} subtitle={`${gradeName} — کلاس ${className}`} icon={<GraduationCap size={22} />} />

      {/* آمار سریع */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <StatCard label="میانگین نمرات" value={avgAll ?? "—"} icon={<TrendingUp size={20} />} />
        <StatCard label="درصد حضور" value={presentPct} icon={<CalendarDays size={20} />} tone="blue" />
        <StatCard label="غیبت / دیرکرد" value={`${faNum(absentCount)}/${faNum(lateCount)}`} icon={<ShieldCheck size={20} />} tone="amber" />
        <StatCard label="امتیاز انضباط" value={faNum(disScore)} icon={<Award size={20} />} tone="rose" />
      </div>

      {/* آزمون‌های فعال */}
      {available.length > 0 && (
        <Card className="mt-6 border-2 !border-amber-300 bg-amber-50/60 p-5">
          <div className="mb-3 flex items-center gap-2 text-sm font-black text-amber-900"><BellRing size={17} className="anim-pulse-soft rounded-full" /> آزمون فعال — فرصت محدود!</div>
          <div className="grid gap-2 sm:grid-cols-2">
            {available.map((e) => (
              <Link key={e.id} href={`/student/exam/${e.id}`}
                className="flex items-center justify-between rounded-xl border border-amber-300 bg-white px-4 py-3 shadow-sm transition hover:border-amber-500 hover:bg-amber-50">
                <div>
                  <div className="text-sm font-black text-emerald-950">{e.title}</div>
                  <div className="mt-0.5 text-[11px] text-emerald-800/60">{faNum(qMap.get(e.id) ?? 0)} سؤال — {faNum(e.durationMin)} دقیقه — شروع {fmtJFull(e.startAt)}</div>
                </div>
                <span className="btn-gold rounded-xl px-3.5 py-2 text-xs font-black text-white">شروع</span>
              </Link>
            ))}
          </div>
        </Card>
      )}

      {/* کارنامه */}
      <SectionTitle action={
        <div className="flex gap-1.5">
          {[["all", "سالانه"], ["month", "ماه جاری"], ["term2", "نیمسال اول"], ["term2s", "نیمسال دوم"]].map(([k, l]) => (
            <Link key={k} href={`/student?period=${k}`} className={`rounded-full px-3 py-1 text-[11px] font-bold ${period === k ? "bg-emerald-700 text-white" : "bg-emerald-900/5 text-emerald-800"}`}>{l}</Link>
          ))}
        </div>
      }><span className="flex items-center gap-2"><BookOpenText size={17} className="text-emerald-700" /> کارنامهٔ من</span></SectionTitle>
      <Card className="p-4">
        {byBook.size === 0 ? <Empty text="هنوز نمره‌ای ثبت نشده است." /> : (
          <Table>
            <thead><tr><Th>درس</Th><Th>میانگین روزانه</Th><Th>نمرهٔ ماهانه</Th><Th>وضعیت</Th></tr></thead>
            <tbody>
              {[...byBook.entries()].map(([book, v]) => {
                const dAvg = v.daily.length ? Math.round((v.daily.reduce((a, b) => a + b, 0) / v.daily.length) * 10) / 10 : null;
                const mAvg = v.monthly.length ? Math.round((v.monthly.reduce((a, b) => a + b, 0) / v.monthly.length) * 10) / 10 : null;
                const total = mAvg ?? dAvg ?? 0;
                return (
                  <tr key={book}>
                    <Td className="font-extrabold">{book}</Td>
                    <Td>{dAvg !== null ? faNum(dAvg) : "—"}</Td>
                    <Td>{mAvg !== null ? faNum(mAvg) : "—"}</Td>
                    <Td>{total >= 15 ? <Badge tone="green">خیلی خوب</Badge> : total >= 10 ? <Badge tone="amber">قابل قبول</Badge> : <Badge tone="red">نیاز به تلاش</Badge>}</Td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        )}
        <p className="mt-3 text-[11px] text-emerald-800/50">نمرهٔ روزانه: {faNum(daily.length)} مورد — نمرهٔ ماهانه: {faNum(monthly.length)} مورد در این بازه</p>
      </Card>

      <div className="mt-6 grid gap-6 lg:grid-cols-2">
        {/* حضور و غیاب */}
        <Card className="p-5">
          <SectionTitle><span className="flex items-center gap-2"><CalendarDays size={16} className="text-emerald-700" /> حضور و غیاب ({faNum(myAtt.length)} روز)</span></SectionTitle>
          <div className="mb-3 flex gap-2">
            <Badge tone="green">حاضر: {faNum(myAtt.filter(a=>a.status==="present").length)}</Badge>
            <Badge tone="red">غایب: {faNum(absentCount)}</Badge>
            <Badge tone="amber">مرخصی: {faNum(myAtt.filter(a=>a.status==="leave").length)}</Badge>
            <Badge tone="gray">دیرکرد: {faNum(lateCount)}</Badge>
          </div>
          {myAtt.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {myAtt.slice(0, 40).map((a) => (
                <span key={a.id} title={faNum(a.jdate)} className={`size-3 rounded-full ${a.status === "present" ? "bg-emerald-500" : a.status === "absent" ? "bg-red-500" : a.status === "leave" ? "bg-amber-400" : "bg-slate-400"}`} />
              ))}
            </div>
          )}
        </Card>

        {/* انضباط */}
        <Card className="p-5">
          <SectionTitle><span className="flex items-center gap-2"><ShieldCheck size={16} className="text-emerald-700" /> انضباط من</span></SectionTitle>
          {myDis.length === 0 ? <Empty text="موردی ثبت نشده." /> : (
            <ul className="space-y-1.5">
              {myDis.map((d) => (
                <li key={d.id} className="flex items-center justify-between gap-2 rounded-xl bg-emerald-50/70 px-3 py-2 text-xs">
                  <span>{d.note} <span className="text-[10px] text-emerald-800/50">— {fmtJ(d.createdAt)}</span></span>
                  <Badge tone={d.kind === "positive" ? "green" : "red"}>{d.kind === "positive" ? "+" : "-"}{faNum(d.points)}</Badge>
                </li>
              ))}
            </ul>
          )}
        </Card>

        {/* لوح‌های سپاس */}
        <Card className="p-5">
          <SectionTitle><span className="flex items-center gap-2"><Award size={16} className="text-amber-600" /> لوح‌های سپاس و افتخارات</span></SectionTitle>
          {myCerts.length === 0 ? <Empty text="به زودی... به تلاشت ادامه بده!" /> : (
            <div className="grid gap-2 sm:grid-cols-2">
              {myCerts.map((c) => (
                <Link key={c.id} href={`/certificate/${c.id}`} className="group rounded-xl border-2 border-amber-200 bg-gradient-to-br from-amber-50 to-cream-50 p-3.5 transition hover:border-amber-400 hover:shadow-md">
                  <div className="flex items-center gap-2 text-sm font-black text-amber-900"><Award size={16} /> لوح سپاس — {c.theme}</div>
                  {c.note && <div className="mt-1 text-[11px] text-amber-800/70">{c.note}</div>}
                  <div className="mt-1.5 text-[10px] text-amber-700/60">{fmtJ(c.createdAt)} — مشاهده و چاپ ←</div>
                </Link>
              ))}
            </div>
          )}
        </Card>

        {/* برنامهٔ هفتگی */}
        <Card className="p-5 lg:col-span-2">
          <SectionTitle><span className="flex items-center gap-2"><CalendarDays size={16} className="text-emerald-700" /> برنامهٔ هفتگی کلاس من</span></SectionTitle>
          {schedRows.length === 0 ? <Empty text="برنامهٔ این کلاس هنوز ثبت نشده." /> : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[640px] border-collapse text-center">
                <thead>
                  <tr>
                    <th className="p-2 text-[11px] font-extrabold text-emerald-900/60">زنگ</th>
                    {[0, 1, 2, 3, 4, 5].map((d) => <th key={d} className="p-2 text-[11px] font-extrabold text-emerald-900/80">{WEEKDAYS[d]}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {[1, 2, 3, 4, 5, 6].map((p) => (
                    <tr key={p}>
                      <td className="p-1.5 text-[11px] font-black text-emerald-900/50">{faNum(p)}</td>
                      {[0, 1, 2, 3, 4, 5].map((d) => {
                        const subj = schedRows.find((x) => x.day === d && x.period === p)?.subject ?? "—";
                        return <td key={d} className="p-1.5"><span className={`inline-block w-full rounded-lg px-1 py-1.5 text-[11px] font-bold ${subj === "—" ? "text-emerald-900/25" : "bg-emerald-50 text-emerald-900 ring-1 ring-emerald-900/8"}`}>{subj}</span></td>;
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Card>
      </div>

      {/* اعلانات */}
      <Card className="mt-6 p-5">
        <SectionTitle><span className="flex items-center gap-2"><Megaphone size={16} className="text-amber-600" /> اعلانات مدرسه</span></SectionTitle>
        {annList.length === 0 ? <Empty text="اعلانی نیست." /> : (
          <ul className="space-y-2">
            {annList.map((a) => (
              <li key={a.id} className="rounded-xl border border-emerald-900/10 bg-white px-4 py-3">
                <div className="text-sm font-black text-emerald-950">{a.title} <span className="mr-2 text-[10px] font-bold text-emerald-800/50">{fmtJ(a.createdAt)}</span></div>
                <p className="mt-1 text-xs leading-6 text-emerald-800/75">{a.body}</p>
              </li>
            ))}
          </ul>
        )}
      </Card>
    </div>
  );
}
