const { SlashCommandBuilder, EmbedBuilder, AttachmentBuilder } = require('discord.js');
const { getServerMode } = require('../utils/modeHelper');

function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

function rgbToHsl(r, g, b) {
  r /= 255; g /= 255; b /= 255;
  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  let h, s, l = (max + min) / 2;

  if (max === min) {
    h = s = 0;
  } else {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
      case g: h = ((b - r) / d + 2) / 6; break;
      case b: h = ((r - g) / d + 4) / 6; break;
    }
  }

  return {
    h: Math.round(h * 360),
    s: Math.round(s * 100),
    l: Math.round(l * 100)
  };
}

module.exports = {
  data: new SlashCommandBuilder()
    .setName('color')
    .setDescription('View color information')
    .addStringOption(option =>
      option.setName('hex')
        .setDescription('Hex color code (e.g., #FF5733 or FF5733)')
        .setRequired(false)
    )
    .addIntegerOption(option =>
      option.setName('red')
        .setDescription('Red value (0-255)')
        .setRequired(false)
        .setMinValue(0)
        .setMaxValue(255)
    )
    .addIntegerOption(option =>
      option.setName('green')
        .setDescription('Green value (0-255)')
        .setRequired(false)
        .setMinValue(0)
        .setMaxValue(255)
    )
    .addIntegerOption(option =>
      option.setName('blue')
        .setDescription('Blue value (0-255)')
        .setRequired(false)
        .setMinValue(0)
        .setMaxValue(255)
    ),

  async execute(interaction, supabase, client) {
    const hexInput = interaction.options.getString('hex');
    const red = interaction.options.getInteger('red');
    const green = interaction.options.getInteger('green');
    const blue = interaction.options.getInteger('blue');

    let r, g, b, hexColor;

    if (hexInput) {
      const rgb = hexToRgb(hexInput);
      if (!rgb) {
        return interaction.reply({
          content: 'Invalid hex color. Use format like #FF5733 or FF5733.',
          ephemeral: true
        });
      }
      r = rgb.r;
      g = rgb.g;
      b = rgb.b;
      hexColor = hexInput.replace('#', '').toUpperCase();
    } else if (red !== null && green !== null && blue !== null) {
      r = red;
      g = green;
      b = blue;
      hexColor = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
    } else if (red !== null || green !== null || blue !== null) {
      return interaction.reply({
        content: 'Please provide all RGB values (red, green, blue) or use a hex code.',
        ephemeral: true
      });
    } else {
      r = Math.floor(Math.random() * 256);
      g = Math.floor(Math.random() * 256);
      b = Math.floor(Math.random() * 256);
      hexColor = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
    }

    const hsl = rgbToHsl(r, g, b);
    const colorInt = parseInt(hexColor, 16);

    const embed = new EmbedBuilder()
      .setColor(colorInt)
      .setTitle(`🎨 Color: #${hexColor}`)
      .addFields(
        { name: 'Hex', value: `\`#${hexColor}\``, inline: true },
        { name: 'RGB', value: `\`rgb(${r}, ${g}, ${b})\``, inline: true },
        { name: 'HSL', value: `\`hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)\``, inline: true },
        { name: 'Integer', value: `\`${colorInt}\``, inline: true }
      )
      .setThumbnail(`https://singlecolorimage.com/get/${hexColor}/100x100`)
      .setTimestamp();

    await interaction.reply({ embeds: [embed] });
  },
};
