// applied-jobs.js
$(document).ready(function() {
    // State management
    let currentPage = 1;
    let hasMorePages = true;
    let isLoading = false;
    let currentFilters = {
        search: '',
        status: '',
        sort_by: 'created_at',
        sort_order: 'desc',
        per_page: 10
    };

    // Initialize
    loadApplicationStats();
    loadApplications();

    // Search handler with debounce
    let searchTimeout;
    $('#searchInput').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentFilters.search = $(this).val();
            resetAndReload();
        }, 500);
    });

    // Filter handlers
    $('#statusFilter').on('change', function() {
        currentFilters.status = $(this).val();
        resetAndReload();
    });

    // Sort handlers
    $('#sortBy, #sortOrder').on('change', function() {
        currentFilters.sort_by = $('#sortBy').val();
        currentFilters.sort_order = $('#sortOrder').val();
        resetAndReload();
    });

    // Load more handler
    $('#loadMoreBtn').on('click', function() {
        if (!isLoading && hasMorePages) {
            currentPage++;
            loadApplications(true);
        }
    });

    // Withdraw application handler
    $(document).on('click', '.withdraw-application', function(e) {
        e.preventDefault();
        const applicationId = $(this).data('id');
        
        myAlert.fire({
            title: 'Withdraw Application',
            text: 'Are you sure you want to withdraw this application?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, withdraw',
            cancelButtonText: 'No, keep it'
        }).then((result) => {
            if (result.isConfirmed) {
                withdrawApplication(applicationId);
            }
        });
    });

    // Load application statistics
    function loadApplicationStats() {
        axios.get(`${base_url}/webapi/jobs/my-applications/stats`)
            .then(response => {
                if (response.data.code === 200) {
                    const stats = response.data.data;
                    updateStatistics(stats);
                    if (stats.application_trends) {
                        renderApplicationTrends(stats.application_trends);
                    }
                }
            })
            .catch(error => {
                console.error('Error loading stats:', error);
            });
    }

    // Load applications
    function loadApplications(append = false) {
        if (isLoading) return;
        isLoading = true;

        if (!append) {
            showLoader('#applicationsList');
        }

        const params = {
            ...currentFilters,
            page: currentPage
        };

        axios.get(`${base_url}/webapi/jobs/my-applications`, { params })
            .then(response => {
                if (response.data.code === 200) {
                    const { data, meta } = response.data;
                    
                    if (!append) {
                        $('#applicationsList').empty();
                    }

                    if (data.length === 0 && currentPage === 1) {
                        $('#emptyState').show();
                        $('#loadMoreContainer').hide();
                        return;
                    }

                    $('#emptyState').hide();
                    renderApplications(data);
                    
                    // Update load more button
                    hasMorePages = meta.current_page < meta.last_page;
                    $('#loadMoreContainer').toggle(hasMorePages);
                }
            })
            .catch(error => {
                console.error('Error loading applications:', error);
                showError('Error loading applications. Please try again.');
            })
            .finally(() => {
                isLoading = false;
                hideLoader('#applicationsList');
            });
    }

    // View application details
    function viewApplicationDetails(applicationId) {
        showLoader('#applicationDetails');
        $('#applicationModal').modal('show');

        axios.get(`${base_url}/webapi/jobs/applications/${applicationId}`)
            .then(response => {
                if (response.data.code === 200) {
                    const application = response.data.data;
                    renderApplicationDetails(application);
                }
            })
            .catch(error => {
                console.error('Error loading application details:', error);
                showError('Error loading application details. Please try again.');
                $('#applicationModal').modal('hide');
            })
            .finally(() => {
                hideLoader('#applicationDetails');
            });
    }

    // Withdraw application
    function withdrawApplication(applicationId) {
        axios.post(`${base_url}/webapi/jobs/applications/${applicationId}/withdraw`)
            .then(response => {
                if (response.data.code === 200) {
                    showSuccess('Application withdrawn successfully');
                    resetAndReload();
                    loadApplicationStats();
                }
            })
            .catch(error => {
                console.error('Error withdrawing application:', error);
                showError(error.response?.data?.message || 'Error withdrawing application. Please try again.');
            });
    }

    // Update statistics display
    function updateStatistics(stats) {
        // Update count cards with animation
        animateCount('#totalApplications', stats.total || 0);
        animateCount('#pendingApplications', stats.by_status?.pending || 0);
        animateCount('#shortlistedApplications', stats.by_status?.shortlisted || 0);
        animateCount('#rejectedApplications', stats.by_status?.rejected || 0);

        // Update status filter counts
        Object.entries(stats.by_status || {}).forEach(([status, count]) => {
            $(`#statusFilter option[value="${status}"]`).text(
                `${capitalizeFirst(status)} (${count})`
            );
        });

        // Update success rate if available
        if (stats.success_rate) {
            renderSuccessRate(stats.success_rate);
        }

        // Update popular categories if available
        if (stats.popular_categories) {
            renderPopularCategories(stats.popular_categories);
        }
    }

    // Render applications list
    function renderApplications(applications) {
        applications.forEach(application => {
            const card = createApplicationCard(application);
            $('#applicationsList').append(card);
        });

        // Initialize tooltips
        $('[data-bs-toggle="tooltip"]').tooltip();
    }

    // Create application card
    function createApplicationCard(application) {
        const statusClasses = {
            pending: 'warning',
            shortlisted: 'info',
            interviewed: 'primary',
            rejected: 'danger',
            hired: 'success'
        };

        return `
            <div class="card border-0 shadow-sm mb-4 application-card" data-id="${application.id}">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <img src="${application.job.company_logo || '/assets/images/companies/default.jpg'}" 
                                 class="rounded-3" style="width: 80px; height: 80px; object-fit: cover;"
                                 alt="${application.job.company_name}">
                        </div>
                        <div class="col">
                            <h5 class="card-title mb-1">${application.job.job_title}</h5>
                            <p class="text-primary mb-2">${application.job.company_name}</p>
                            <div class="d-flex flex-wrap gap-2">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-map-marker-alt me-1"></i>${application.job.job_location}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-briefcase me-1"></i>${application.job.job_type}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-calendar-alt me-1"></i>Applied ${moment(application.created_at).fromNow()}
                                </span>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="d-flex flex-column align-items-end">
                                <span class="badge bg-${statusClasses[application.status]} mb-2">
                                    ${capitalizeFirst(application.status)}
                                </span>
                                <div class="btn-group">
                                    <button class="btn btn-sm btn-outline-primary" 
                                            onclick="viewApplicationDetails(${application.id})">
                                        View Details
                                    </button>
                                    ${application.status === 'pending' ? `
                                        <button class="btn btn-sm btn-outline-danger withdraw-application" 
                                                data-id="${application.id}">
                                            Withdraw
                                        </button>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // Render success rate chart
    function renderSuccessRate(rate) {
        const chart = new ApexCharts(document.querySelector("#successRateChart"), {
            series: [rate],
            chart: {
                height: 250,
                type: 'radialBar',
            },
            plotOptions: {
                radialBar: {
                    hollow: {
                        size: '70%',
                    },
                    dataLabels: {
                        show: true,
                        name: {
                            show: true,
                            fontSize: '16px',
                            fontWeight: 600,
                            offsetY: -10
                        },
                        value: {
                            show: true,
                            fontSize: '30px',
                            fontWeight: 700,
                            formatter: function(val) {
                                return val + '%';
                            }
                        }
                    }
                }
            },
            labels: ['Success Rate'],
            colors: ['#0d6efd']
        });

        chart.render();
    }

    // Render application trends chart
    function renderApplicationTrends(trends) {
        const chart = new ApexCharts(document.querySelector("#applicationTrendsChart"), {
            series: [{
                name: 'Total Applications',
                data: trends.map(t => t.total_applications)
            }, {
                name: 'Successful Applications',
                data: trends.map(t => t.successful_applications)
            }],
            chart: {
                height: 350,
                type: 'line',
                toolbar: {
                    show: false
                }
            },
            stroke: {
                width: [3, 3],
                curve: 'smooth'
            },
            xaxis: {
                categories: trends.map(t => moment(t.month).format('MMM YYYY'))
            },
            colors: ['#0d6efd', '#198754'],
            legend: {
                position: 'top'
            }
        });

        chart.render();
    }

    // Helper functions
    function capitalizeFirst(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    function resetAndReload() {
        currentPage = 1;
        hasMorePages = true;
        loadApplications();
    }

    function showLoader(container) {
        $(container).html(`
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        `);
    }

    function hideLoader(container) {
        $(container).find('.spinner-border').parent().remove();
    }

    function showSuccess(message) {
        myAlert.fire({
            icon: 'success',
            title: 'Success',
            text: message
        });
    }

    function showError(message) {
        myAlert.fire({
            icon: 'error',
            title: 'Error',
            text: message
        });
    }

    // Make viewApplicationDetails available globally
    window.viewApplicationDetails = viewApplicationDetails;
});