import ComboBoxInput from '@/Components/ComboBoxInput';
import { User } from '@/types';
import axios from 'axios';
import { useState } from 'react';

interface PatientSelectInputProps {
    value: User | null;
    onChange: (patient: User | null) => void;
    /** Restrict the search to patients of this company (the device's company). */
    companyId?: number | null;
    readOnly?: boolean;
}

export default function PatientSelectInput({
    value,
    onChange,
    companyId,
    readOnly = false,
}: PatientSelectInputProps) {
    const [patients, setPatients] = useState<User[]>([]);

    const fetchPatients = async (search: string) => {
        try {
            const response = await axios.get(route('search-patients'), {
                params: { search, company_id: companyId ?? undefined },
            });
            setPatients(response.data);
        } catch (error) {
            console.error('Error fetching patients:', error);
        }
    };

    return (
        <ComboBoxInput
            value={value}
            options={patients}
            readOnly={readOnly}
            renderOption={(patient) => `${patient.name} ${patient.surname}`}
            onChange={onChange}
            onSearchChange={fetchPatients}
        />
    );
}
