import { ChannelType, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { db, getGuildConfig, audit } from '../../core/db.js';
import { generateTranscript } from './transcript.js';

function emjText(tag) {
  if (!tag) return '';
  // Insert ZWSP after < to prevent Discord from parsing <:name:id> as emoji
  return tag.replace(/<(:\w+:)\d+>/g, '\u200B$1').replace(/<a?(:\w+:)\d+>/g, '\u200B$1');
}

export async function handleTicketButton(interaction, client) {
  const id = interaction.customId;

  // Step 1: User pilih produk dari dropdown
  if (id === 'order_select_product' && interaction.isStringSelectMenu()) {
    const productId = parseInt(interaction.values[0]);
    return showProductDetail(interaction, productId);
  }

  // Step 2: User klik tombol ORDER → tampil form
  if (id.startsWith('order_form:') && interaction.isButton()) {
    const productId = parseInt(id.split(':')[1]);
    return showOrderForm(interaction, productId);
  }

  // Step 3: User submit form → buka ticket
  if (id.startsWith('order_submit:') && interaction.isModalSubmit()) {
    const productId = parseInt(id.split(':')[1]);
    return createOrderTicket(interaction, productId);
  }

  // Staff confirm payment
  if (id.startsWith('order_confirm:') && interaction.isButton()) {
    const ticketId = parseInt(id.split(':')[1]);
    return confirmPayment(interaction, ticketId);
  }

  // Cancel order
  if (id.startsWith('order_cancel:') && interaction.isButton()) {
    const ticketId = parseInt(id.split(':')[1]);
    return cancelOrder(interaction, ticketId);
  }

  if (id === 'ticket_close') return closeTicket(interaction);
  if (id === 'ticket_claim') return claimTicket(interaction);
}

// Show product detail + tombol ORDER
async function showProductDetail(interaction, productId) {
  const product = db.prepare(`
    SELECT p.*, c.name AS category_name, c.emoji AS category_emoji,
      (SELECT COUNT(*) FROM stock WHERE product_id = p.id AND sold = 0) AS stock_count
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    WHERE p.id = ?
  `).get(productId);

  if (!product) {
    return interaction.reply({ content: '❌ Produk tidak ditemukan', ephemeral: true });
  }

  const cfg = getGuildConfig(interaction.guildId);
  const ep = cfg.emoji_price || '💰';
  const es = cfg.emoji_stock || '📦';
  const ek = cfg.emoji_sku || '🏷️';
  const ec = cfg.emoji_category || '📁';
  const ed = cfg.emoji_description || '📝';
  const eo = cfg.emoji_order || '🔵';
  const ticketColor = cfg.ticket_color ? parseInt(cfg.ticket_color.replace('#', ''), 16) : 0x5865f2;

  const priceText = product.price_max
    ? `Rp${product.price.toLocaleString('id-ID')} - Rp${product.price_max.toLocaleString('id-ID')}`
    : `Rp${product.price.toLocaleString('id-ID')}`;

  const skuText = product.sku ? `\`${product.sku}\`` : `#${product.id}`;
  const catText = product.category_name ? `${emjText(product.category_emoji || '')} ${product.category_name}` : '-';
  const stockText = product.stock_count > 0 ? `${es} ${product.stock_count} tersedia` : '❌ Habis';

  const desc = [
    `${ep} **Harga**\n${priceText}`,
    '',
    `${es} **Stock**\n${product.stock_count > 0 ? `${product.stock_count} tersedia` : '❌ Habis'}`,
    '',
    `${ek} **SKU**\n${skuText}`,
    '',
    `${ec} **Kategori**\n${catText}`,
  ];

  if (product.description) {
    desc.push('', `${ed} **Deskripsi**\n${product.description.slice(0, 500)}`);
  }

  const embed = new EmbedBuilder()
    .setTitle(`${product.category_emoji || '📦'} ${product.name}`)
    .setColor(product.stock_count > 0 ? ticketColor : 0xef4444)
    .setDescription(desc.join('\n'));

  if (product.image_url) embed.setImage(product.image_url);

  embed.setFooter({ text: 'Klik ORDER jika sudah yakin' });

  const orderBtn = new ButtonBuilder()
    .setCustomId(`order_form:${productId}`)
    .setLabel('ORDER SEKARANG')
    .setStyle(ButtonStyle.Primary)
    .setDisabled(product.stock_count === 0);

  const orderMatch = eo.match(/<a?:(\w+):(\d+)>/);
  if (orderMatch) orderBtn.setEmoji({ id: orderMatch[2], name: orderMatch[1], animated: eo.startsWith('<a:') });
  else orderBtn.setEmoji({ name: eo });

  const row = new ActionRowBuilder().addComponents(orderBtn);

  await interaction.reply({ embeds: [embed], components: [row], ephemeral: true });
}

// Show order form modal
async function showOrderForm(interaction, productId) {
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(productId);
  if (!product) {
    return interaction.reply({ content: '❌ Produk tidak ditemukan', ephemeral: true });
  }

  const modal = new ModalBuilder()
    .setCustomId(`order_submit:${productId}`)
    .setTitle(`Order: ${product.name.slice(0, 40)}`);

  const quantityInput = new TextInputBuilder()
    .setCustomId('quantity')
    .setLabel('Quantity (angka bulat, mis. 1)')
    .setStyle(TextInputStyle.Short)
    .setValue('1')
    .setPlaceholder('Cukup angka: 1, 2, 3 …')
    .setMinLength(1)
    .setMaxLength(3)
    .setRequired(true);

  const paymentInput = new TextInputBuilder()
    .setCustomId('payment_method')
    .setLabel('Metode Pembayaran')
    .setStyle(TextInputStyle.Short)
    .setPlaceholder('QRIS / Dana / OVO / Bank Transfer')
    .setRequired(true);

  const noteInput = new TextInputBuilder()
    .setCustomId('note')
    .setLabel('Catatan (opsional)')
    .setStyle(TextInputStyle.Paragraph)
    .setPlaceholder('Tulis catatan tambahan jika ada...')
    .setRequired(false);

  modal.addComponents(
    new ActionRowBuilder().addComponents(quantityInput),
    new ActionRowBuilder().addComponents(paymentInput),
    new ActionRowBuilder().addComponents(noteInput)
  );

  await interaction.showModal(modal);
}

// Create order ticket after form submitted
async function createOrderTicket(interaction, productId) {
  const cfg = getGuildConfig(interaction.guildId);
  if (!cfg.ticket_category_id) {
    return interaction.reply({ content: '❌ Ticket system belum di-setup', ephemeral: true });
  }

  const existing = db.prepare('SELECT * FROM tickets WHERE guild_id = ? AND user_id = ? AND status = ?')
    .get(interaction.guildId, interaction.user.id, 'open');
  if (existing) {
    return interaction.reply({ content: `❌ Kamu sudah punya order aktif: <#${existing.channel_id}>`, ephemeral: true });
  }

  await interaction.deferReply({ ephemeral: true });

  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(productId);
  if (!product) {
    return interaction.editReply({ content: '❌ Produk tidak ditemukan' });
  }

  const qtyRaw = (interaction.fields.getTextInputValue('quantity') || '').trim();
  const paymentMethod = interaction.fields.getTextInputValue('payment_method');
  const note = interaction.fields.getTextInputValue('note') || '-';

  // Quantity wajib INTEGER POSITIF murni. Tolak: kosong, huruf, desimal, negatif, nol.
  if (!/^\d+$/.test(qtyRaw)) {
    return interaction.editReply({ content: '❌ Quantity harus berupa angka bulat (contoh: 1, 2, 3). Tidak boleh huruf, desimal, atau negatif.' });
  }
  const quantity = parseInt(qtyRaw, 10);
  if (quantity < 1) {
    return interaction.editReply({ content: '❌ Quantity minimal 1.' });
  }

  // Batasi ke stok tersedia (kalau auto_delivery), maksimal 10 per order
  const availStock = db.prepare('SELECT COUNT(*) AS n FROM stock WHERE product_id = ? AND sold = 0').get(productId).n;
  const maxQty = product.auto_delivery ? Math.min(10, availStock) : 10;
  if (product.auto_delivery && availStock < 1) {
    return interaction.editReply({ content: '❌ Stok produk ini habis.' });
  }
  if (quantity > maxQty) {
    return interaction.editReply({ content: `❌ Quantity maksimal ${maxQty}${product.auto_delivery ? ` (stok tersedia: ${availStock})` : ''}.` });
  }

  const total = product.price * quantity;

  const overwrites = [
    { id: interaction.guildId, deny: [PermissionFlagsBits.ViewChannel] },
    {
      id: interaction.user.id,
      allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.AttachFiles, PermissionFlagsBits.ReadMessageHistory],
    },
  ];
  if (cfg.staff_role_id) {
    overwrites.push({
      id: cfg.staff_role_id,
      allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ManageMessages, PermissionFlagsBits.ReadMessageHistory],
    });
  }

  const ch = await interaction.guild.channels.create({
    name: `order-${interaction.user.username}`.toLowerCase().slice(0, 90),
    type: ChannelType.GuildText,
    parent: cfg.ticket_category_id,
    permissionOverwrites: overwrites,
  });

  const result = db.prepare(
    'INSERT INTO tickets (guild_id, user_id, channel_id, category, product_id) VALUES (?, ?, ?, ?, ?)'
  ).run(interaction.guildId, interaction.user.id, ch.id, 'order', productId);

  const skuText = product.sku ? `[${product.sku}]` : `#${productId}`;
  const embed = new EmbedBuilder()
    .setTitle('📦 ORDER BARU')
    .setColor(0xfbbf24)
    .addFields(
      { name: 'Produk', value: `${skuText} ${product.name}`, inline: true },
      { name: 'Quantity', value: `${quantity}`, inline: true },
      { name: 'Total', value: `Rp${total.toLocaleString('id-ID')}`, inline: true },
      { name: 'Metode Pembayaran', value: paymentMethod, inline: true },
      { name: 'Status', value: '⏳ Menunggu Pembayaran', inline: true },
      { name: 'Catatan', value: note, inline: false },
    )
    .setFooter({ text: `Ticket #${result.lastInsertRowid}` })
    .setTimestamp();

  const row = new ActionRowBuilder().addComponents(
    new ButtonBuilder().setCustomId(`order_confirm:${result.lastInsertRowid}`).setLabel('✅ Konfirmasi Bayar').setStyle(ButtonStyle.Success),
    new ButtonBuilder().setCustomId(`order_cancel:${result.lastInsertRowid}`).setLabel('❌ Cancel Order').setStyle(ButtonStyle.Danger),
    new ButtonBuilder().setCustomId('ticket_close').setLabel('🔒 Close Ticket').setStyle(ButtonStyle.Secondary),
  );

  const staffPing = cfg.staff_role_id ? `<@&${cfg.staff_role_id}>` : '';
  await ch.send({
    content: `${interaction.user} ${staffPing}`,
    embeds: [embed],
    components: [row],
  });

  audit(interaction.guildId, interaction.user.id, 'order:create', {
    ticket_id: result.lastInsertRowid,
    product_id: productId,
    product_name: product.name,
    quantity,
    total,
    payment_method: paymentMethod,
  });

  await interaction.editReply({ content: `✅ Order ticket dibuat: ${ch}\n\nSilakan tunggu staff untuk proses pembayaran.` });
}

