import React, { useEffect, useState } from 'react';
import { ActionIcon, Text, Title } from '@mantine/core';
import { IconTrash } from '@tabler/icons-react';
import { useDispatch, useSelector } from 'react-redux';
import { modals } from '@mantine/modals';
import { notifications } from '@mantine/notifications';
import { deleteAttachment } from '../Settings/store/taskSlice';
import { downloadAttachment } from '../../services/TaskService';
import { __ } from '@wordpress/i18n';

// Renders the saved attachments of a single comment as download/delete pills
// (same look as task attachments). Self-contained: download via service,
// delete via the shared deleteAttachment thunk (the comment's parent task_id
// drives the project-permission gate), removing the pill from its own copy.
const CommentAttachments = ({ attachments = [], taskId, canDeleteOthers = false, readOnly = false }) => {
    const dispatch = useDispatch();
    const { loggedUserId } = useSelector((s) => s.auth.user);
    const { loggedInUser } = useSelector((s) => s.auth.session);
    const [items, setItems] = useState(attachments || []);

    useEffect(() => {
        setItems(attachments || []);
    }, [attachments]);

    if (!items || items.length === 0) return null;

    const handleDownload = (att) => {
        if (att.id) {
            downloadAttachment(att.id, att.name).catch(() => {});
        }
    };

    const doDelete = (att) => {
        dispatch(deleteAttachment({
            id: att.id,
            data: { task_id: taskId, deleted_by: loggedInUser ? loggedInUser.loggedUserId : loggedUserId },
        })).then((response) => {
            const ok = response.payload && (response.payload.status === 200 || response.payload.data);
            if (ok) {
                setItems((prev) => prev.filter((a) => a.id !== att.id));
                notifications.show({
                    title: __('Attachment', 'lazytasks-project-task-management'),
                    message: __('Attachment deleted successfully.', 'lazytasks-project-task-management'),
                    color: 'green',
                    autoClose: 2500,
                });
            } else {
                notifications.show({
                    title: __('Attachment', 'lazytasks-project-task-management'),
                    message: __('Failed to delete attachment. Please try again.', 'lazytasks-project-task-management'),
                    color: 'red',
                    autoClose: 3000,
                });
            }
        });
    };

    const handleDelete = (att) => {
        if (!att.id) return;
        modals.openConfirmModal({
            title: <Title order={5}>{__('Delete attachment', 'lazytasks-project-task-management')}</Title>,
            size: 'sm',
            radius: 'md',
            withCloseButton: false,
            children: (
                <Text size="sm">
                    {__('Are you sure you want to delete this attachment? This cannot be undone.', 'lazytasks-project-task-management')}
                </Text>
            ),
            labels: { confirm: __('Delete', 'lazytasks-project-task-management'), cancel: __('Cancel', 'lazytasks-project-task-management') },
            confirmProps: { color: 'red' },
            onConfirm: () => doDelete(att),
        });
    };

    const canDelete = (att) => !readOnly && (parseInt(loggedUserId) === parseInt(att.user_id) || canDeleteOthers);

    return (
        <div className="comment-attachments flex flex-wrap gap-2 mt-2">
            {items.map((att, index) => (
                <div key={att.id ?? index} className="bg-[#EBF1F4] rounded-full px-3 py-1 flex gap-2 items-center">
                    <button type="button" onClick={() => handleDownload(att)}>
                        <Text size="xs" lineClamp={1} fw={400} fz={12} c="#1A202C" maw={160}>{att.name}</Text>
                    </button>
                    {canDelete(att) && (
                        <ActionIcon
                            variant="transparent"
                            onClick={() => handleDelete(att)}
                            aria-label={__('Delete', 'lazytasks-project-task-management')}
                        >
                            <IconTrash size={16} stroke={1} color="red" />
                        </ActionIcon>
                    )}
                </div>
            ))}
        </div>
    );
};

export default CommentAttachments;
