import { ActionIcon, rem, Tooltip } from "@mantine/core";
import { IconCheck, IconLink } from "@tabler/icons-react";
import { FC } from "react";
import { useClipboard } from "@mantine/hooks";
import { ClientSchema, ClientService } from "../../../../client";
import { notifications } from "../../../../shared/lib/notifications.ts";

type Props = {
    client: ClientSchema;
};

const ClientLinkActionIcon: FC<Props> = ({ client }) => {
    const clipboard = useClipboard();

    const onGetLinkClick = () => {
        ClientService.clientLink({
            clientId: client.id,
        })
            .then(({ ok, message, url }) => {
                if (ok) {
                    clipboard.copy(`${window.location.origin}/${url}`);
                } else {
                    notifications.error({ message });
                }
            })
            .catch(err => console.log(err));
    };

    return (
        <Tooltip
            label={"Ссылка скопирована"}
            offset={5}
            radius="xl"
            transitionProps={{ duration: 100, transition: "slide-down" }}
            opened={clipboard.copied}>
            <ActionIcon
                variant={"default"}
                size="md"
                onClick={() => onGetLinkClick()}
            >
                {clipboard.copied ? (
                    <IconCheck
                        style={{ width: rem(20), height: rem(20) }}
                        stroke={1.5}
                    />
                ) : (
                    <IconLink
                        style={{ width: rem(20), height: rem(20) }}
                        stroke={1.5}
                    />
                )}
            </ActionIcon>
        </Tooltip>
    );
};

export default ClientLinkActionIcon;
