"use client";

import * as React from "react";
import { useActionState } from "react";
import { Plus, Trash2, TriangleAlert, UserPlus } from "lucide-react";
import { Avatar } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Alert } from "@/components/ui/alert";
import { Card, CardContent } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Field, Select } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { ActionButton } from "@/components/ui/action-button";
import { enrollStudentAction, unenrollStudentAction } from "@/actions/courses";
import { IDLE_ACTION } from "@/lib/action-state";
import { formatDate } from "@/lib/format";
import { ENROLLMENT_BADGE } from "@/lib/labels";
import type { CourseStudentRow } from "@/lib/queries/courses";

interface EnrollableStudent {
  id: string;
  fullName: string;
  username: string;
  gradeLevel: string | null;
}

/** Enrolled-student roster with manual enrolment controls. */
export function CourseRoster({
  courseId,
  students,
  enrollable,
}: {
  courseId: string;
  students: CourseStudentRow[];
  enrollable: EnrollableStudent[];
}) {
  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <p className="text-sm text-secondary">
          {students.length} siswa terdaftar di kursus ini.
        </p>
        <EnrollStudentDialog courseId={courseId} enrollable={enrollable} />
      </div>

      {students.length === 0 ? (
        <EmptyState
          icon={<UserPlus className="size-5" />}
          title="Belum ada siswa"
          description="Tambahkan siswa secara manual, atau minta mereka bergabung lewat kode kelas."
        />
      ) : (
        <div className="space-y-2">
          {students.map((student) => {
            const badge = ENROLLMENT_BADGE[student.status as keyof typeof ENROLLMENT_BADGE];
            return (
              <Card key={student.id}>
                <CardContent className="flex flex-wrap items-center gap-3 pt-5">
                  <Avatar name={student.fullName} src={student.avatarUrl} size="sm" />
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-primary">{student.fullName}</p>
                    <p className="truncate text-xs text-tertiary">
                      @{student.username}
                      {student.gradeLevel ? ` · Kelas ${student.gradeLevel}` : ""} · bergabung{" "}
                      {formatDate(student.enrolledAt)}
                    </p>
                  </div>

                  <div className="w-32 shrink-0 space-y-1">
                    <Progress value={student.progress} size="sm" tone="brand" />
                    <p className="text-[10px] tabular-nums text-tertiary">{student.progress}% selesai</p>
                  </div>

                  {badge ? <Badge variant={badge.variant}>{badge.label}</Badge> : null}

                  <ActionButton
                    action={unenrollStudentAction}
                    fields={{ courseId, studentId: student.id }}
                    label=""
                    icon={<Trash2 className="size-3.5" />}
                    variant="ghost"
                    size="icon-sm"
                    confirm={`${student.fullName} akan dikeluarkan dari kursus ini. Progres belajarnya dihapus.`}
                    confirmTitle="Keluarkan siswa?"
                    confirmLabel="Keluarkan"
                  />
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}

function EnrollStudentDialog({
  courseId,
  enrollable,
}: {
  courseId: string;
  enrollable: EnrollableStudent[];
}) {
  const [open, setOpen] = React.useState(false);
  const [state, formAction, pending] = useActionState(enrollStudentAction, IDLE_ACTION);

  React.useEffect(() => {
    if (state.status === "success") setOpen(false);
  }, [state.status]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="secondary" disabled={enrollable.length === 0}>
          <Plus className="size-4" />
          Tambah Siswa
        </Button>
      </DialogTrigger>
      <DialogContent size="sm">
        <form action={formAction}>
          <input type="hidden" name="courseId" value={courseId} />
          <DialogHeader>
            <DialogTitle>Tambahkan Siswa</DialogTitle>
            <DialogDescription>
              Pilih siswa yang belum terdaftar di kursus ini.
            </DialogDescription>
          </DialogHeader>
          <DialogBody className="space-y-4">
            {state.status === "error" && state.message ? (
              <Alert tone="danger" icon={<TriangleAlert className="size-4" />}>
                {state.message}
              </Alert>
            ) : null}
            <Field label="Siswa" htmlFor="enroll-student" required>
              <Select id="enroll-student" name="studentId" required>
                <option value="">Pilih siswa…</option>
                {enrollable.map((student) => (
                  <option key={student.id} value={student.id}>
                    {student.fullName}
                    {student.gradeLevel ? ` (${student.gradeLevel})` : ""} — @{student.username}
                  </option>
                ))}
              </Select>
            </Field>
          </DialogBody>
          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => setOpen(false)}>
              Batal
            </Button>
            <Button type="submit" loading={pending}>
              Tambahkan
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
