import Link from "next/link"
import { notFound } from "next/navigation"

import { getClassHomeworkInsights, getClassSchedule, getClassStudents } from "@/modules/classes/data-access"
import { ScheduleView } from "@/modules/classes/components/schedule-view"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatDate } from "@/shared/lib/utils"

export const dynamic = "force-dynamic"

type SearchParams = { [key: string]: string | string[] | undefined }

const getParam = (params: SearchParams, key: string) => {
  const v = params[key]
  return Array.isArray(v) ? v[0] : v
}

const formatNumber = (v: number | null, digits = 1) => {
  if (typeof v !== "number" || Number.isNaN(v)) return "-"
  return v.toFixed(digits)
}

export default async function ClassDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>
  searchParams: Promise<SearchParams>
}) {
  const { id } = await params
  const sp = await searchParams
  const hw = getParam(sp, "hw")
  const hwFilter = hw === "active" || hw === "overdue" ? hw : "all"

  const [insights, students, schedule] = await Promise.all([
    getClassHomeworkInsights({ classId: id, limit: 50 }),
    getClassStudents({ classId: id }),
    getClassSchedule({ classId: id }),
  ])

  if (!insights) return notFound()

  const latest = insights.latest
  const filteredAssignments = insights.assignments.filter((a) => {
    if (hwFilter === "all") return true
    if (hwFilter === "overdue") return a.isOverdue
    if (hwFilter === "active") return a.isActive
    return true
  })
  const hasAssignments = filteredAssignments.length > 0
  const scheduleBuilderClasses = [
    {
      id: insights.class.id,
      name: insights.class.name,
      grade: insights.class.grade,
      homeroom: insights.class.homeroom ?? null,
      room: insights.class.room ?? null,
      studentCount: insights.studentCounts.total,
    },
  ]

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <Button asChild variant="outline" size="sm">
              <Link href="/teacher/classes/my">Back</Link>
            </Button>
            <Badge variant="secondary">{insights.class.grade}</Badge>
            <Badge variant="outline">{insights.studentCounts.total} students</Badge>
          </div>
          <h2 className="text-2xl font-bold tracking-tight">{insights.class.name}</h2>
          <div className="text-sm text-muted-foreground">
            {insights.class.room ? `Room: ${insights.class.room}` : "Room: Not set"}
            {insights.class.homeroom ? ` · Homeroom: ${insights.class.homeroom}` : null}
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <Button asChild variant="outline">
            <Link href={`/teacher/classes/students?classId=${encodeURIComponent(insights.class.id)}`}>Students</Link>
          </Button>
          <Button asChild variant="outline">
            <Link href={`/teacher/classes/schedule?classId=${encodeURIComponent(insights.class.id)}`}>Schedule</Link>
          </Button>
          <Button asChild variant="outline">
            <Link href={`/teacher/classes/insights?classId=${encodeURIComponent(insights.class.id)}`}>Insights</Link>
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Students</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{insights.studentCounts.total}</div>
            <div className="text-xs text-muted-foreground">
              Active {insights.studentCounts.active} · Inactive {insights.studentCounts.inactive}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Schedule items</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{schedule.length}</div>
            <div className="text-xs text-muted-foreground">Weekly timetable entries</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Assignments</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{insights.assignments.length}</div>
            <div className="text-xs text-muted-foreground">{latest ? `Latest ${formatDate(latest.createdAt)}` : "No homework yet"}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Overall avg</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatNumber(insights.overallScores.avg, 1)}</div>
            <div className="text-xs text-muted-foreground">
              Median {formatNumber(insights.overallScores.median, 1)} · Count {insights.overallScores.count}
            </div>
          </CardContent>
        </Card>
      </div>

      {latest ? (
        <Card>
          <CardHeader className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
            <div>
              <CardTitle className="text-base">Latest homework</CardTitle>
              <div className="mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
                <span className="font-medium text-foreground">{latest.title}</span>
                <Badge variant="outline" className="capitalize">
                  {latest.status}
                </Badge>
                <span>·</span>
                <span>{formatDate(latest.createdAt)}</span>
                {latest.dueAt ? (
                  <>
                    <span>·</span>
                    <span>Due {formatDate(latest.dueAt)}</span>
                  </>
                ) : null}
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button asChild variant="outline" size="sm">
                <Link href={`/teacher/homework/assignments/${latest.assignmentId}`}>Open</Link>
              </Button>
              <Button asChild variant="outline" size="sm">
                <Link href={`/teacher/homework/assignments/${latest.assignmentId}/submissions`}>Submissions</Link>
              </Button>
            </div>
          </CardHeader>
          <CardContent className="grid gap-4 md:grid-cols-5">
            <div>
              <div className="text-sm text-muted-foreground">Targeted</div>
              <div className="text-lg font-semibold">{latest.targetCount}</div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground">Submitted</div>
              <div className="text-lg font-semibold">{latest.submittedCount}</div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground">Graded</div>
              <div className="text-lg font-semibold">{latest.gradedCount}</div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground">Average</div>
              <div className="text-lg font-semibold">{formatNumber(latest.scoreStats.avg, 1)}</div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground">Median</div>
              <div className="text-lg font-semibold">{formatNumber(latest.scoreStats.median, 1)}</div>
            </div>
          </CardContent>
        </Card>
      ) : null}

      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">Students (preview)</CardTitle>
            <Button asChild variant="outline" size="sm">
              <Link href={`/teacher/classes/students?classId=${encodeURIComponent(insights.class.id)}`}>View all</Link>
            </Button>
          </CardHeader>
          <CardContent>
            {students.length === 0 ? (
              <div className="text-sm text-muted-foreground">No students enrolled.</div>
            ) : (
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {students.slice(0, 8).map((s) => (
                      <TableRow key={s.id}>
                        <TableCell className="font-medium">{s.name}</TableCell>
                        <TableCell className="text-muted-foreground">{s.email}</TableCell>
                        <TableCell>
                          <Badge variant="outline" className="capitalize">
                            {s.status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">Schedule</CardTitle>
            <Button asChild variant="outline" size="sm">
              <Link href={`/teacher/classes/schedule?classId=${encodeURIComponent(insights.class.id)}`}>View all</Link>
            </Button>
          </CardHeader>
          <CardContent>
            <ScheduleView schedule={schedule} classes={scheduleBuilderClasses} />
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
          <CardTitle className="text-base">Homework history</CardTitle>
          <div className="flex flex-wrap items-center gap-2">
            <Button asChild size="sm" variant={hwFilter === "all" ? "secondary" : "outline"}>
              <Link href={`/teacher/classes/my/${encodeURIComponent(insights.class.id)}`}>All</Link>
            </Button>
            <Button asChild size="sm" variant={hwFilter === "active" ? "secondary" : "outline"}>
              <Link href={`/teacher/classes/my/${encodeURIComponent(insights.class.id)}?hw=active`}>Active</Link>
            </Button>
            <Button asChild size="sm" variant={hwFilter === "overdue" ? "secondary" : "outline"}>
              <Link href={`/teacher/classes/my/${encodeURIComponent(insights.class.id)}?hw=overdue`}>Overdue</Link>
            </Button>
            <Button asChild variant="outline" size="sm">
              <Link href={`/teacher/homework/assignments?classId=${encodeURIComponent(insights.class.id)}`}>Open list</Link>
            </Button>
            <Button asChild size="sm">
              <Link href={`/teacher/homework/assignments/create?classId=${encodeURIComponent(insights.class.id)}`}>New homework</Link>
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {!hasAssignments ? (
            <div className="text-sm text-muted-foreground">No homework assignments yet.</div>
          ) : (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Assignment</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Due</TableHead>
                    <TableHead className="text-right">Targeted</TableHead>
                    <TableHead className="text-right">Submitted</TableHead>
                    <TableHead className="text-right">Graded</TableHead>
                    <TableHead className="text-right">Avg</TableHead>
                    <TableHead className="text-right">Median</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredAssignments.map((a) => (
                    <TableRow key={a.assignmentId}>
                      <TableCell className="font-medium">
                        <Link href={`/teacher/homework/assignments/${a.assignmentId}`} className="hover:underline">
                          {a.title}
                        </Link>
                        <div className="text-xs text-muted-foreground">Created {formatDate(a.createdAt)}</div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="capitalize">
                          {a.status}
                        </Badge>
                      </TableCell>
                      <TableCell>{a.dueAt ? formatDate(a.dueAt) : "-"}</TableCell>
                      <TableCell className="text-right">{a.targetCount}</TableCell>
                      <TableCell className="text-right">{a.submittedCount}</TableCell>
                      <TableCell className="text-right">{a.gradedCount}</TableCell>
                      <TableCell className="text-right">{formatNumber(a.scoreStats.avg, 1)}</TableCell>
                      <TableCell className="text-right">{formatNumber(a.scoreStats.median, 1)}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