// Staff confirm payment
async function confirmPayment(interaction, ticketId) {
  const cfg = getGuildConfig(interaction.guildId);
  const isStaff = interaction.member.permissions.has(PermissionFlagsBits.ManageMessages) ||
                  (cfg.staff_role_id && interaction.member.roles.cache.has(cfg.staff_role_id));
  if (!isStaff) return interaction.reply({ content: '❌ Staff only', ephemeral: true });

  const ticket = db.prepare('SELECT * FROM tickets WHERE id = ? AND status = ?').get(ticketId, 'open');
  if (!ticket) {
    return interaction.reply({ content: '❌ Ticket tidak ditemukan atau sudah closed', ephemeral: true });
  }

  await interaction.deferReply();

  const orderLog = db.prepare(`
    SELECT data FROM audit_log
    WHERE guild_id = ? AND action = 'order:create' AND json_extract(data, '$.ticket_id') = ?
    ORDER BY created_at DESC LIMIT 1
  `).get(interaction.guildId, ticketId);

  if (!orderLog) {
    return interaction.editReply({ content: '❌ Order data tidak ditemukan' });
  }

  const orderData = JSON.parse(orderLog.data);
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(orderData.product_id);

  if (!product || !product.sku) {
    return interaction.editReply({
      content: `❌ Produk tidak ditemukan atau belum punya SKU. Kirim manual: \`/send sku:... user:<@${ticket.user_id}> quantity:${orderData.quantity}\``,
    });
  }

  const stocks = db.prepare('SELECT * FROM stock WHERE product_id = ? AND sold = 0 LIMIT ?').all(orderData.product_id, orderData.quantity);
  if (stocks.length < orderData.quantity) {
    return interaction.editReply({
      content: `❌ Stock tidak cukup. Tersedia: ${stocks.length}, diminta: ${orderData.quantity}`,
    });
  }

  const tx = db.transaction(() => {
    for (const stock of stocks) {
      db.prepare('UPDATE stock SET sold = 1, sold_to = ?, sold_at = unixepoch() WHERE id = ?')
        .run(ticket.user_id, stock.id);
    }
  });
  tx();

  try {
    const user = await interaction.client.users.fetch(ticket.user_id);
    const deliveryContent = stocks.map(s => s.content).join('\n');

    const dmEmbed = new EmbedBuilder()
      .setTitle('✅ Pembayaran Dikonfirmasi')
      .setColor(0x10b981)
      .addFields(
        { name: 'Produk', value: `[${product.sku}] ${product.name}`, inline: true },
        { name: 'Quantity', value: `${orderData.quantity}`, inline: true },
        { name: 'Total', value: `Rp${orderData.total.toLocaleString('id-ID')}`, inline: true },
      )
      .setDescription('```\n' + deliveryContent + '\n```')
      .setTimestamp();

    await user.send({ embeds: [dmEmbed] });

    db.prepare('UPDATE tickets SET status = ? WHERE id = ?').run('completed', ticketId);
    audit(interaction.guildId, interaction.user.id, 'order:confirm', {
      ticket_id: ticketId,
      product_id: orderData.product_id,
      product_sku: product.sku,
      quantity: orderData.quantity,
    });

    await interaction.editReply({ content: `✅ Pembayaran dikonfirmasi! Produk dikirim ke ${user}. Ticket akan ditutup dalam 10 detik.` });
    setTimeout(() => interaction.channel.delete().catch(() => {}), 10000);
  } catch (e) {
    db.transaction(() => {
      for (const stock of stocks) {
        db.prepare('UPDATE stock SET sold = 0, sold_to = NULL, sold_at = NULL WHERE id = ?').run(stock.id);
      }
    })();
    return interaction.editReply({ content: `❌ Gagal kirim DM: ${e.message}. Stock di-rollback.` });
  }
}

