"use client";

import { useActionState } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { enrollStudentAction, removeEnrollmentAction } from "@/lib/actions/admin-actions";
import type { ActionResult } from "@/lib/actions/auth-actions";

const initialState: ActionResult = { error: null };

type Student = { id: string; full_name: string };

export function EnrollmentManager({
  courseId,
  enrolledStudents,
  availableStudents,
}: {
  courseId: string;
  enrolledStudents: Student[];
  availableStudents: Student[];
}) {
  const [state, formAction, pending] = useActionState(enrollStudentAction, initialState);

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap gap-2">
        {enrolledStudents.length === 0 && (
          <p className="text-sm text-muted-foreground">No students enrolled yet.</p>
        )}
        {enrolledStudents.map((s) => (
          <Badge key={s.id} variant="secondary" className="gap-2 py-1.5">
            {s.full_name}
            <form action={removeEnrollmentAction.bind(null, courseId, s.id)}>
              <button type="submit" className="text-muted-foreground hover:text-destructive" aria-label={`Remove ${s.full_name}`}>
                ×
              </button>
            </form>
          </Badge>
        ))}
      </div>

      {availableStudents.length > 0 && (
        <form action={formAction} className="flex items-end gap-2">
          <input type="hidden" name="courseId" value={courseId} />
          <div className="flex-1">
            <Select
              name="studentId"
              items={availableStudents.map((s) => ({ value: s.id, label: s.full_name }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select a student to enroll" />
              </SelectTrigger>
              <SelectContent>
                {availableStudents.map((s) => (
                  <SelectItem key={s.id} value={s.id}>
                    {s.full_name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <Button type="submit" disabled={pending} variant="outline">
            Enroll
          </Button>
        </form>
      )}
      {state.error && <p className="text-sm text-destructive">{state.error}</p>}
    </div>
  );
}
