import { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ChannelType, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder } from 'discord.js';
import { db, getGuildConfig, updateGuildConfig } from '../core/db.js';
import { closeTicket } from '../modules/ticket/buttons.js';

export default {
  data: new SlashCommandBuilder()
    .setName('ticket')
    .setDescription('Kelola sistem ticket/order')
    .addSubcommand(s => s
      .setName('panel')
      .setDescription('Kirim panel order')
      .addChannelOption(o => o.setName('channel').setDescription('Target channel').addChannelTypes(ChannelType.GuildText).setRequired(true))
      .addBooleanOption(o => o.setName('mention').setDescription('Mention @everyone?').setRequired(false)))
    .addSubcommand(s => s
      .setName('close')
      .setDescription('Tutup ticket ini')),
  async execute(interaction) {
    const sub = interaction.options.getSubcommand();

    if (sub === 'panel') {
      if (!interaction.member.permissions.has(PermissionFlagsBits.Administrator)) {
        return interaction.reply({ content: '❌ Admin only', ephemeral: true });
      }
      const ch = interaction.options.getChannel('channel');
      const mentionEveryone = interaction.options.getBoolean('mention') || false;
      const cfg = getGuildConfig(interaction.guildId);
      if (!cfg.ticket_category_id) {
        return interaction.reply({
          content: '⚠️ Belum ada ticket category. Run `/setup` → Ticket dulu.',
          ephemeral: true,
        });
      }

      const products = 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.guild_id = ? AND p.enabled = 1
        ORDER BY c.sort_order, p.sort_order, p.id
      `).all(interaction.guildId);

      if (!products.length) {
        return interaction.reply({
          content: '❌ Belum ada produk. Tambah produk di dashboard dulu.',
          ephemeral: true,
        });
      }

      const defaultRules = [
        '— Dilarang Mainin Tiket / Spam Order',
        '— Setiap Produk Memiliki Garansi Atau Tidak Ada Garansi Yang Berbeda',
        '— Harga Bisa Update Kapan Aja',
        '— Bayar Sesuai Harga Yang Tertera',
        '— Jangan Kabur Setelah Order',
      ];

      const ticketColor = cfg.ticket_color ? parseInt(cfg.ticket_color.replace('#', ''), 16) : 0x5865f2;

      const embed = new EmbedBuilder()
        .setTitle('🛒 ORDER PRODUK')
        .setColor(ticketColor)
        .setDescription([
          'Pilih Sesuai Kategori Yang Kamu Mau',
          '',
          '**Notes:**',
          ...defaultRules,
        ].join('\n'))
        .setFooter({ text: 'Pilih produk → lihat detail → klik ORDER' });

      const emojiStock = cfg.emoji_stock || '📦';

      const select = new StringSelectMenuBuilder()
        .setCustomId('order_select_product')
        .setPlaceholder('Pilih Di Sini')
        .addOptions(products.slice(0, 25).map(p => {
          const catLabel = p.category_name ? `${p.category_emoji || ''} ${p.category_name}` : 'Produk';
          const opt = {
            label: `${p.name}`.slice(0, 100),
            value: `${p.id}`,
            description: `${catLabel} — Rp${p.price.toLocaleString('id-ID')} | Stock: ${p.stock_count}`.slice(0, 100),
          };
          const customMatch = emojiStock.match(/<a?:(\w+):(\d+)>/);
          if (customMatch) opt.emoji = { id: customMatch[2], name: customMatch[1], animated: emojiStock.startsWith('<a:') };
          else opt.emoji = { name: emojiStock };
          return opt;
        }));

      const content = mentionEveryone ? '@everyone' : '';
      await ch.send({ content, embeds: [embed], components: [new ActionRowBuilder().addComponents(select)] });
      await interaction.reply({ content: `✅ Panel order dikirim ke ${ch}`, ephemeral: true });
      return;
    }

    if (sub === 'close') {
      await closeTicket(interaction);
    }
  },
};