// Cancel order
async function cancelOrder(interaction, ticketId) {
  const ticket = db.prepare('SELECT * FROM tickets WHERE id = ?').get(ticketId);
  if (!ticket) return interaction.reply({ content: '❌ Ticket tidak ditemukan', ephemeral: true });

  const cfg = getGuildConfig(interaction.guildId);
  const isStaff = interaction.member.permissions.has(PermissionFlagsBits.ManageMessages) ||
                  (cfg.staff_role_id && interaction.member.roles.cache.has(cfg.staff_role_id));
  const isOwner = interaction.user.id === ticket.user_id;

  if (!isStaff && !isOwner) {
    return interaction.reply({ content: '❌ Hanya staff atau pemilik ticket yang bisa cancel', ephemeral: true });
  }

  await interaction.reply({ content: '❌ Order dibatalkan. Ticket akan ditutup dalam 5 detik.' });
  db.prepare('UPDATE tickets SET status = ? WHERE id = ?').run('cancelled', ticketId);
  audit(interaction.guildId, interaction.user.id, 'order:cancel', { ticket_id: ticketId });

  setTimeout(() => interaction.channel.delete().catch(() => {}), 5000);
}

export async function closeTicket(interaction) {
  const ticket = db.prepare('SELECT * FROM tickets WHERE channel_id = ? AND status = ?')
    .get(interaction.channelId, 'open');
  if (!ticket) {
    return interaction.reply({ content: '❌ Ini bukan channel ticket aktif', ephemeral: true });
  }

  await interaction.reply({ content: '⏳ Membuat transcript...' });

  const transcriptPath = await generateTranscript(interaction.channel, ticket).catch(e => {
    console.error('[transcript]', e);
    return null;
  });

  db.prepare('UPDATE tickets SET status = ?, closed_at = unixepoch(), transcript_path = ? WHERE id = ?')
    .run('closed', transcriptPath, ticket.id);

  const cfg = getGuildConfig(interaction.guildId);
  if (cfg.log_channel_id) {
    const log = interaction.guild.channels.cache.get(cfg.log_channel_id);
    if (log) {
      const embed = new EmbedBuilder()
        .setTitle(`🔒 Ticket #${ticket.id} closed`)
        .setColor(0xef4444)
        .addFields(
          { name: 'Category', value: ticket.category || '_-_', inline: true },
          { name: 'Opened by', value: `<@${ticket.user_id}>`, inline: true },
          { name: 'Closed by', value: `<@${interaction.user.id}>`, inline: true },
        );
      const files = transcriptPath ? [{ attachment: transcriptPath, name: `ticket-${ticket.id}.html` }] : [];
      await log.send({ embeds: [embed], files }).catch(() => {});
    }
  }

  setTimeout(() => interaction.channel.delete().catch(() => {}), 5000);
}

async function claimTicket(interaction) {
  const cfg = getGuildConfig(interaction.guildId);
  const isStaff = interaction.member.permissions.has(PermissionFlagsBits.ManageMessages) ||
                  (cfg.staff_role_id && interaction.member.roles.cache.has(cfg.staff_role_id));
  if (!isStaff) return interaction.reply({ content: '❌ Staff only', ephemeral: true });

  await interaction.reply({
    embeds: [new EmbedBuilder()
      .setColor(0x10b981)
      .setDescription(`✋ Ticket di-claim oleh ${interaction.user}`)],
  });
}
