import {useDebouncedValue} from "@mantine/hooks";
import {Autocomplete, AutocompleteProps, TextInputProps} from "@mantine/core";
import {FC, useEffect, useState} from "react";
import {Client} from "../../../types/Client.ts";
import {ClientService} from "../../../client";

type Props = {
    onSelect?: (client: Client) => void;
    withAddress?: boolean;
    nameRestProps?: AutocompleteProps;
    addressRestProps?: TextInputProps;
}
const ClientAutocomplete: FC<Props> = ({onSelect, addressRestProps, nameRestProps, withAddress = false}) => {
    const [value, setValue] = useState('');
    const [debouncedValue] = useDebouncedValue(value, 200);

    // const [isLoading, setIsLoading] = useState(false);
    const [clients, setClients] = useState<Client[]>([])
    const [selectedClient, selectClient] = useState<Client>();

    const handleChange = (value: string) => {
        setClients([]);
        setValue(value);
    }
    const handleDebouncedChange = () => {
        if (!value.trim()) return;
        // setIsLoading(true);
        ClientService.searchClients({name: value}).then(({clients}) => {
            setClients(clients);
            // setIsLoading(false);
        })
    }

    useEffect(() => {
        handleDebouncedChange();
    }, [debouncedValue]);

    useEffect(() => {
        selectClient(clients.find(client =>
                client.name.toLowerCase().trim() == value.toLowerCase().trim())
            ||
            {
                name: value,
                id: -1,
                address: ""
            });
    }, [value]);
    useEffect(() => {
        if (!selectedClient) return;
        if (onSelect) onSelect(selectedClient);
        if (nameRestProps?.onChange) nameRestProps.onChange(selectedClient.name);
        if (addressRestProps?.onChange) {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            addressRestProps.onChange(selectedClient.address);
        }
    }, [selectedClient]);
    return (
        <>
            <Autocomplete
                {...nameRestProps}
                placeholder={'Клиент'}
                onChange={handleChange}
                value={value}
                data={clients.map(client => client.name)}
                styles={withAddress ? {
                    input: {
                        borderBottomLeftRadius: 0,
                        borderBottomRightRadius: 0
                    }
                } : {}}
            />


        </>

    )
}
export default ClientAutocomplete;




