const fs = require('fs');
const path = require('path');
const { createCanvas, loadImage, registerFont } = require('canvas');

module.exports.config = {
  name: "menu",
  usePrefix: true,
  version: "6.0.0",
  hasPermssion: 0,
  credits: "Neon Team",
  description: "Hiển thị danh sách lệnh hoặc thông tin chi tiết về lệnh",
  commandCategory: "Tiện ích",
  usages: "menu [tên lệnh | danh mục | all]",
  cooldowns: 5
};

const createCyberImage = (textContent, type = 'menu') => {
  const lines = Array.isArray(textContent) ? textContent : textContent.split('\n').filter(line => line.trim());
  const lineHeight = 32;
  const padding = 40;
  const headerHeight = 80;
  
  const canvas = createCanvas(1000, headerHeight + (lines.length * lineHeight) + (padding * 2));
  const ctx = canvas.getContext('2d');

  const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
  gradient.addColorStop(0, '#0a0a0a');
  gradient.addColorStop(0.3, '#1a1a2e');
  gradient.addColorStop(0.7, '#16213e');
  gradient.addColorStop(1, '#0f0f23');
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  ctx.strokeStyle = '#00ffff';
  ctx.lineWidth = 3;
  ctx.setLineDash([10, 5]);
  ctx.strokeRect(15, 15, canvas.width - 30, canvas.height - 30);
  ctx.setLineDash([]);

  ctx.fillStyle = '#00ffff';
  ctx.shadowColor = '#00ffff';
  ctx.shadowBlur = 20;
  ctx.font = 'bold 28px Arial';
  ctx.textAlign = 'center';
  
  let title = 'CYBER CORE SYSTEM';
  if (type === 'command') title = 'COMMAND INFO';
  else if (type === 'category') title = 'CATEGORY LIST';
  
  ctx.fillText(title, canvas.width / 2, 50);
  ctx.shadowBlur = 0;

  ctx.strokeStyle = '#00ffff';
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.moveTo(padding, headerHeight - 10);
  ctx.lineTo(canvas.width - padding, headerHeight - 10);
  ctx.stroke();

  ctx.font = '20px monospace';
  ctx.textAlign = 'left';
  
  lines.forEach((line, index) => {
    const y = headerHeight + padding + (index * lineHeight);
    
    if (line.includes(':')) {
      const parts = line.split(':');
      ctx.fillStyle = '#00ffff';
      ctx.fillText(parts[0] + ':', 50, y);
      ctx.fillStyle = '#ffffff';
      ctx.fillText(parts.slice(1).join(':'), 50 + ctx.measureText(parts[0] + ': ').width, y);
    } else if (line.match(/^\d+\./)) {
      ctx.fillStyle = '#ff6b6b';
      const numPart = line.match(/^\d+\./)[0];
      ctx.fillText(numPart, 50, y);
      ctx.fillStyle = '#ffffff';
      ctx.fillText(line.substring(numPart.length), 50 + ctx.measureText(numPart + ' ').width, y);
    } else {
      ctx.fillStyle = line.includes('─') || line.includes('=') ? '#00ffff' : '#ffffff';
      ctx.fillText(line, 50, y);
    }

    if (index % 2 === 0) {
      ctx.fillStyle = 'rgba(0, 255, 255, 0.1)';
      ctx.fillRect(30, y - 20, canvas.width - 60, lineHeight - 2);
    }
  });

  const cornerSize = 20;
  ctx.strokeStyle = '#ff6b6b';
  ctx.lineWidth = 3;
  
  [[30, 30], [canvas.width - 30, 30], [30, canvas.height - 30], [canvas.width - 30, canvas.height - 30]].forEach(([x, y]) => {
    ctx.beginPath();
    if (x < canvas.width / 2) {
      ctx.moveTo(x, y + cornerSize);
      ctx.lineTo(x, y);
      ctx.lineTo(x + cornerSize, y);
    } else {
      ctx.moveTo(x - cornerSize, y);
      ctx.lineTo(x, y);
      ctx.lineTo(x, y + cornerSize);
    }
    if (y > canvas.height / 2) {
      ctx.moveTo(x < canvas.width / 2 ? x : x - cornerSize, y);
      ctx.lineTo(x, y);
      ctx.lineTo(x, y - cornerSize);
    }
    ctx.stroke();
  });

  return canvas.toBuffer('image/png');
};

const cleanupFiles = () => {
  const tempDir = __dirname;
  const tempFiles = fs.readdirSync(tempDir).filter(file => 
    file.endsWith('.png') && (
      file.includes('menu_') || 
      file.includes('allCommands_') || 
      file.includes('categoryCommands_') || 
      file === 'menu.png'
    )
  );
  
  tempFiles.forEach(file => {
    try {
      fs.unlinkSync(path.join(tempDir, file));
    } catch (err) {}
  });
};

