/**
 * Tasks Panel Component
 * Displays tasks with their status
 */

import React, { useEffect } from 'react';
import { useContentPlan } from '../context/ContentPlanContext';
import { Task } from '../types';

interface TasksPanelProps {
    taskId?: string | null;
    onClose?: () => void;
}

const TasksPanel: React.FC<TasksPanelProps> = ({ taskId, onClose }) => {
    const {
        tasks,
        tasksLoading,
        tasksError,
        fetchTasks,
        getString,
        setCurrentTaskId,
        markTaskAsWatched,
        setTaskFilter,
        taskFilterId,
        contentPlan,
    } = useContentPlan();

    useEffect(() => {
        // Fetch tasks when taskId changes (initial fetch is handled by ContentPlanContext on mount)
        // Note: Polling is now handled in ContentPlanContext
        if (taskId) {
            fetchTasks({ limit: 20 });
        }
    }, [taskId]); // Removed fetchTasks from dependencies as it's stable (useCallback)

    const getStatusBadgeClasses = (status: Task['status']): string => {
        switch (status) {
            case 'completed':
                return 'text-green-600 bg-green-50';
            case 'failed':
                return 'text-red-600 bg-red-50';
            case 'processing':
                return 'text-blue-600 bg-blue-50';
            case 'queued':
                return 'text-yellow-600 bg-yellow-50';
            default:
                return 'text-gray-600 bg-gray-50';
        }
    };

    const getTaskContainerClasses = (status: Task['status']): string => {
        switch (status) {
            case 'completed':
                return 'bg-green-50 border-green-200';
            case 'failed':
                return 'bg-red-50 border-red-200';
            case 'processing':
                return 'bg-blue-50 border-blue-200';
            case 'queued':
                return 'bg-yellow-50 border-yellow-200';
            default:
                return 'bg-gray-50 border-gray-200';
        }
    };

    const formatTypeForDisplay = (value: string): string =>
        value
            .split(/[_\s-]+/)
            .filter(Boolean)
            .map(
                word =>
                    word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
            )
            .join(' ');

    const getTaskTitle = (type: Task['type']): string => {
        const normalizedType = type?.toLowerCase();

        switch (normalizedType) {
            case 'content_plan_generation':
            case 'content_plan':
                return getString(
                    'tasks_panel',
                    'content_plan_generation',
                    'Content plan generation task'
                );
            case 'post_generation':
            case 'post':
                return getString(
                    'tasks_panel',
                    'post_generation',
                    'Post generation task'
                );
            default:
                return type
                    ? `${formatTypeForDisplay(type)} task`
                    : getString('tasks_panel', 'generic_task', 'Task');
        }
    };

    const getStatusLabel = (status: Task['status']): string => {
        switch (status) {
            case 'completed':
                return 'Completed';
            case 'failed':
                return 'Failed';
            case 'processing':
                return 'Processing';
            case 'queued':
                return 'Queued';
            default:
                return status;
        }
    };

    return (
        <>
            {tasksLoading && tasks.length === 0 && (
                <div className="text-center py-8">
                    <div className="cpepai-spinner mx-auto mb-2"></div>
                    <p className="text-gray-500">
                        {getString(
                            'generation_modal',
                            'loading_tasks',
                            'Loading tasks...'
                        )}
                    </p>
                </div>
            )}
            {tasksError && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
                    <p className="text-red-800 text-sm">
                        {getString(
                            'generation_modal',
                            'error_loading_tasks',
                            'Error loading tasks:'
                        )}{' '}
                        {tasksError}
                    </p>
                </div>
            )}
            {!tasksLoading && tasks.length === 0 && (
                <div className="text-center py-8">
                    <p className="text-gray-500">
                        {getString(
                            'generation_modal',
                            'no_tasks',
                            'No tasks found'
                        )}
                    </p>
                </div>
            )}
            {tasks.length > 0 && (
                <div className="space-y-2 sm:space-y-3">
                    {tasks
                        .filter(task => !task.watched) // Filter out watched tasks
                        .map(task => (
                            <div
                                key={task.id}
                                className={`border rounded-lg p-3 sm:p-4 ${getTaskContainerClasses(
                                    task.status
                                )}`}
                            >
                                <div className="flex items-start justify-between gap-2">
                                    <div className="flex-1 min-w-0">
                                        <h3 className="text-xs sm:text-sm font-semibold text-gray-800 mb-1 break-words">
                                            {getTaskTitle(task.type)}
                                        </h3>
                                        <div className="flex flex-wrap items-center gap-2 mb-2">
                                            <span className="text-xs font-medium text-gray-700">
                                                Status:{' '}
                                                <span
                                                    className={`py-0.5 sm:py-1 pr-1 sm:pr-2 pl-0 rounded text-xs font-medium ${getStatusBadgeClasses(
                                                        task.status
                                                    )} ${
                                                        task.status ===
                                                        'processing'
                                                            ? 'relative overflow-hidden'
                                                            : ''
                                                    }`}
                                                >
                                                    {task.status ===
                                                    'processing' ? (
                                                        <span className="cpepai-processing-light">
                                                            {getStatusLabel(
                                                                task.status
                                                            )}
                                                        </span>
                                                    ) : (
                                                        getStatusLabel(
                                                            task.status
                                                        )
                                                    )}
                                                </span>
                                            </span>
                                        </div>
                                        <p className="text-xs text-gray-500">
                                            Created:{' '}
                                            {new Date(
                                                task.created_at
                                            ).toLocaleString()}
                                        </p>
                                    </div>
                                    <button
                                        onClick={async () => {
                                            try {
                                                await markTaskAsWatched(
                                                    task.id
                                                );
                                            } catch (error) {
                                                console.error(
                                                    'Failed to mark task as watched:',
                                                    error
                                                );
                                            }
                                        }}
                                        className="ml-2 sm:ml-4 text-gray-400 hover:text-gray-600 focus:outline-none flex-shrink-0"
                                        aria-label="Mark as watched"
                                        title="Mark as watched"
                                    >
                                        <svg
                                            className="w-4 h-4 sm:w-5 sm:h-5"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                strokeWidth={2}
                                                d="M6 18L18 6M6 6l12 12"
                                            />
                                        </svg>
                                    </button>
                                </div>
                                {task.status === 'completed' &&
                                    (() => {
                                        // Check for content plan generation tasks (have item_ids)
                                        const itemIds =
                                            task.result?.output?.item_ids;
                                        const hasItemIds =
                                            itemIds &&
                                            Array.isArray(itemIds) &&
                                            itemIds.length > 0;

                                        // Check for post generation tasks (have item_id in input)
                                        const itemId =
                                            task.result?.input?.item_id;
                                        const hasItemId =
                                            itemId !== undefined &&
                                            itemId !== null;

                                        // For post generation tasks, get the formatted scheduled date from task
                                        const formattedScheduledDate =
                                            task.formatted_scheduled_date ||
                                            null;

                                        // Show filter link if task has item_ids (content plan generation) or item_id (post generation)
                                        if (hasItemIds || hasItemId) {
                                            const filterText = hasItemIds
                                                ? getString(
                                                      'tasks_panel',
                                                      'filter_items',
                                                      `Show ${itemIds.length} item${itemIds.length === 1 ? '' : 's'}`
                                                  )
                                                : getString(
                                                      'tasks_panel',
                                                      'filter_post',
                                                      'Show generated post'
                                                  );

                                            return (
                                                <div className="mt-2 sm:mt-3 space-y-2">
                                                    <button
                                                        onClick={() => {
                                                            setTaskFilter(
                                                                task.id
                                                            );
                                                        }}
                                                        className="text-xs text-blue-600 hover:text-blue-800 font-medium underline flex items-center gap-1 break-words"
                                                        title={
                                                            hasItemIds
                                                                ? 'Filter content plan items created by this task'
                                                                : 'Filter content plan item with generated post'
                                                        }
                                                    >
                                                        <svg
                                                            className="w-3 h-3 sm:w-4 sm:h-4 flex-shrink-0"
                                                            fill="none"
                                                            stroke="currentColor"
                                                            viewBox="0 0 24 24"
                                                        >
                                                            <path
                                                                strokeLinecap="round"
                                                                strokeLinejoin="round"
                                                                strokeWidth={2}
                                                                d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
                                                            />
                                                        </svg>
                                                        <span className="break-words">
                                                            {filterText}
                                                        </span>
                                                    </button>
                                                    {formattedScheduledDate && (
                                                        <div className="flex items-start gap-1.5">
                                                            <svg
                                                                className="w-3 h-3 sm:w-4 sm:h-4 text-green-600 flex-shrink-0 mt-0.5"
                                                                fill="none"
                                                                stroke="currentColor"
                                                                viewBox="0 0 24 24"
                                                            >
                                                                <path
                                                                    strokeLinecap="round"
                                                                    strokeLinejoin="round"
                                                                    strokeWidth={
                                                                        2
                                                                    }
                                                                    d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
                                                                />
                                                            </svg>
                                                            <p className="text-xs text-gray-700 break-words">
                                                                <span className="font-medium">
                                                                    {getString(
                                                                        'tasks_panel',
                                                                        'auto_publish',
                                                                        'Will auto-publish on:'
                                                                    )}
                                                                </span>{' '}
                                                                <span className="text-green-700 font-semibold">
                                                                    {
                                                                        formattedScheduledDate
                                                                    }
                                                                </span>
                                                            </p>
                                                        </div>
                                                    )}
                                                </div>
                                            );
                                        }
                                        return null;
                                    })()}
                                {task.status === 'failed' && (
                                    <div className="mt-2 sm:mt-3">
                                        {task.result &&
                                        typeof task.result === 'object' &&
                                        task.result.error ? (
                                            <>
                                                {/* Check moderation flags from task.moderation or task.result */}
                                                {(task as any).moderation
                                                    ?.blocked ||
                                                task.result
                                                    .moderation_blocked ? (
                                                    <div className="bg-red-50 border-l-4 border-red-500 p-3 rounded">
                                                        <div className="flex items-start">
                                                            <div className="flex-shrink-0">
                                                                <svg
                                                                    className="h-5 w-5 text-red-500"
                                                                    viewBox="0 0 20 20"
                                                                    fill="currentColor"
                                                                >
                                                                    <path
                                                                        fillRule="evenodd"
                                                                        d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                                                                        clipRule="evenodd"
                                                                    />
                                                                </svg>
                                                            </div>
                                                            <div className="ml-3 flex-1">
                                                                <h3 className="text-sm font-bold text-red-800">
                                                                    ACCOUNT
                                                                    BLOCKED
                                                                </h3>
                                                                <div className="mt-1 text-sm text-red-700 whitespace-pre-line break-words">
                                                                    {task.result.error?.replace(
                                                                        /\\n/g,
                                                                        '\n'
                                                                    )}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ) : (task as any).moderation
                                                      ?.warning ||
                                                  task.result
                                                      .moderation_warning ? (
                                                    <div className="bg-yellow-50 border-l-4 border-yellow-500 p-3 rounded">
                                                        <div className="flex items-start">
                                                            <div className="flex-shrink-0">
                                                                <svg
                                                                    className="h-5 w-5 text-yellow-500"
                                                                    viewBox="0 0 20 20"
                                                                    fill="currentColor"
                                                                >
                                                                    <path
                                                                        fillRule="evenodd"
                                                                        d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                                                                        clipRule="evenodd"
                                                                    />
                                                                </svg>
                                                            </div>
                                                            <div className="ml-3 flex-1">
                                                                <div className="mt-1 text-sm text-yellow-700 whitespace-pre-line break-words">
                                                                    {task.result.error?.replace(
                                                                        /\\n/g,
                                                                        '\n'
                                                                    )}
                                                                </div>
                                                                <p className="mt-2 text-xs text-yellow-600 font-medium">
                                                                    You can
                                                                    modify your
                                                                    request and
                                                                    try again.
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <div className="bg-red-50 border-l-4 border-red-400 p-3 rounded">
                                                        <div className="flex items-start">
                                                            <div className="flex-shrink-0">
                                                                <svg
                                                                    className="h-5 w-5 text-red-400"
                                                                    viewBox="0 0 20 20"
                                                                    fill="currentColor"
                                                                >
                                                                    <path
                                                                        fillRule="evenodd"
                                                                        d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                                                                        clipRule="evenodd"
                                                                    />
                                                                </svg>
                                                            </div>
                                                            <div className="ml-3 flex-1">
                                                                <h3 className="text-sm font-bold text-red-700">
                                                                    Task Failed
                                                                </h3>
                                                                <div className="mt-1 text-sm text-red-600 whitespace-pre-line break-words">
                                                                    {task.result.error?.replace(
                                                                        /\\n/g,
                                                                        '\n'
                                                                    )}
                                                                </div>
                                                                {(task as any)
                                                                    .moderation
                                                                    ?.can_retry !==
                                                                    false &&
                                                                    task.result
                                                                        .can_retry !==
                                                                        false && (
                                                                        <p className="mt-2 text-xs text-red-500 font-medium">
                                                                            You
                                                                            can
                                                                            retry
                                                                            this
                                                                            task.
                                                                        </p>
                                                                    )}
                                                            </div>
                                                        </div>
                                                    </div>
                                                )}
                                            </>
                                        ) : (
                                            <p className="text-xs text-gray-500 break-words">
                                                {getString(
                                                    'tasks_panel',
                                                    'loading_error_details',
                                                    'Loading error details...'
                                                )}
                                            </p>
                                        )}
                                    </div>
                                )}
                            </div>
                        ))}
                </div>
            )}
        </>
    );
};

export default TasksPanel;
