/**
 * Call History Directive
 * Displays 3CX call history in a table format
 */

angular.module('archDB').directive('callHistory', ['$http', 'ErrorsHandler', function ($http, ErrorsHandler) {
    return {
        restrict: 'E',
        scope: {
            taskId: '=',
            maxRecords: '@',
            showPagination: '@'
        },
        template: `
            <div class="call-history-widget" style="margin-left:-23px">
                <div ng-show="loading" class="text-center" style="padding: 20px;">
                    <i class="fa fa-spinner fa-spin"></i> Loading call history...
                </div>
                <div ng-show="!loading && calls.length === 0" class="alert alert-info text-center">
                    <i class="fa fa-info-circle"></i> No call history available yet
                </div>
                <div ng-show="!loading && calls.length > 0">
                    <table class="table table-striped table-condensed">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Number</th>
                                <th>Username</th>
                                <th>Extension</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="call in paginatedCalls">
                                <td>
                                    <small>{[{ call.called_at | fromNow }]}</small>
                                </td>
                                <td>
                                    <strong>{[{ call.phone_number }]}</strong>
                                </td>
                                <td>
                                    <small>{[{ call.user_name || 'Unknown' }]}</small>
                                </td>
                                <td>
                                    <span class="badge badge-info">{[{ call.extension }]}</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <!-- Pagination Controls -->
                    <nav ng-show="showPagination && totalPages > 1" class="text-right">
                        <ul class="pagination pagination-sm">
                            <li ng-class="{disabled: currentPage === 1}">
                                <a href="#" ng-click="goToPage(currentPage - 1)" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <li ng-repeat="page in getPageNumbers()" ng-class="{active: page === currentPage}">
                                <a href="#" ng-click="goToPage(page)">{[{ page }]}</a>
                            </li>
                            <li ng-class="{disabled: currentPage === totalPages}">
                                <a href="#" ng-click="goToPage(currentPage + 1)" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        `,
        link: function (scope, element, attrs) {
            scope.calls = [];
            scope.loading = false;
            scope.maxRecords = scope.maxRecords || 5;
            scope.showPagination = scope.showPagination !== 'false';

            // Pagination variables
            scope.currentPage = 1;
            scope.itemsPerPage = parseInt(scope.maxRecords) || 5;
            scope.totalPages = 1;
            scope.paginatedCalls = [];

            console.log('[Call History] Directive initialized with:', {
                taskId: scope.taskId,
                maxRecords: scope.maxRecords,
                attrs: attrs
            });

            // Load call history for this task
            scope.loadHistory = function () {
                console.log('[Call History] loadHistory called with taskId:', scope.taskId);
                if (!scope.taskId) {
                    console.warn('[Call History] No task ID provided');
                    return;
                }

                scope.loading = true;

                // Use the proper ThreeCX task logs endpoint
                $http.get('/api/threecx/logs/task', {
                    params: { task_id: scope.taskId }
                })
                    .then(function (response) {
                        scope.calls = response.data.data || response.data || [];
                        scope.loading = false;
                        scope.updatePagination();
                        console.log('[Call History] Loaded', scope.calls.length, 'calls for task', scope.taskId);
                        console.log('[Call History] Response data:', response.data);
                        if (scope.calls.length > 0) {
                            console.log('[Call History] Latest call:', scope.calls[0]);
                        }
                    })
                    .catch(function (error) {
                        console.error('[Call History] Failed to load task call logs:', error);
                        scope.calls = [];
                        scope.loading = false;

                        // Only show error if not a 404 (which just means no calls yet)
                        if (error.status !== 404) {
                            ErrorsHandler(error);
                        }
                    });
            };

            // Refresh call history
            scope.refresh = function () {
                scope.loadHistory();
            };

            // Pagination functions
            scope.updatePagination = function () {
                if (!scope.calls.length) {
                    scope.paginatedCalls = [];
                    scope.totalPages = 1;
                    scope.currentPage = 1;
                    return;
                }

                scope.totalPages = Math.ceil(scope.calls.length / scope.itemsPerPage);
                if (scope.currentPage > scope.totalPages) {
                    scope.currentPage = scope.totalPages;
                }

                var startIndex = (scope.currentPage - 1) * scope.itemsPerPage;
                var endIndex = startIndex + scope.itemsPerPage;
                scope.paginatedCalls = scope.calls.slice(startIndex, endIndex);
            };

            scope.goToPage = function (page) {
                if (page < 1 || page > scope.totalPages) return;
                scope.currentPage = page;
                scope.updatePagination();
            };

            scope.getPageNumbers = function () {
                var pages = [];
                var startPage = Math.max(1, scope.currentPage - 2);
                var endPage = Math.min(scope.totalPages, scope.currentPage + 2);

                for (var i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }
                return pages;
            };

            // Get label class for status
            scope.getStatusLabelClass = function (status) {
                switch (status) {
                    case 'answered':
                    case 'completed':
                        return 'label-success';
                    case 'missed':
                    case 'failed':
                        return 'label-warning';
                    case 'rejected':
                    case 'error':
                        return 'label-danger';
                    case 'ringing':
                    case 'connecting':
                        return 'label-info';
                    default:
                        return 'label-default';
                }
            };

            // Format call duration
            scope.formatDuration = function (duration) {
                if (!duration) return '-';

                const seconds = parseInt(duration);
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;

                if (minutes > 0) {
                    return minutes + 'm ' + remainingSeconds + 's';
                }
                return seconds + 's';
            };

            // Get formatted status with rejection reasons
            scope.getFormattedStatus = function (call) {
                switch (call.status) {
                    case 'rejected':
                    case 'failed':
                        if (call.extension) {
                            return 'Rejected by ' + call.extension;
                        }
                        return 'Rejected by client';
                    case 'answered':
                    case 'completed':
                        if (call.extension) {
                            return 'Answered by ' + call.extension;
                        }
                        return 'Answered';
                    case 'missed':
                        return 'Missed call';
                    case 'cancelled':
                        return 'Cancelled';
                    case 'busy':
                        return 'Line busy';
                    case 'no_answer':
                        return 'No answer';
                    default:
                        return call.status ? call.status.charAt(0).toUpperCase() + call.status.slice(1) : 'Unknown';
                }
            };


            // Manual refresh function for when call dialog closes
            if (scope.taskId) {
                window.refreshCallHistory = function () {
                    console.log('[Call History] Manual refresh triggered by call dialog close');
                    scope.loadHistory();
                    if (!scope.$$phase) {
                        scope.$apply();
                    }
                };
            }

            // Auto-load on initialization
            scope.loadHistory();
        }
    };
}]);

// Add capitalize filter if not exists
angular.module('archDB').filter('capitalize', function () {
    return function (input) {
        if (!input) return '';
        return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
    };
});
