import { useEffect, useState } from 'react';
import { Progress } from '@heroui/react';
import { useTaskStatus } from '../hooks';
import { taskHelpers } from '../helpers';

interface TaskProgressProps {
    taskId: string;
    taskType: string;
    progressAriaLabel?: string;
    onComplete?: (status: 'success' | 'error', error?: string) => void;
}

export default function TaskProgress({
    taskId,
    taskType,
    progressAriaLabel = 'Task progress',
    onComplete,
}: TaskProgressProps) {
    const { taskInfo, error } = useTaskStatus(taskId, taskType);

    useEffect(() => {
        if (taskInfo && taskHelpers.isTaskComplete(taskInfo) && onComplete) {
            onComplete(taskInfo.state, taskHelpers.formatTaskError(taskInfo));
        }
    }, [taskInfo, onComplete]);

    if (error) {
        return (
            <div className="flex flex-col w-full items-center justify-center gap-4 p-4">
                <p>{`Error: ${error.message}`}</p>
            </div>
        );
    }

    if (!taskInfo) {
        return (
            <div className="flex flex-col w-full items-center justify-center gap-4 p-4">
                <p>Loading task information...</p>
            </div>
        );
    }

    if (taskInfo.state === 'running') {
        return (
            <div className="flex flex-col w-full items-center justify-center gap-4 p-4">
                <Progress
                    value={taskHelpers.getProgressPercentage(taskInfo)}
                    showValueLabel
                    className="w-full"
                    aria-label={progressAriaLabel}
                />
            </div>
        );
    }

    if (taskInfo.state === 'error') {
        return (
            <div className="flex flex-col w-full items-center justify-center gap-4 p-4">
                <p>{taskHelpers.formatTaskError(taskInfo)}</p>
            </div>
        );
    }

    if (taskInfo.state === 'success') {
        return (
            <div className="flex flex-col w-full items-center justify-center gap-4 p-4">
                <p>Task completed successfully.</p>
            </div>
        );
    }

    return (
        <div className="flex flex-col w-full items-center justify-center gap-4 p-4">
            <p>Task status: {taskInfo.state}.</p>
        </div>
    );
}
