// Trial Period Management JavaScript
// This file contains all trial period related functionality

// Global variables for trial periods
let currentCustomerId = null;
let currentTrialPeriods = [];

// Initialize trial period modals and event listeners
function initTrialPeriodManagement() {
    const addTrialPeriodModal = document.getElementById('addTrialPeriodModal');
    const editTrialPeriodModal = document.getElementById('editTrialPeriodModal');
    const addTrialPeriodBtn = document.getElementById('addTrialPeriodBtn');
    const addTrialPeriodForm = document.getElementById('addTrialPeriodForm');
    const editTrialPeriodForm = document.getElementById('editTrialPeriodForm');

    // Add trial period button click
    if (addTrialPeriodBtn) {
        addTrialPeriodBtn.addEventListener('click', function () {
            document.getElementById('trialCustomerId').value = currentCustomerId;
            addTrialPeriodModal.style.display = 'block';
        });
    }

    // Close modals
    const closeButtons = document.querySelectorAll('.close');
    closeButtons.forEach(btn => {
        btn.addEventListener('click', function () {
            const modal = this.closest('.modal');
            if (modal) {
                modal.style.display = 'none';
            }
        });
    });

    // Cancel buttons
    document.querySelector('.cancel-trial')?.addEventListener('click', function () {
        addTrialPeriodModal.style.display = 'none';
    });

    document.querySelector('.cancel-edit-trial')?.addEventListener('click', function () {
        editTrialPeriodModal.style.display = 'none';
    });

    // Add trial period form submit
    if (addTrialPeriodForm) {
        addTrialPeriodForm.addEventListener('submit', async function (e) {
            e.preventDefault();
            await createTrialPeriod();
        });
    }

    // Edit trial period form submit
    if (editTrialPeriodForm) {
        editTrialPeriodForm.addEventListener('submit', async function (e) {
            e.preventDefault();
            await updateTrialPeriod();
        });
    }

    // Click outside modal to close
    window.addEventListener('click', function (e) {
        if (e.target === addTrialPeriodModal) {
            addTrialPeriodModal.style.display = 'none';
        }
        if (e.target === editTrialPeriodModal) {
            editTrialPeriodModal.style.display = 'none';
        }
    });
}

// Load trial periods for a customer
async function loadTrialPeriods(customerId) {
    currentCustomerId = customerId;

    try {
        const response = await authenticatedFetch(`/api/trial-periods?customerId=${customerId}`);
        const data = await response.json();

        currentTrialPeriods = data.trialPeriods || [];
        renderTrialPeriods();
    } catch (error) {
        console.error('Error loading trial periods:', error);
        currentTrialPeriods = [];
        renderTrialPeriods();
    }
}

// Render trial periods table
function renderTrialPeriods() {
    const tbody = document.getElementById('trialPeriodsTableBody');
    const noDataMessage = document.getElementById('noTrialPeriodsMessage');
    const table = document.querySelector('.trial-periods-table');

    if (!tbody) return;

    tbody.innerHTML = '';

    if (currentTrialPeriods.length === 0) {
        table.style.display = 'none';
        noDataMessage.style.display = 'block';
        return;
    }

    table.style.display = 'table';
    noDataMessage.style.display = 'none';

    currentTrialPeriods.forEach(period => {
        const row = document.createElement('tr');

        const startTime = formatDateTime(period.startTime);
        const endTime = formatDateTime(period.endTime);

        row.innerHTML = `
            <td>${startTime}</td>
            <td>${endTime}</td>
            <td>
                <div class="trial-action-btns">
                    <button class="action-btn edit-btn" data-id="${period.id}" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="action-btn delete-btn" data-id="${period.id}" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        `;

        tbody.appendChild(row);
    });

    // Add event listeners to edit and delete buttons
    tbody.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const periodId = this.getAttribute('data-id');
            openEditTrialPeriodModal(periodId);
        });
    });

    tbody.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const periodId = this.getAttribute('data-id');
            deleteTrialPeriod(periodId);
        });
    });
}

