const { readDb, writeDb } = require('../config/db');
const { getAccountStatus, getDropletCount, getAccountBalance } = require('../utils/digitalocean');

const userState = {};

function showApiMenu(bot, chatId) {
    const message = "<b>🔑 Manajemen API Key</b>\n\nPilih aksi yang Anda inginkan:";
    bot.sendMessage(chatId, message, {
        parse_mode: 'HTML',
        reply_markup: {
            inline_keyboard: [
                [{ text: '➕ Tambah API', callback_data: 'api_add' }],
                [{ text: '➖ Hapus API', callback_data: 'api_delete_menu' }],
                [{ text: '📊 List API', callback_data: 'api_list' }]
            ]
        }
    });
}

// === FUNGSI BARU: MENAMPILKAN SALDO AKUN ===
async function showAccountBalance(bot, chatId) {
    const loadingMessage = await bot.sendMessage(chatId, '⏳ Sedang mengambil data saldo...');
    const db = await readDb();
    const apiKeys = Object.keys(db).filter(key => db[key] && db[key].token);
    
    if (apiKeys.length === 0) {
        await bot.editMessageText('ℹ️ Tidak ada API Key yang tersimpan.', { chat_id: chatId, message_id: loadingMessage.message_id });
        return;
    }

    let message = '💰 <b>Status Saldo Semua Akun</b> 💰\n\n';
    
    for (const key of apiKeys) {
        const token = db[key].token;
        const balanceRes = await getAccountBalance(token);
        const dropletCountRes = await getDropletCount(token);
        
        message += `<b>Nama Akun: ${key}</b>\n`;
        
        if (balanceRes.success) {
            const balance = parseFloat(balanceRes.data.account_balance).toFixed(2);
            const monthToDate = parseFloat(balanceRes.data.month_to_date_balance).toFixed(2);
            message += `├─ Saldo Tersisa: $${balance} USD\n`;
            message += `└─ Biaya Bulan Ini: $${monthToDate} USD\n`;
        } else {
            message += `└─ Status Saldo: ❌ Gagal (${balanceRes.message})\n`;
        }

        if (dropletCountRes.success) {
            message += `  └ Jumlah Droplet: 💧 ${dropletCountRes.total}\n\n`;
        } else {
            message += `  └ Jumlah Droplet: ❌ Gagal (${dropletCountRes.message})\n\n`;
        }
    }
    
    await bot.editMessageText(message, { chat_id: chatId, message_id: loadingMessage.message_id, parse_mode: 'HTML' });
}


// === FUNGSI-FUNGSI AKSI ===

function handleAddApi(bot, chatId) {
    bot.sendMessage(chatId, '📝 Masukkan nama untuk API Key ini (bisa nama apa saja):');
    userState[chatId] = { step: 'api_add_name' };
}

async function askApiType(bot, chatId) {
    const keyboard = {
        inline_keyboard: [
            [{ text: '☀️ Harian (untuk < 15 hari)', callback_data: 'api_add_type_harian' }],
            [{ text: '🌙 Bulanan (untuk > 15 hari)', callback_data: 'api_add_type_bulanan' }]
        ]
    };
    await bot.sendMessage(chatId, 'Pilih tipe penggunaan untuk API Key ini:', { reply_markup: keyboard });
}

async function handleDeleteApiMenu(bot, chatId) {
    const db = await readDb();
    const apiKeys = Object.keys(db);
    if (apiKeys.length === 0) {
        bot.sendMessage(chatId, 'ℹ️ Tidak ada API Key yang tersimpan.').then(() => setTimeout(() => showApiMenu(bot, chatId), 1500));
        return;
    }

    const keyboard = [];
    const harianApis = apiKeys.filter(key => db[key].type === 'harian');
    const bulananApis = apiKeys.filter(key => db[key].type === 'bulanan');
    const lainnyaApis = apiKeys.filter(key => !db[key].type); // Untuk kompatibilitas

    if (harianApis.length > 0) {
        keyboard.push([{ text: '--- ☀️ API Harian ---', callback_data: 'no_action' }]);
        harianApis.forEach(key => keyboard.push([{ text: `🗑️ ${key}`, callback_data: `api_delete_confirm_${key}` }]));
    }
    if (bulananApis.length > 0) {
        keyboard.push([{ text: '--- 🌙 API Bulanan ---', callback_data: 'no_action' }]);
        bulananApis.forEach(key => keyboard.push([{ text: `🗑️ ${key}`, callback_data: `api_delete_confirm_${key}` }]));
    }
     if (lainnyaApis.length > 0) {
        keyboard.push([{ text: '--- Lainnya (Tanpa Tipe) ---', callback_data: 'no_action' }]);
        lainnyaApis.forEach(key => keyboard.push([{ text: `🗑️ ${key}`, callback_data: `api_delete_confirm_${key}` }]));
    }

    keyboard.push([{ text: '↩️ Kembali', callback_data: 'api_show_menu' }]);
    bot.sendMessage(chatId, '👇 Pilih API Key yang akan dihapus:', { reply_markup: { inline_keyboard: keyboard } });
}

