/**
 * Logs Table Component
 * Displays logs in a table format similar to tasks
 */

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

const LogsTable: React.FC = () => {
    const { logs, logsLoading, logsError, fetchLogs, getString } =
        useContentPlan();

    useEffect(() => {
        // Fetch logs on mount
        fetchLogs({ limit: 100 });
    }, []); // Empty dependency array - only fetch on mount

    const getLevelBadgeClasses = (level: Log['level']): string => {
        switch (level) {
            case 'error':
                return 'text-red-600 bg-red-50';
            case 'warning':
                return 'text-yellow-600 bg-yellow-50';
            case 'info':
                return 'text-blue-600 bg-blue-50';
            case 'debug':
                return 'text-gray-600 bg-gray-50';
            default:
                return 'text-gray-600 bg-gray-50';
        }
    };

    const formatDate = (dateString: string): string => {
        try {
            const date = new Date(dateString);
            return date.toLocaleString();
        } catch {
            return dateString;
        }
    };

    const formatContext = (context: string | null | undefined): string => {
        if (!context) return '';
        try {
            const parsed = JSON.parse(context);
            return JSON.stringify(parsed, null, 2);
        } catch {
            return context;
        }
    };

    if (logsLoading && logs.length === 0) {
        return (
            <div className="text-center py-8">
                <div className="cpepai-spinner mx-auto mb-2"></div>
                <p className="text-gray-500">
                    {getString('log', 'loading', 'Loading logs...')}
                </p>
            </div>
        );
    }

    if (logsError) {
        return (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
                <p className="text-red-800 text-sm">
                    {getString('log', 'error_loading', 'Error loading logs:')}{' '}
                    {logsError}
                </p>
            </div>
        );
    }

    if (!logsLoading && logs.length === 0) {
        return (
            <div className="text-center py-8">
                <p className="text-gray-500">
                    {getString('log', 'no_logs', 'No logs found')}
                </p>
            </div>
        );
    }

    return (
        <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 border border-gray-200 rounded-lg">
                <thead className="bg-gray-50">
                    <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            {getString('log', 'date', 'Date')}
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            {getString('log', 'level', 'Level')}
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            {getString('log', 'event', 'Event')}
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            {getString('log', 'message', 'Message')}
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            {getString('log', 'tokens_spent', 'Tokens Spent')}
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                            {getString('log', 'task_id', 'Task ID')}
                        </th>
                    </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                    {logs.map(log => (
                        <tr key={log.id} className="hover:bg-gray-50">
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                                {formatDate(log.created_at)}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap">
                                <span
                                    className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getLevelBadgeClasses(
                                        log.level
                                    )}`}
                                >
                                    {log.level.toUpperCase()}
                                </span>
                            </td>
                            <td className="px-4 py-3 text-sm text-gray-900 break-words max-w-xs">
                                {log.event || '-'}
                            </td>
                            <td className="px-4 py-3 text-sm text-gray-900 break-words max-w-md">
                                <div className="max-h-32 overflow-y-auto">
                                    {log.message || '-'}
                                    {log.context && (
                                        <details className="mt-2">
                                            <summary className="cursor-pointer text-xs text-gray-500 hover:text-gray-700">
                                                {getString(
                                                    'log',
                                                    'show_context',
                                                    'Show context'
                                                )}
                                            </summary>
                                            <pre className="mt-2 text-xs bg-gray-100 p-2 rounded overflow-x-auto">
                                                {formatContext(log.context)}
                                            </pre>
                                        </details>
                                    )}
                                </div>
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
                                {log.tokens_spent !== null &&
                                log.tokens_spent !== undefined
                                    ? log.tokens_spent
                                    : '-'}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                {log.task_id || '-'}
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default LogsTable;