// Format datetime for display
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';

    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}/${month}/${day} ${hours}:${minutes}`;
}

// Create trial period
async function createTrialPeriod() {
    const customerId = document.getElementById('trialCustomerId').value;
    const startTime = document.getElementById('trialStartTime').value;
    const endTime = document.getElementById('trialEndTime').value;

    if (!startTime || !endTime) {
        alert('请填写开始时间和结束时间');
        return;
    }

    const formData = {
        customerId: customerId,
        startTime: new Date(startTime).toISOString(),
        endTime: new Date(endTime).toISOString()
    };

    try {
        const response = await authenticatedFetch('/api/trial-periods', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });

        if (response.ok) {
            document.getElementById('addTrialPeriodModal').style.display = 'none';
            document.getElementById('addTrialPeriodForm').reset();
            await loadTrialPeriods(customerId);
            alert('试用时间添加成功！');
        } else {
            alert('添加试用时间时出错');
        }
    } catch (error) {
        console.error('Error creating trial period:', error);
        alert('添加试用时间时出错');
    }
}

// Open edit trial period modal
function openEditTrialPeriodModal(periodId) {
    const period = currentTrialPeriods.find(p => p.id === periodId);
    if (!period) return;

    document.getElementById('editTrialPeriodId').value = period.id;

    // Convert ISO string to datetime-local format
    const startDate = new Date(period.startTime);
    const endDate = new Date(period.endTime);

    document.getElementById('editTrialStartTime').value = formatDateTimeLocal(startDate);
    document.getElementById('editTrialEndTime').value = formatDateTimeLocal(endDate);

    document.getElementById('editTrialPeriodModal').style.display = 'block';
}

// Format date to datetime-local input format
function formatDateTimeLocal(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// Update trial period
async function updateTrialPeriod() {
    const periodId = document.getElementById('editTrialPeriodId').value;
    const startTime = document.getElementById('editTrialStartTime').value;
    const endTime = document.getElementById('editTrialEndTime').value;

    // Get source value
    const sourceEl = document.getElementById('editTrialCustomerSource');
    const source = sourceEl ? sourceEl.value.trim() : '';

    // Get isTrial value from radio buttons
    const isTrialRadio = document.querySelector('input[name="editIsTrial"]:checked');
    const isTrial = isTrialRadio ? isTrialRadio.value === 'true' : true;

    if (!startTime || !endTime) {
        alert('请填写开始时间和结束时间');
        return;
    }

    const formData = {
        source: source,
        startTime: new Date(startTime).toISOString(),
        endTime: new Date(endTime).toISOString(),
        isTrial: isTrial
    };

    try {
        const response = await authenticatedFetch(`/api/trial-periods/${periodId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });

        if (response.ok) {
            document.getElementById('editTrialPeriodModal').style.display = 'none';
            // Load trial periods for specific customer (for embedded list)
            if (currentCustomerId) {
                await loadTrialPeriods(currentCustomerId);
            }
            // Also refresh the main trial periods page list
            if (typeof loadAllTrialPeriods === 'function') {
                await loadAllTrialPeriods();
            }
            alert('试用时间更新成功！');
        } else {
            alert('更新试用时间时出错');
        }
    } catch (error) {
        console.error('Error updating trial period:', error);
        alert('更新试用时间时出错');
    }
}

// Delete trial period
async function deleteTrialPeriod(periodId) {
    if (!confirm('确定要删除这个试用时间记录吗？')) {
        return;
    }

    try {
        const response = await authenticatedFetch(`/api/trial-periods/${periodId}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            await loadTrialPeriods(currentCustomerId);
            alert('试用时间删除成功！');
        } else {
            alert('删除试用时间时出错');
        }
    } catch (error) {
        console.error('Error deleting trial period:', error);
        alert('删除试用时间时出错');
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function () {
    initTrialPeriodManagement();
});