module.exports.run = async function({ api, event, args, Users }) {
  const commandsPath = path.resolve(__dirname, '..', 'commands');
  const senderID = event.senderID;
  const userPermission = (await Users.getData(senderID)).data.permission || 0;

  try {
    const files = await fs.promises.readdir(commandsPath);
    let commandFiles = files.filter(file => file.endsWith('.js'));

    if (commandFiles.length === 0) {
      return api.sendMessage("║ SYSTEM ERROR ║ Không có lệnh nào trong database", event.threadID, event.messageID);
    }

    commandFiles = await Promise.all(commandFiles.map(async file => {
      try {
        const command = require(path.join(commandsPath, file));
        const stats = await fs.promises.stat(path.join(commandsPath, file));
        return {
          name: file.replace('.js', ''),
          config: command.config,
          lastUpdated: stats.mtime
        };
      } catch {
        return {
          name: file.replace('.js', ''),
          config: {
            description: 'System Error - Unable to load',
            credits: 'Unknown',
            version: 'Error',
            usages: 'Unavailable',
            cooldowns: 0,
            hasPermssion: 0,
            commandCategory: 'Error'
          },
          lastUpdated: null
        };
      }
    }));

    commandFiles = commandFiles.filter(cmd => userPermission >= cmd.config.hasPermssion);

    if (args.length === 0) {
      let categorizedCommands = {};
      commandFiles.forEach((cmd, idx) => {
        const category = cmd.config.commandCategory || 'Unknown';
        if (!categorizedCommands[category]) categorizedCommands[category] = [];
        categorizedCommands[category].push({ ...cmd, index: idx + 1 });
      });

      let menuLines = [
        "═══════════════════════════════════════",
        "         COMMAND CATEGORIES",
        "═══════════════════════════════════════",
        ""
      ];

      Object.keys(categorizedCommands).forEach((category, idx) => {
        menuLines.push(`${idx + 1}. ${category.toUpperCase()}: ${categorizedCommands[category].length} commands`);
      });

      menuLines.push("");
      menuLines.push("─────────────────────────────────────");
      menuLines.push("Reply with number or category name");
      menuLines.push("Type 'all' to view all commands");
      menuLines.push("─────────────────────────────────────");

      const buffer = createCyberImage(menuLines, 'menu');
      const fileName = `menu_${Date.now()}.png`;
      const filePath = path.resolve(__dirname, fileName);
      fs.writeFileSync(filePath, buffer);

      setTimeout(() => cleanupFiles(), 30000);

      return api.sendMessage({ 
        body: "║ CYBER CORE SYSTEM ║ Command Menu Loaded", 
        attachment: fs.createReadStream(filePath) 
      }, event.threadID, (err, info) => {
        if (err) return console.error(err);
        global.client.handleReply.push({
          name: this.config.name,
          messageID: info.messageID,
          author: senderID,
          categorizedCommands: categorizedCommands
        });
      });

    } else {
      const input = args.join(" ").toLowerCase();

      if (input === 'all') {
        let allLines = [
          "═══════════════════════════════════════",
          "           ALL COMMANDS",
          "═══════════════════════════════════════",
          ""
        ];
        
        commandFiles.forEach((cmd, idx) => {
          allLines.push(`${idx + 1}. ${cmd.name.toUpperCase()}: ${cmd.config.description || 'No description available'}`);
        });

        allLines.push("");
        allLines.push("─────────────────────────────────────");
        allLines.push(`Total Commands: ${commandFiles.length}`);
        allLines.push("─────────────────────────────────────");

        const buffer = createCyberImage(allLines, 'category');
        const fileName = `allCommands_${Date.now()}.png`;
        const filePath = path.resolve(__dirname, fileName);
        fs.writeFileSync(filePath, buffer);

        setTimeout(() => cleanupFiles(), 30000);

        return api.sendMessage({ 
          body: "║ CYBER CORE ║ All Commands Database", 
          attachment: fs.createReadStream(filePath) 
        }, event.threadID, (err, info) => {
          if (err) return console.error(err);
          global.client.handleReply.push({
            name: this.config.name,
            messageID: info.messageID,
            author: senderID,
            commandsList: commandFiles
          });
        });
      }

      const command = commandFiles.find(cmd => cmd.name.toLowerCase() === input);

      if (command) {
        let detailLines = [
          "═══════════════════════════════════════",
          `        ${command.name.toUpperCase()} INFO`,
          "═══════════════════════════════════════",
          "",
          `Command Name: ${command.name}`,
          `Description: ${command.config.description || 'No description'}`,
          `Author: ${command.config.credits || 'Unknown'}`,
          `Version: ${command.config.version || 'Unknown'}`,
          `Usage: ${command.config.usages || 'No usage info'}`,
          `Cooldown: ${command.config.cooldowns || '0'} seconds`,
          `Permission: Level ${command.config.hasPermssion || 0}`,
          `Last Updated: ${command.lastUpdated ? command.lastUpdated.toLocaleString() : 'Unknown'}`,
          "",
          "─────────────────────────────────────"
        ];

        const buffer = createCyberImage(detailLines, 'command');
        const fileName = `${command.name}_${Date.now()}.png`;
        const filePath = path.resolve(__dirname, fileName);
        fs.writeFileSync(filePath, buffer);

        setTimeout(() => cleanupFiles(), 30000);

        return api.sendMessage({ 
          body: `║ CYBER CORE ║ Command: ${command.name}`, 
          attachment: fs.createReadStream(filePath) 
        }, event.threadID, event.messageID);
      }

      const categoryCommands = commandFiles.filter(cmd => 
        cmd.config.commandCategory && cmd.config.commandCategory.toLowerCase() === input
      );

      if (categoryCommands.length === 0) {
        return api.sendMessage("║ SYSTEM ERROR ║ Command or category not found in database", event.threadID, event.messageID);
      }

      let categoryLines = [
        "═══════════════════════════════════════",
        `      ${input.toUpperCase()} CATEGORY`,
        "═══════════════════════════════════════",
        ""
      ];

      categoryCommands.forEach((cmd, idx) => {
        categoryLines.push(`${idx + 1}. ${cmd.name.toUpperCase()}: ${cmd.config.description || 'No description'}`);
      });

      categoryLines.push("");
      categoryLines.push("─────────────────────────────────────");
      categoryLines.push(`Total in category: ${categoryCommands.length}`);
      categoryLines.push("─────────────────────────────────────");

      const buffer = createCyberImage(categoryLines, 'category');
      const fileName = `categoryCommands_${input}_${Date.now()}.png`;
      const filePath = path.resolve(__dirname, fileName);
      fs.writeFileSync(filePath, buffer);

      setTimeout(() => cleanupFiles(), 30000);

      return api.sendMessage({ 
        body: `║ CYBER CORE ║ Category: ${input.toUpperCase()}`, 
        attachment: fs.createReadStream(filePath) 
      }, event.threadID, event.messageID);
    }
  } catch (err) {
    console.error(err);
    return api.sendMessage("║ CRITICAL ERROR ║ System malfunction detected", event.threadID, event.messageID);
  }
};

