import { ActionIcon, Box, CopyButton, Menu, TextInput } from '@mantine/core';
import { IconCopy, IconMenu, IconTrash } from '@tabler/icons-react';
import { useMemo, useRef } from 'react';
import { createKey, deleteKey, deletesKey, getKeys } from '../apis/generate-key';
import Table from '../lib/table/table';
import { IColumn, TRefTableFn } from '../lib/table/type';
import { useConfirmStore } from '../lib/zustand/use-confirm';
import { IKey } from '../system/type';
import { formatTime } from '../utils';

export default function GenerateKeys() {
    const refTableFn: TRefTableFn<IKey> = useRef({});

    const { setConfirm } = useConfirmStore();

    const columns: IColumn<IKey>[] = [
        {
            key: 'id',
            title: 'ID',
            typeFilter: 'number',
        },
        {
            key: 'client_key',
            title: 'Client key',
            typeFilter: 'text',
            renderRow(row) {
                return (
                    <CopyButton value={row.client_key}>
                        {({ copied, copy }) => (
                            <TextInput
                                size="xs"
                                value={row.client_key}
                                rightSection={
                                    <ActionIcon className="z-30 cursor-pointer" size="xs" color={copied ? 'teal' : 'blue'} onClick={copy}>
                                        <IconCopy size={12} />
                                    </ActionIcon>
                                }
                            />
                        )}
                    </CopyButton>
                );
            },
        },
        {
            key: 'created_at',
            title: 'Create at',
            typeFilter: 'none',
            renderRow(row) {
                return <span className="text-sm">{formatTime(row.created_at)}</span>;
            },
        },
    ];

    const handleDelete = (bid: IKey) => {
        setConfirm({
            title: 'Delete ?',
            message: 'This key will be delete',
            handleOk: async () => {
                await deleteKey(bid);

                if (refTableFn.current?.fetchData) {
                    refTableFn.current.fetchData();
                }
            },
        });
    };

    const table = useMemo(() => {
        return (
            <Table
                actionsOptions={{
                    actions: [
                        {
                            key: 'create',
                            title: 'New key',
                            callback: async () => {
                                setConfirm({
                                    okButton: {
                                        color: 'lime',
                                        value: 'Ok',
                                    },
                                    title: 'A new key will generate',
                                    handleOk: async () => {
                                        await createKey();

                                        if (!refTableFn.current?.fetchData) return;

                                        refTableFn.current.fetchData();
                                    },
                                });
                            },
                        },
                        {
                            key: 'delete',
                            title: 'Delete',
                            callback: (data) => {
                                if (!data.length) return;
                                setConfirm({
                                    title: 'Delete',
                                    message: `${data.length} keys will be delete`,
                                    handleOk: async () => {
                                        const result = await deletesKey(data);

                                        if (!result) return;
                                        if (refTableFn.current.fetchData) {
                                            refTableFn.current.fetchData();
                                        }
                                    },
                                });
                            },
                            disabled: (data) => data.length <= 0,
                        },
                    ],
                }}
                refTableFn={refTableFn}
                striped
                showLoading={true}
                highlightOnHover
                styleDefaultHead={{
                    justifyContent: 'flex-start',
                    width: 'fit-content',
                }}
                options={{
                    query: getKeys,
                    pathToData: 'data.data',
                    keyOptions: {
                        last_page: 'lastPage',
                        per_page: 'perPage',
                        from: 'from',
                        to: 'to',
                        total: 'total',
                    },
                }}
                actions={{
                    title: <Box className="w-full text-center">Action</Box>,
                    body: (row) => {
                        return (
                            <Menu shadow="md" width={200}>
                                <Menu.Target>
                                    <Box onClick={(e) => e.stopPropagation()} className="flex w-full items-center justify-center">
                                        <ActionIcon size="sm" variant="light">
                                            <IconMenu size={14} />
                                        </ActionIcon>
                                    </Box>
                                </Menu.Target>

                                <Menu.Dropdown onClick={(e) => e.stopPropagation()}>
                                    <Menu.Item onClick={() => handleDelete(row)} leftSection={<IconTrash color="red" size={14} />}>
                                        Delete
                                    </Menu.Item>
                                </Menu.Dropdown>
                            </Menu>
                        );
                    },
                }}
                rows={[]}
                withColumnBorders
                showChooses={true}
                withTableBorder
                columns={columns}
                rowKey="id"
            />
        );
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return <Box>{table}</Box>;
}
