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
    student_atrisk: boolean;
    ab_flag: boolean;
    student_contract_stage: string;
    gender:string;
}

interface Person {
    id: number;
    nameFull: string;
    reference: string;
    nameWithReference: string;
    links: Link[];
    student_atrisk: boolean;
    ab_flag: boolean;
    student_contract_stage: string;
    gender:string;  
}

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,
                student_atrisk: student.student_atrisk,
                ab_flag: student.ab_flag,
                student_contract_stage: student.student_contract_stage,
                gender:student.gender,
            }));
        } 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}
    />;
}
