import { Dropdown, List, Spin } from "antd";
import { useCallback, useState } from "react";

import { deleteJobs } from "../../queue/job/deleteJobs.js";
import { retryJobs } from "../../queue/job/retryJobs.js";
import { skipJobs } from "../../queue/job/skipJobs.js";
import { __ } from "../../utils/i18n.js";

import type { useStatusErrors } from "../../hooks/useStatusErrors.js";
import type { FC } from "react";

type ErrorItem = ReturnType<typeof useStatusErrors>["errors"][""];

const ErrorModalListItem: FC<{ item: ErrorItem }> = ({ item: { actions, type, label, description, failedJobs } }) => {
    const [busy, setBusy] = useState(false);
    const handleDelete = useCallback(async () => {
        setBusy(true);
        try {
            await deleteJobs({
                type,
            });
        } finally {
            setBusy(false);
        }
    }, [type]);

    const handleRetry = useCallback(async () => {
        setBusy(true);
        try {
            await retryJobs({
                type,
            });
        } finally {
            setBusy(false);
        }
    }, [type]);

    const handleSkip = useCallback(async () => {
        setBusy(true);
        try {
            await skipJobs({
                type,
            });
        } finally {
            setBusy(false);
        }
    }, [type]);

    const useActionText = useCallback(
        (action: (typeof actions)[0]["action"], defaultText: string) =>
            actions.filter(({ action: a }) => action === a)[0]?.linkText || defaultText,
        [actions],
    );

    return (
        <Spin spinning={busy}>
            <List.Item
                style={{ paddingLeft: 0, paddingRight: 0 }}
                actions={[
                    <Dropdown.Button
                        key="test"
                        onClick={handleRetry}
                        menu={{
                            items: [
                                {
                                    key: "skip",
                                    label: useActionText("skip", __("Skip failed jobs")),
                                    onClick: handleSkip,
                                },
                                ...actions.map(
                                    ({ action, url, linkText, target = "_blank" }) =>
                                        !action && {
                                            key: url,
                                            onClick: () => window.open(url, target),
                                            label: linkText,
                                        },
                                ),
                                {
                                    key: "delete",
                                    danger: true,
                                    label: useActionText("delete", __("Cancel process")),
                                    onClick: handleDelete,
                                },
                            ],
                        }}
                    >
                        {useActionText("retry", __("Retry"))}
                    </Dropdown.Button>,
                ]}
            >
                <List.Item.Meta
                    title={label}
                    description={
                        <>
                            <div>{description}</div>
                            <div style={{ marginTop: 10 }}>
                                <strong>{__("Error message:")}</strong>
                            </div>
                            {failedJobs.slice(0, 1).map((job) => {
                                const {
                                    id,
                                    exception: { errors },
                                } = job;
                                return (
                                    <div data-job={id} key={id} onClick={() => console.log(job)}>
                                        {Object.keys(errors).map((code) => (
                                            <div
                                                key={code}
                                                data-code={code}
                                                dangerouslySetInnerHTML={{
                                                    __html: errors[code].join("<br />"),
                                                }}
                                            />
                                        ))}
                                    </div>
                                );
                            })}
                        </>
                    }
                />
            </List.Item>
        </Spin>
    );
};

export { ErrorModalListItem };
