import { Box, Text } from '@mantine/core';
import { useMemo, useRef } from 'react';
import { getSendMessageHistories, sendMessageHistoryTest } from '../apis/send-message-histories';
import Table from '../lib/table/table';
import { IColumn, TRefTableFn } from '../lib/table/type';
import { ISendMessageHistory } from '../system/type';
import { formatTime } from '../utils';

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

    const columns: IColumn<ISendMessageHistory>[] = [
        {
            key: 'id',
            title: 'ID',
            typeFilter: 'text',
        },
        {
            key: 'bid',
            title: 'Product name',
            typeFilter: 'none',
            renderRow(row) {
                return <Text>{row.bid?.name || 'None'}</Text>;
            },
        },
        {
            key: 'message',
            title: 'Message',
            typeFilter: 'text',
            renderRow(row) {
                return <Box className="max-w-[500px]" dangerouslySetInnerHTML={{ __html: row.message }}></Box>;
            },
        },
        {
            key: 'created_at',
            title: 'Create at',
            typeFilter: 'none',
            renderRow(row) {
                return <span className="text-sm">{formatTime(row.created_at)}</span>;
            },
        },
    ];

    const table = useMemo(() => {
        return (
            <Table
                actionsOptions={{
                    actions: [
                        {
                            key: 'send-test',
                            title: 'Send test',
                            callback: async () => {
                                await sendMessageHistoryTest();
                            },
                        },
                    ],
                }}
                refTableFn={refTableFn}
                striped
                showLoading={true}
                highlightOnHover
                styleDefaultHead={{
                    justifyContent: 'flex-start',
                    width: 'fit-content',
                }}
                options={{
                    query: getSendMessageHistories,
                    pathToData: 'data.data',
                    keyOptions: {
                        last_page: 'lastPage',
                        per_page: 'perPage',
                        from: 'from',
                        to: 'to',
                        total: 'total',
                    },
                }}
                rows={[]}
                withColumnBorders
                showChooses={true}
                withTableBorder
                columns={columns}
                rowKey="id"
            />
        );
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

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