import Link from "next/link";
import { db } from "@/db";
import { grades, books, lessons, questions, exams, examQuestions, examAttempts, users } from "@/db/schema";
import { eq, asc, desc, sql } from "drizzle-orm";
import { FileQuestion, PlusCircle, Trash2, ToggleRight, BarChart3, Crown, Medal, Trophy } from "lucide-react";
import { Card, SectionTitle, Table, Th, Td, Empty, inputCls, selectCls, Field, Badge, DiffBadge, TypeBadge } from "@/components/ui";
import { ActionForm, SubmitBtn, GhostBtn, ConfirmSubmit } from "@/components/ui-client";
import { saveExam, toggleExam, deleteExam } from "@/lib/actions";
import { faNum, fmtJFull } from "@/lib/jalali";

export async function ExamView({ basePath, teacherId, sp }: {
  basePath: string; teacherId: number | null; sp: Record<string, string | undefined>;
}) {
  const selGrade = Number(sp.grade ?? 0);
  const selBook = Number(sp.book ?? 0);
  const selLesson = Number(sp.lesson ?? 0);
  const resultsId = Number(sp.results ?? 0);

  const [gradeList, bookList, lessonList] = await Promise.all([
    db.select().from(grades).orderBy(asc(grades.level)),
    db.select().from(books).orderBy(asc(books.id)),
    db.select().from(lessons).orderBy(asc(lessons.sort)),
  ]);
  const booksOfGrade = selGrade ? bookList.filter((b) => b.gradeId === selGrade) : [];
  const lessonsOfBook = selBook ? lessonList.filter((l) => l.bookId === selBook) : [];
  const qList = selLesson
    ? await db.select().from(questions).where(eq(questions.lessonId, selLesson)).orderBy(asc(questions.id)).limit(60)
    : [];

  let examList = await db
    .select({ e: exams, teacherName: sql<string>`concat(${users.firstName}, ' ', ${users.lastName})` })
    .from(exams).innerJoin(users, eq(exams.teacherId, users.id)).orderBy(desc(exams.createdAt));
  if (teacherId) examList = examList.filter((x) => x.e.teacherId === teacherId);

  const attemptCounts = await db.select({ examId: examAttempts.examId, c: sql<number>`count(*)::int` }).from(examAttempts).groupBy(examAttempts.examId);
  const countMap = new Map(attemptCounts.map((a) => [a.examId, a.c]));

  const results = resultsId
    ? await db.select({ a: examAttempts, fn: users.firstName, ln: users.lastName })
        .from(examAttempts).innerJoin(users, eq(examAttempts.studentId, users.id))
        .where(eq(examAttempts.examId, resultsId)).orderBy(desc(examAttempts.score))
    : [];
  const resultExam = resultsId ? (await db.select().from(exams).where(eq(exams.id, resultsId)).limit(1))[0] : null;

  const qs = (obj: Record<string, string | number>) => {
    const cur = { grade: selGrade, book: selBook, lesson: selLesson };
    const n = { ...cur, ...obj };
    const parts = Object.entries(n).filter(([, v]) => String(v)).map(([k, v]) => `${k}=${v}`);
    return `${basePath}${parts.length ? "?" + parts.join("&") : ""}`;
  };

  return (
    <div>
      {/* ساخت آزمون */}
      <Card className="mb-6 p-6">
        <details open={selLesson > 0}>
          <summary className="flex cursor-pointer items-center gap-2 text-sm font-extrabold text-emerald-950">
            <PlusCircle size={17} className="text-emerald-700" /> ساخت آزمون جدید از بانک سوالات
          </summary>
          <div className="mt-4">
            <p className="mb-3 text-xs text-emerald-800/60">۱) پایه، کتاب و درس را انتخاب کنید تا سؤالات نمایش داده شود؛ ۲) سؤال‌های دلخواه را تیک بزنید؛ ۳) زمان شروع و مدت را تعیین و آزمون را ایجاد کنید.</p>
            <div className="mb-3 flex flex-wrap gap-1.5">
              {gradeList.map((g) => (
                <Link key={g.id} href={qs({ grade: g.id, book: 0, lesson: 0 })} className={`rounded-full px-3 py-1 text-xs font-bold ${selGrade === g.id ? "bg-emerald-700 text-white" : "bg-emerald-900/5 text-emerald-900"}`}>{g.name}</Link>
              ))}
            </div>
            {selGrade > 0 && (
              <div className="mb-3 flex flex-wrap gap-1.5">
                {booksOfGrade.map((b) => (
                  <Link key={b.id} href={qs({ book: b.id, lesson: 0 })} className={`rounded-full px-3 py-1 text-xs font-bold ${selBook === b.id ? "bg-amber-500 text-white" : "bg-amber-50 text-amber-900"}`}>{b.title}</Link>
                ))}
              </div>
            )}
            {selBook > 0 && (
              <div className="mb-4 flex flex-wrap gap-1.5">
                {lessonsOfBook.map((l) => (
                  <Link key={l.id} href={qs({ lesson: l.id })} className={`rounded-xl px-3 py-1.5 text-xs font-bold ${selLesson === l.id ? "bg-gradient-to-l from-emerald-700 to-emerald-900 text-white shadow" : "bg-emerald-50 text-emerald-800 ring-1 ring-emerald-900/8"}`}>{l.title}</Link>
                ))}
              </div>
            )}

            {selLesson > 0 && (
              <ActionForm action={saveExam}>
                <input type="hidden" name="gradeId" value={selGrade} />
                <input type="hidden" name="bookId" value={selBook} />
                <div className="mb-4 grid max-h-72 gap-2 overflow-y-auto rounded-xl border border-emerald-900/10 bg-emerald-50/40 p-3">
                  {qList.map((q) => (
                    <label key={q.id} className="flex cursor-pointer items-start gap-2.5 rounded-lg bg-white p-2.5 text-xs leading-6 shadow-sm ring-1 ring-emerald-900/5 transition hover:ring-emerald-500/40">
                      <input type="checkbox" name="qIds" value={q.id} className="mt-1 size-4 shrink-0 accent-emerald-700" />
                      <span className="flex-1">
                        <span className="font-bold">{q.text}</span>
                        {q.options && <span className="block text-[10px] text-emerald-700/60">{q.options.join(" | ")}</span>}
                      </span>
                      <span className="flex shrink-0 gap-1"><TypeBadge t={q.type} /><DiffBadge d={q.difficulty} /></span>
                    </label>
                  ))}
                </div>
                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                  <Field label="عنوان آزمون"><input name="title" required placeholder="مثال: آزمون فصل ۱ ریاضی" className={inputCls} /></Field>
                  <Field label="زمان شروع" hint="به وقت محلی">
                    <input name="startAt" type="datetime-local" required className={inputCls} />
                  </Field>
                  <Field label="مدت (دقیقه)"><input name="durationMin" type="number" min={5} defaultValue={30} required className={inputCls} dir="ltr" /></Field>
                  <div className="flex items-end"><SubmitBtn><FileQuestion size={16} /> ایجاد و فعال‌سازی آزمون</SubmitBtn></div>
                </div>
              </ActionForm>
            )}
          </div>
        </details>
      </Card>

      {/* نتایج آزمون */}
      {resultExam && (
        <Card className="mb-6 p-6">
          <SectionTitle><span className="flex items-center gap-2"><BarChart3 size={17} className="text-emerald-700" /> نتایج «{resultExam.title}»</span></SectionTitle>
          {results.length === 0 ? <Empty text="هنوز کسی در این آزمون شرکت نکرده." /> : (
            <Table>
              <thead><tr><Th>رتبه</Th><Th>دانش‌آموز</Th><Th>نمره از ۲۰</Th><Th>پاسخ صحیح</Th><Th>پایان</Th></tr></thead>
              <tbody>
                {results.map((r, i) => (
                  <tr key={r.a.id}>
                    <Td>
                      <span className="inline-flex items-center gap-1 font-black">
                        {i === 0 ? <Crown size={15} className="text-amber-500" /> : i === 1 ? <Medal size={15} className="text-slate-400" /> : i === 2 ? <Trophy size={15} className="text-amber-700" /> : null}
                        {faNum(i + 1)}
                      </span>
                    </Td>
                    <Td className="font-bold">{r.ln}، {r.fn}</Td>
                    <Td>
                      <span className={`rounded-full px-2.5 py-1 text-xs font-black ${(r.a.score ?? 0) >= 10 ? "bg-emerald-600 text-white" : "bg-red-100 text-red-700"}`}>
                        {r.a.score === null ? "در انتظار تصحیح" : faNum(r.a.score)}
                      </span>
                    </Td>
                    <Td>{faNum(r.a.correctCount)} از {faNum(r.a.totalCount)}</Td>
                    <Td className="text-xs text-emerald-800/60">{r.a.finishedAt ? fmtJFull(r.a.finishedAt) : "—"}</Td>
                  </tr>
                ))}
              </tbody>
            </Table>
          )}
          <div className="mt-3"><Link href={basePath} className="text-xs font-bold text-amber-700 hover:underline">← بستن نتایج</Link></div>
        </Card>
      )}

      {/* لیست آزمون‌ها */}
      <SectionTitle>آزمون‌های {teacherId ? "من" : "سامانه"}</SectionTitle>
      <Card className="p-4">
        {examList.length === 0 ? <Empty text="هنوز آزمونی ساخته نشده." /> : (
          <Table>
            <thead><tr><Th>عنوان</Th><Th>سازنده</Th><Th>شروع</Th><Th>مدت</Th><Th>شرکت‌کننده</Th><Th>وضعیت</Th><Th>عملیات</Th></tr></thead>
            <tbody>
              {examList.map(({ e, teacherName }) => (
                <tr key={e.id}>
                  <Td className="font-extrabold">{e.title}</Td>
                  <Td>{teacherName}</Td>
                  <Td className="whitespace-nowrap text-xs">{fmtJFull(e.startAt)}</Td>
                  <Td>{faNum(e.durationMin)} دقیقه</Td>
                  <Td><Badge tone="blue">{faNum(countMap.get(e.id) ?? 0)} نفر</Badge></Td>
                  <Td>{e.active ? <Badge tone="green">فعال</Badge> : <Badge tone="gray">غیرفعال</Badge>}</Td>
                  <Td>
                    <div className="flex flex-wrap gap-1.5">
                      <Link href={`${basePath}?results=${e.id}`} className="grid size-8 place-items-center rounded-lg bg-sky-100 text-sky-800 hover:bg-sky-200" title="نتایج"><BarChart3 size={14} /></Link>
                      <form action={toggleExam.bind(null, e.id)}><GhostBtn><ToggleRight size={13} />{e.active ? "غیرفعال" : "فعال"}</GhostBtn></form>
                      <form action={deleteExam.bind(null, e.id)}>
                        <ConfirmSubmit message={`حذف آزمون «${e.title}»؟`} className="grid size-8 place-items-center rounded-lg bg-red-100 text-red-700 hover:bg-red-200"><Trash2 size={14} /></ConfirmSubmit>
                      </form>
                    </div>
                  </Td>
                </tr>
              ))}
            </tbody>
          </Table>
        )}
      </Card>
    </div>
  );
}
