import React from "react";
import { OneOrMany } from "@/helpers";
import useTheme from "@material-ui/core/styles/useTheme";
import { Trans, useTranslation } from "react-i18next";
import { Confirm } from "@/components/confirm";
import { Button, IconButton, Tooltip } from "@material-ui/core";
import { Delete } from "mdi-material-ui";
import { createBoundComponent } from "@/management/common/helpers";

export type DeleteResourceActionProps<T> = {
    onDelete: (resource: OneOrMany<T>) => void;
    resource: OneOrMany<T>;
    label: (resource: T) => string;
    children?: (action: any) => React.ReactNode;
};

export function DeleteResourceAction<T>({ onDelete, resource, children, label }: DeleteResourceActionProps<T>) {
    const theme = useTheme();
    const { t } = useTranslation("management");

    const confirmation = <>
        { !Array.isArray(resource)
            ? <Trans i18nKey="confirm.delete">
                Czy na pewno chcesz usunąć <strong>{ label(resource) }</strong>?
            </Trans>
            : <>
                { t("confirm.bulk-delete") }
                <ul>
                    { resource.map(current => <li key={ label(current) }>{ label(current) }</li>) }
                </ul>
            </>
        }
    </>;

    return <Confirm
        onConfirm={ () => onDelete(resource) }
        content={ confirmation }
        confirm={ props =>
            <Button variant="contained" startIcon={ <Delete /> }
                    style={{
                        backgroundColor: theme.palette.error.dark,
                        color: theme.palette.error.contrastText,
                    }}
                    { ...props }>
                { t("actions.delete") }
            </Button>
        }
    >
        { action => children ? children(action) : <Tooltip title={ t("actions.delete") as string }><IconButton onClick={ action }><Delete /></IconButton></Tooltip> }
    </Confirm>;
}

export function createDeleteAction<T>(props: Pick<DeleteResourceActionProps<T>, 'label' | 'onDelete'>) {
    return createBoundComponent(DeleteResourceAction, props);
}

