import MultiSelectInput from '@/Components/MultiSelectInput';
import { Role, User } from '@/types';
import axios from 'axios';
import { useState } from 'react';

export default function OperatorsSelectInput({
    onChange,
    selectedOperators,
    operatorRole,
    errors,
    readOnly,
}: {
    selectedOperators: User[];
    onChange: (operators: User[]) => void;
    operatorRole: Role;
    readOnly?: boolean;
    errors?: string[] | string | Record<string, string>;
}) {
    const [availableOperators, setAvailableOperators] = useState<User[]>([]);

    const getAvailableOperatorValue = (operator: User) =>
        `${operator.name} ${operator.surname}`;

    const renderAvailableOperator = (operator: User) => (
        <span className="text-zinc-500">
            {operator.name} {operator.surname}
        </span>
    );

    const renderSelectedOperator = (operator: User) => (
        <div className="">
            {operator.name} {operator.surname}
        </div>
    );

    const fetchOperators = async (search: string) => {
        try {
            console.log(search, operatorRole.id);
            const response = await axios.get(route('search-users'), {
                params: {
                    search,
                    role: operatorRole.id,
                },
            });
            setAvailableOperators(response.data);
        } catch (error) {
            console.error('Error fetching items:', error);
        }
    };

    return (
        <MultiSelectInput
            label="Operatori sanitari"
            readOnly={readOnly}
            listEmptyMessage="Nessun operatore associato."
            selectEmptyMessage="Nessun operatore trovato."
            availableOptions={availableOperators}
            selectedOptions={selectedOperators}
            onSearchChange={fetchOperators}
            getAvailableOptionValue={getAvailableOperatorValue}
            renderAvailableOption={renderAvailableOperator}
            renderSelectedOption={renderSelectedOperator}
            errors={errors}
            onChange={onChange}
        />
    );
}