module.exports.handleReply = async function({ api, event, handleReply }) {
  const { threadID, messageID, senderID, body } = event;

  if (handleReply.author !== senderID) return;

  const input = body.trim();
  const index = parseInt(input);

  let categoryName = input.toLowerCase();
  let categoryCommands = null;

  if (!isNaN(index)) {
    if (handleReply.commandsList && index > 0 && index <= handleReply.commandsList.length) {
      const command = handleReply.commandsList[index - 1];

      let detailLines = [
        "═══════════════════════════════════════",
        `        ${command.name.toUpperCase()} INFO`,
        "═══════════════════════════════════════",
        "",
        `Command Name: ${command.name}`,
        `Description: ${command.config.description || 'No description'}`,
        `Author: ${command.config.credits || 'Unknown'}`,
        `Version: ${command.config.version || 'Unknown'}`,
        `Usage: ${command.config.usages || 'No usage info'}`,
        `Cooldown: ${command.config.cooldowns || '0'} seconds`,
        `Permission: Level ${command.config.hasPermssion || 0}`,
        `Last Updated: ${command.lastUpdated ? command.lastUpdated.toLocaleString() : 'Unknown'}`,
        "",
        "─────────────────────────────────────"
      ];

      const buffer = createCyberImage(detailLines, 'command');
      const fileName = `${command.name}_${Date.now()}.png`;
      const filePath = path.resolve(__dirname, fileName);
      fs.writeFileSync(filePath, buffer);

      setTimeout(() => cleanupFiles(), 30000);

      return api.sendMessage({
        body: `║ CYBER CORE ║ Command: ${command.name}`,
        attachment: fs.createReadStream(filePath)
      }, threadID, messageID);
    } else if (index > 0 && index <= Object.keys(handleReply.categorizedCommands).length) {
      categoryName = Object.keys(handleReply.categorizedCommands)[index - 1].toLowerCase();
    }
  }

  for (const [key, value] of Object.entries(handleReply.categorizedCommands)) {
    if (key.toLowerCase() === categoryName) {
      categoryCommands = value;
      break;
    }
  }

  if (categoryCommands) {
    let categoryLines = [
      "═══════════════════════════════════════",
      `      ${categoryName.toUpperCase()} CATEGORY`,
      "═══════════════════════════════════════",
      ""
    ];

    categoryCommands.forEach((cmd, idx) => {
      categoryLines.push(`${idx + 1}. ${cmd.name.toUpperCase()}: ${cmd.config.description || 'No description'}`);
    });

    categoryLines.push("");
    categoryLines.push("─────────────────────────────────────");
    categoryLines.push(`Total in category: ${categoryCommands.length}`);
    categoryLines.push("─────────────────────────────────────");

    const buffer = createCyberImage(categoryLines, 'category');
    const fileName = `categoryCommands_${categoryName}_${Date.now()}.png`;
    const filePath = path.resolve(__dirname, fileName);
    fs.writeFileSync(filePath, buffer);

    setTimeout(() => cleanupFiles(), 30000);

    return api.sendMessage({
      body: `║ CYBER CORE ║ Category: ${categoryName.toUpperCase()}`,
      attachment: fs.createReadStream(filePath)
    }, threadID, messageID);
  }
};