import Link from "next/link";
import { db } from "@/db";
import { users, classes, attendance } from "@/db/schema";
import { eq, and, asc, sql } from "drizzle-orm";
import { Card, SectionTitle, Table, Th, Td, Empty, Badge } from "@/components/ui";
import { AttendanceRoster } from "@/components/attendance-roster";
import { faNum, jKey, g2j, J_MONTHS } from "@/lib/jalali";

export async function AttendanceView({ basePath, sp }: { basePath: string; sp: Record<string, string | undefined> }) {
  const classList = await db.select().from(classes).orderBy(asc(classes.id));
  const selClass = Number(sp.class ?? classList[0]?.id ?? 0);
  const jdate = sp.date ?? jKey();

  const roster = selClass
    ? await db.select().from(users).where(and(eq(users.classId, selClass), eq(users.role, "student"))).orderBy(asc(users.lastName))
    : [];
  const today = jKey();
  const existing = await db.select().from(attendance).where(eq(attendance.jdate, jdate));
  const existingMap: Record<number, string> = {};
  for (const a of existing) existingMap[a.studentId] = a.status;

  const stats = await db
    .select({ studentId: attendance.studentId, status: attendance.status, c: sql<number>`count(*)::int` })
    .from(attendance).groupBy(attendance.studentId, attendance.status);
  const [{ c: totalDays }] = await db.select({ c: sql<number>`count(distinct ${attendance.jdate})::int` }).from(attendance);

  return (
    <div>
      <div className="no-print">
        <div className="mb-3 flex flex-wrap gap-1.5">
          {classList.map((c) => (
            <Link key={c.id} href={`${basePath}?class=${c.id}&date=${jdate}`}
              className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition ${selClass === c.id ? "bg-gradient-to-l from-emerald-700 to-emerald-900 text-white shadow" : "bg-emerald-900/5 text-emerald-900 hover:bg-emerald-900/10"}`}>
              {c.name}
            </Link>
          ))}
        </div>
        <div className="mb-4 flex flex-wrap gap-1.5">
          {[0, 1, 2, 3, 4, 5, 6].map((off) => {
            const d = new Date(Date.now() - off * 86400000);
            const key = jKey(d);
            const [, jm, jd] = g2j(d.getFullYear(), d.getMonth() + 1, d.getDate());
            return (
              <Link key={off} href={`${basePath}?class=${selClass}&date=${key}`}
                className={`rounded-xl px-3 py-1.5 text-[11px] font-bold ${jdate === key ? "bg-amber-500 text-white shadow" : "bg-amber-50 text-amber-900 hover:bg-amber-100"}`}>
                {off === 0 ? "امروز" : `${faNum(jd)} ${J_MONTHS[jm - 1]}`}
              </Link>
            );
          })}
        </div>
      </div>

      <Card className="p-5">
        <SectionTitle action={
          <Badge tone="amber">تاریخ: <span dir="ltr" className="mr-1">{faNum(jdate)}</span>{jdate === today && " (امروز)"}</Badge>
        }>ثبت حضور و غیاب — کلاس {classList.find((c) => c.id === selClass)?.name ?? ""}</SectionTitle>
        {roster.length === 0 ? <Empty text="برای این کلاس دانش‌آموزی ثبت نشده." /> : (
          <AttendanceRoster classId={selClass} jdate={jdate}
            students={roster.map((s) => ({ id: s.id, name: `${s.lastName}، ${s.firstName}` }))}
            existing={existingMap} />
        )}
      </Card>

      <Card className="mt-6 p-5">
        <SectionTitle>گزارش تجمیعی حضور ({faNum(totalDays)} روز ثبت‌شده)</SectionTitle>
        {roster.length === 0 ? <Empty text="—" /> : (
          <Table>
            <thead><tr><Th>دانش‌آموز</Th><Th>حاضر</Th><Th>غایب</Th><Th>مرخصی</Th><Th>دیرکرد</Th><Th>درصد حضور</Th></tr></thead>
            <tbody>
              {roster.map((st) => {
                const sOf = (k: string) => stats.find((s) => s.studentId === st.id && s.status === k)?.c ?? 0;
                const total = sOf("present") + sOf("absent") + sOf("leave") + sOf("late");
                const pct = total ? Math.round(((sOf("present") + sOf("late")) / total) * 100) : 100;
                return (
                  <tr key={st.id}>
                    <Td className="font-bold">{st.lastName}، {st.firstName}</Td>
                    <Td className="text-emerald-700">{faNum(sOf("present"))}</Td>
                    <Td className="text-red-600">{faNum(sOf("absent"))}</Td>
                    <Td className="text-amber-600">{faNum(sOf("leave"))}</Td>
                    <Td className="text-slate-500">{faNum(sOf("late"))}</Td>
                    <Td>
                      <div className="flex items-center gap-2">
                        <div className="h-2.5 w-24 overflow-hidden rounded-full bg-emerald-900/10">
                          <div className={`h-full rounded-full ${pct >= 90 ? "bg-emerald-600" : pct >= 75 ? "bg-amber-500" : "bg-red-500"}`} style={{ width: `${pct}%` }} />
                        </div>
                        <span className="text-xs font-black" dir="ltr">{faNum(pct)}٪</span>
                      </div>
                    </Td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        )}
      </Card>
    </div>
  );
}
