import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Progress } from "@/components/ui/progress";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { formatNumber, formatPercent } from "@/lib/format";
import { attendanceToneClass, scoreToneClass } from "@/lib/labels";
import type {
  AttendanceBreakdown,
  ClassReportRow,
  CourseReportRow,
  ScoreBucket,
} from "@/lib/queries/admin";

/** Per-class performance table. */
export function ClassReportTable({ rows }: { rows: ClassReportRow[] }) {
  if (rows.length === 0) {
    return (
      <EmptyState
        compact
        title="Belum ada kelas"
        description="Kelas yang kamu kelola akan muncul di sini beserta statistiknya."
      />
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Kelas</TableHead>
          <TableHead>Guru</TableHead>
          <TableHead className="text-right">Siswa</TableHead>
          <TableHead className="text-right">Kehadiran</TableHead>
          <TableHead className="text-right">Rata-rata Nilai</TableHead>
          <TableHead className="text-right">Penyelesaian</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((row) => (
          <TableRow key={row.id}>
            <TableCell>
              <span className="block font-medium text-primary">{row.name}</span>
              <span className="block text-xs text-tertiary">{row.code}</span>
            </TableCell>
            <TableCell className="text-xs">{row.teacherName}</TableCell>
            <TableCell className="text-right tabular-nums">{formatNumber(row.studentCount)}</TableCell>
            <TableCell className="text-right tabular-nums">
              {row.attendanceRate === null ? (
                <span className="text-tertiary">—</span>
              ) : (
                <span className={attendanceToneClass(row.attendanceRate)}>
                  {formatPercent(row.attendanceRate, 1)}
                </span>
              )}
            </TableCell>
            <TableCell className="text-right tabular-nums">
              {row.averageScore === null ? (
                <span className="text-tertiary">—</span>
              ) : (
                <span className={scoreToneClass(row.averageScore)}>
                  {formatPercent(row.averageScore, 1)}
                </span>
              )}
            </TableCell>
            <TableCell className="text-right tabular-nums">
              {formatPercent(row.completionPercent, 1)}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}

/** Per-course performance table. */
export function CourseReportTable({ rows }: { rows: CourseReportRow[] }) {
  if (rows.length === 0) {
    return (
      <EmptyState
        compact
        title="Belum ada kursus"
        description="Kursus yang kamu ampu akan muncul di sini beserta statistiknya."
      />
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Kursus</TableHead>
          <TableHead className="text-right">Terdaftar</TableHead>
          <TableHead className="text-right">Pelajaran</TableHead>
          <TableHead className="text-right">Tugas Terbit</TableHead>
          <TableHead className="text-right">Tingkat Pengumpulan</TableHead>
          <TableHead className="text-right">Rata-rata Nilai</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((row) => (
          <TableRow key={row.id}>
            <TableCell className="font-medium text-primary">{row.title}</TableCell>
            <TableCell className="text-right tabular-nums">{formatNumber(row.enrolledCount)}</TableCell>
            <TableCell className="text-right tabular-nums">{formatNumber(row.lessonCount)}</TableCell>
            <TableCell className="text-right tabular-nums">
              {formatNumber(row.publishedAssignments)}
            </TableCell>
            <TableCell className="text-right tabular-nums">
              {row.submissionRate === null ? (
                <span className="text-tertiary">—</span>
              ) : (
                formatPercent(row.submissionRate, 1)
              )}
            </TableCell>
            <TableCell className="text-right tabular-nums">
              {row.averageScore === null ? (
                <span className="text-tertiary">—</span>
              ) : (
                <span className={scoreToneClass(row.averageScore)}>
                  {formatPercent(row.averageScore, 1)}
                </span>
              )}
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}

/** Horizontal bars for the graded-score buckets. */
export function ScoreDistributionCard({
  buckets,
  gradedCount,
}: {
  buckets: ScoreBucket[];
  gradedCount: number;
}) {
  const max = Math.max(1, ...buckets.map((bucket) => bucket.count));

  return (
    <Card>
      <CardHeader>
        <CardTitle>Sebaran Nilai</CardTitle>
        <CardDescription>
          {gradedCount === 0
            ? "Belum ada pengumpulan yang dinilai."
            : `${formatNumber(gradedCount)} pengumpulan dinilai, dikelompokkan per rentang nilai.`}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {buckets.map((bucket) => (
          <div key={bucket.label} className="space-y-1.5">
            <div className="flex items-center justify-between text-xs">
              <span className="font-medium text-secondary">{bucket.label}</span>
              <span className="tabular-nums text-tertiary">
                {formatNumber(bucket.count)} pengumpulan · {formatPercent(bucket.percent, 1)}
              </span>
            </div>
            <Progress
              value={bucket.count}
              max={max}
              tone={
                bucket.min >= 90
                  ? "success"
                  : bucket.min >= 70
                    ? "brand"
                    : bucket.min >= 60
                      ? "warning"
                      : "danger"
              }
            />
          </div>
        ))}
      </CardContent>
    </Card>
  );
}

type AttendanceTone = "success" | "warning" | "danger" | "brand";

const ATTENDANCE_ROWS: {
  key: "present" | "late" | "absent" | "excused";
  percentKey: "presentPercent" | "latePercent" | "absentPercent" | "excusedPercent";
  label: string;
  tone: AttendanceTone;
}[] = [
  { key: "present", percentKey: "presentPercent", label: "Hadir", tone: "success" },
  { key: "late", percentKey: "latePercent", label: "Terlambat", tone: "warning" },
  { key: "absent", percentKey: "absentPercent", label: "Alpa", tone: "danger" },
  { key: "excused", percentKey: "excusedPercent", label: "Izin", tone: "brand" },
];

/** Attendance breakdown as counts, percentages and bars. */
export function AttendanceBreakdownCard({ attendance }: { attendance: AttendanceBreakdown }) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>Rincian Kehadiran</CardTitle>
        <CardDescription>
          {attendance.total === 0
            ? "Belum ada catatan absensi."
            : `${formatNumber(attendance.total)} catatan absensi · tingkat kehadiran ${formatPercent(attendance.attendanceRate, 1)}`}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {ATTENDANCE_ROWS.map((row) => {
          const count = attendance[row.key];
          const percent = attendance[row.percentKey];
          return (
            <div key={row.key} className="space-y-1.5">
              <div className="flex items-center justify-between text-xs">
                <span className="font-medium text-secondary">{row.label}</span>
                <span className="tabular-nums text-tertiary">
                  {formatNumber(count)} catatan · {formatPercent(percent, 1)}
                </span>
              </div>
              <Progress value={count} max={Math.max(1, attendance.total)} tone={row.tone} />
            </div>
          );
        })}
      </CardContent>
    </Card>
  );
}
