import React from 'react';
import {PersonPicker} from './PersonPicker';

interface Link {
    rel: string;
    href: string;
    type: string;
    title?: string;
}

interface Student {
    id: number;
    nameFull: string;
    reference: string;
    nameWithReference: string;
    links: Link[]; // Add links to represent HATEOAS navigation
}

interface Person {
    id: number;
    nameFull: string;
    reference: string;
    nameWithReference: string;
    links: Link[];
}

interface StudentPickerProps {
    onSelect?: (student: Person) => void; // Callback when a person is selected
    selectedStudent?: Person;
}

export function StudentPicker({ onSelect, selectedStudent }: StudentPickerProps) {
    const getStudents = async (): Promise<Person[]> => {
        try {
            const response = await fetch(`/api/cedar/v1/students`);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const students: Student[] = await response.json();
            return students.map(student => ({
                id: student.id,
                nameFull: student.nameFull,
                reference: student.reference,
                nameWithReference: student.nameWithReference,
                links: student.links,
            }));
        } catch (error) {
            console.error('Error fetching students:', error);
            return []; // Return an empty array on error
        }
    };

    return <PersonPicker
        fetchPeople={getStudents}
        onSelect={onSelect}
        value={selectedStudent ? { value: selectedStudent.id, label: selectedStudent.nameFull } : null}
    />;
}