async function handleListApi(bot, chatId) {
    const loadingMessage = await bot.sendMessage(chatId, '⏳ Sedang mengambil data...');
    const db = await readDb();
    const apiKeys = Object.keys(db);
    const backKeyboard = { inline_keyboard: [[{ text: '↩️ Kembali ke Menu API', callback_data: 'api_show_menu' }]] };

    if (apiKeys.length === 0) {
        bot.editMessageText('ℹ️ Tidak ada API Key yang tersimpan.', { chat_id: chatId, message_id: loadingMessage.message_id, reply_markup: backKeyboard });
        return;
    }
    
    let message = '📊 <b>Daftar API Key Anda</b> 📊\n\n';
    const harianApis = apiKeys.filter(key => db[key].type === 'harian');
    const bulananApis = apiKeys.filter(key => db[key].type === 'bulanan');
    const lainnyaApis = apiKeys.filter(key => !db[key].type);

    const processApiGroup = async (keys, title) => {
        if (keys.length === 0) return '';
        let groupMessage = `<b>${title}</b>\n`;
        const promises = keys.map(async (name) => {
            const token = db[name]?.token;
            if (!token) return { name, error: 'Token tidak ditemukan.' };
            const [status, count] = await Promise.all([getAccountStatus(token), getDropletCount(token)]);
            return { name, status, count };
        });
        const results = await Promise.all(promises);
        for (const res of results) {
            groupMessage += `▪️ <b>Nama:</b> <code>${res.name}</code>\n`;
            if (res.error) {
                groupMessage += `  └ Status: ❌ Error (${res.error})\n\n`;
            } else if (res.status.success) {
                const icon = res.status.data.status === 'active' ? '✅' : '⚠️';
                const dropletCount = res.count.success ? res.count.total : 'N/A';
                const dropletLimit = res.status.data.droplet_limit;
                // Menggabungkan jumlah droplet aktif dan limitnya
                const dropletUsageText = res.count.success ? `${dropletCount}/${dropletLimit}` : 'N/A';
                groupMessage += `  ├ Email: ${res.status.data.email}\n  ├ Status: ${icon} ${res.status.data.status}\n  └ Droplets: 💧 ${dropletUsageText}\n\n`;
            } else {
                groupMessage += `  └ Status: ❌ Token tidak valid\n\n`;
            }
        }
        return groupMessage;
    };

    message += await processApiGroup(harianApis, '☀️ API Harian');
    message += await processApiGroup(bulananApis, '🌙 API Bulanan');
    message += await processApiGroup(lainnyaApis, '🔧 Lainnya (Tanpa Tipe)');

    bot.editMessageText(message, { chat_id: chatId, message_id: loadingMessage.message_id, parse_mode: 'HTML', reply_markup: backKeyboard });
}

// === PENGELOLA EVENT (ROUTER INTERNAL) ===

async function handleTextMessage(bot, msg) {
    const chatId = msg.chat.id;
    if (!userState[chatId]) return false;

    const state = userState[chatId];
    const text = msg.text;

    if (state.step === 'api_add_name') {
        userState[chatId].name = text;
        userState[chatId].step = 'api_add_type';
        await askApiType(bot, chatId);
    } else if (state.step === 'api_add_token') {
        const { name, type } = state;
        delete userState[chatId];
        const loading = await bot.sendMessage(chatId, 'Verifikasi token...');
        const status = await getAccountStatus(text);
        let resultMsg;
        if (!status.success) {
            resultMsg = `❌ Token tidak valid: ${status.message}.`;
        } else {
            const db = await readDb();
            if (db[name]) {
                resultMsg = '⚠️ Nama API sudah ada.';
            } else {
                db[name] = { token: text, type: type }; // Simpan dengan tipe
                await writeDb(db);
                resultMsg = `✅ API Key "<b>${name}</b>" (Tipe: ${type}) berhasil ditambahkan.`;
            }
        }
        await bot.editMessageText(resultMsg, { chat_id: chatId, message_id: loading.message_id, parse_mode: 'HTML' });
        setTimeout(() => showApiMenu(bot, chatId), 1500);
    }
    return true;
}

async function handleCallbackQuery(bot, callbackQuery) {
    const data = callbackQuery.data;
    if (!data.startsWith('api_')) return false;

    const msg = callbackQuery.message;
    const chatId = msg.chat.id;
    
    if (data !== 'api_list' && data !== 'api_delete_menu') {
        await bot.deleteMessage(chatId, msg.message_id).catch(() => {});
    }

    if (data === 'api_show_menu') {
        showApiMenu(bot, chatId);
    } else if (data === 'api_add') {
        handleAddApi(bot, chatId);
    } else if (data.startsWith('api_add_type_')) {
        const type = data.replace('api_add_type_', '');
        userState[chatId].type = type;
        userState[chatId].step = 'api_add_token';
        bot.sendMessage(chatId, `🔑 Tipe "${type}" dipilih. Sekarang, masukkan token DigitalOcean API:`);
    } else if (data === 'api_delete_menu') {
        await bot.deleteMessage(chatId, msg.message_id).catch(() => {});
        await handleDeleteApiMenu(bot, chatId);
    } else if (data === 'api_list') {
        await bot.deleteMessage(chatId, msg.message_id).catch(() => {});
        await handleListApi(bot, chatId);
    } else if (data.startsWith('api_delete_confirm_')) {
        const key = data.replace('api_delete_confirm_', '');
        const db = await readDb();
        let message;
        if (db[key]) {
            delete db[key];
            await writeDb(db);
            message = `✅ API Key "<b>${key}</b>" telah dihapus.`;
        } else {
            message = `ℹ️ API Key "<b>${key}</b>" tidak ditemukan.`;
        }
        await bot.sendMessage(chatId, message, { parse_mode: 'HTML' });
        setTimeout(() => showApiMenu(bot, chatId), 1500);
    }
    return true;
}

module.exports = {
    showApiMenu,
    handleTextMessage,
    handleCallbackQuery,
    showAccountBalance
};
