"use client";

import { FC, useEffect, useMemo, useState } from "react";
import { Text } from "@mantine/core";
import useClientsList from "@/app/clients/hooks/lists/useClientsList";
import ObjectSelect, {
    ObjectSelectProps,
} from "@/components/selects/ObjectSelect/ObjectSelect";
import { ClientSchema, DealSchema } from "@/lib/client";

type RestProps = {
    includeDeleted?: boolean;
    deal?: DealSchema;
};

type Props = Omit<ObjectSelectProps<ClientSchema>, "data"> & RestProps;

const ClientSelect: FC<Props> = ({ includeDeleted = false, ...props }) => {
    const { clients } = useClientsList({ includeDeleted });

    const filteredClients = useMemo(
        () =>
            clients.filter(
                client =>
                    !client.isDeleted ||
                    (includeDeleted && client.id === props.deal?.client?.id)
            ),
        [clients]
    );

    const [deletedClientIds, setDeletedClientIds] = useState<Set<number>>(
        new Set()
    );
    const [warning, setWarning] = useState<string>("");

    useEffect(() => {
        const deletedClientIds = new Set(
            clients.filter(client => client.isDeleted).map(client => client.id)
        );

        setDeletedClientIds(deletedClientIds);
    }, [clients]);

    useEffect(() => {
        if (props.value && deletedClientIds.has(props.value.id)) {
            setWarning("Выбран удаленный клиент");
        } else {
            setWarning("");
        }
    }, [props.value, deletedClientIds]);

    return (
        <>
            <ObjectSelect
                searchable
                data={filteredClients}
                placeholder={"Выберите клиента"}
                {...props}
            />
            {warning && (
                <Text
                    size={"sm"}
                    c={"yellow"}>
                    {warning}
                </Text>
            )}
        </>
    );
};
export default ClientSelect;
