/* eslint-disable no-eval */
import { NextRequest, NextResponse } from "next/server";
const fs = eval('require("fs")') as typeof import("fs");
const path = eval('require("path")') as typeof import("path");

const BANNERS_FILE = "/var/www/html/bots/bot_hills/banners.json";
const BOTS_ROOT = "/var/www/html/bots/bot_hills";

interface BannerConfig {
  label: string;
  channel_id: string;
  bot: string;
  image_url: string;
  description: string;
}

type BannersData = Record<string, BannerConfig>;

function readBanners(): BannersData {
  const content = fs.readFileSync(BANNERS_FILE, "utf-8");
  return JSON.parse(content);
}

function writeBanners(data: BannersData): void {
  fs.writeFileSync(BANNERS_FILE, JSON.stringify(data, null, 2) + "\n", "utf-8");
}

function getBotToken(botName: string): string {
  const envPath = path.join(BOTS_ROOT, botName, ".env");
  const content = fs.readFileSync(envPath, "utf-8");
  for (const line of content.split("\n")) {
    const trimmed = line.trim();
    if (trimmed.startsWith("DISCORD_TOKEN=")) {
      let value = trimmed.substring("DISCORD_TOKEN=".length).trim();
      if (
        (value.startsWith('"') && value.endsWith('"')) ||
        (value.startsWith("'") && value.endsWith("'"))
      ) {
        value = value.slice(1, -1);
      }
      return value;
    }
  }
  throw new Error(`DISCORD_TOKEN não encontrado em ${envPath}`);
}

function buildPanelComponents(panel: string, imageUrl: string): object[] {
  const mediaGallery = (desc: string) => ({
    type: 12,
    items: [{ media: { url: imageUrl }, description: desc, spoiler: false }],
  });
  const divider = { type: 14, divider: true, spacing: 2 };
  const hasImage = imageUrl.trim().length > 0;

  switch (panel) {
    case "verificacao": {
      const components: object[] = [];
      if (hasImage) components.push(mediaGallery("Hills City Verificação"));
      components.push(
        { type: 10, content: "### ✅ Verificação de Segurança\nConfirme que você é um humano respondendo a um **`DESAFIO`** de segurança." },
        divider,
        { type: 10, content: "-# **Atenção!**\n> -# - Você tem **10 MINUTOS** para responder esse desafio corretamente;\n> -# - Preste atenção no desafio, se errar será kickado do servidor;\n> -# - Você não precisa em momento algum vincular sua conta para responder o desafio;" },
        divider,
        {
          type: 1, components: [
            { type: 2, custom_id: "verificar_btn", style: 1, label: "Responder", emoji: { name: "✅" } },
            { type: 2, custom_id: "verificar_info", style: 2, label: "Porque responder a esse desafio?", emoji: { name: "ℹ️" } },
          ],
        }
      );
      return [{ type: 17, accent_color: 2829617, components }];
    }

    case "allowlist": {
      const components: object[] = [];
      if (hasImage) components.push(mediaGallery("Hills City Allowlist"));
      components.push(
        { type: 10, content: "### 📝 Sistema de Allowlist\nPara dar continuidade e inscrição em nosso servidor responda as perguntas em nossa allowlist e aguarde a análise feita pela nossa equipe.\n\n-# ℹ️ Lembre-se de dar uma lida completa em nossas [REGRAS](https://discord.com/channels/1291244963279011932/1291245260067963031) antes de começar a responder nossas perguntas. Clique no **Criar Canal** para criar um canal para você poder responder nossas perguntas." },
        divider,
        {
          type: 1, components: [
            { type: 2, custom_id: "wl_analise_btn", style: 1, label: "Criar Canal", emoji: { name: "📝" } },
            { type: 2, style: 5, label: "Ler as Regras", emoji: { name: "📄" }, url: "https://discord.com/channels/1291244963279011932/1291245260067963031" },
          ],
        }
      );
      return [{ type: 17, accent_color: 2829617, components }];
    }

    case "tickets": {
      const components: object[] = [];
      if (hasImage) components.push(mediaGallery("Hills City Tickets"));
      components.push(
        { type: 10, content: "### 📄 Tickets - Hills City\n▸ **` ATENÇÃO! `**\nNão abra um TICKET sem ter algo relevante. Leia nossas <#1291245260067963031>, abrir apenas por abrir irá gerar punições.\n\nSelecione uma das **CATEGORIAS** abaixo para abrir um **TICKET**:" },
        divider,
        {
          type: 1, components: [{
            type: 3, custom_id: "ticket_open_select", placeholder: "Selecione uma categoria...", min_values: 1, max_values: 1, options: [
              { label: "Suporte", value: "1291245249171034193", description: "Ticket destinado para suporte.", emoji: { name: "📂" } },
              { label: "Bugs", value: "1291245251545010207", description: "Ticket destinado para reportar qualquer bug.", emoji: { name: "⛔" } },
              { label: "Alinhamento", value: "1291245250517536769", description: "Ticket destinado para alinhamento.", emoji: { name: "🔄" } },
              { label: "Vips e Doações", value: "1291245252534992896", description: "Ticket destinado a doações ao servidor.", emoji: { name: "💰" } },
            ],
          }],
        }
      );
      return [{ type: 17, accent_color: 2829617, components }];
    }

    case "liberacao": {
      const components: object[] = [];
      if (hasImage) components.push(mediaGallery("Hills City Liberação"));
      components.push(
        { type: 10, content: "### 🔓 Sistema de Liberação\nSe você precisa solicitar sua liberação no servidor, clique no botão abaixo e preencha o formulário." },
        divider,
        { type: 10, content: "-# ℹ️ Sua solicitação será analisada pela equipe de staff. Você receberá uma notificação por DM com o resultado." },
        divider,
        { type: 1, components: [{ type: 2, custom_id: "liberacao_request_btn", style: 1, label: "Solicitar Liberação", emoji: { name: "🔓" } }] }
      );
      return [{ type: 17, accent_color: 2829617, components }];
    }

    case "status": {
      const components: object[] = [];
      if (hasImage) components.push(mediaGallery("Hills City Status"));
      components.push(
        { type: 10, content: "### 🖥️ Status do Servidor\n▸ **Servidor:** Hills City\n▸ **Status:** 🟢 Online\n▸ **Jogadores:** 0/10" },
        divider,
        { type: 10, content: "### 🔌 Conectar ao Servidor\nCopie o comando abaixo e cole no **F8** do FiveM:\n\n```\nconnect 45.146.81.246\n```" },
        divider,
        { type: 10, content: "-# Atualiza a cada 60s" },
        {
          type: 1, components: [
            { type: 2, style: 5, label: "Conectar via CFX", emoji: { name: "🎮" }, url: "https://cfx.re/join/qvv9q6" },
            { type: 2, custom_id: "status_refresh", style: 2, label: "Atualizar Status", emoji: { name: "🔄" } },
          ],
        }
      );
      return [{ type: 17, accent_color: 2829617, components }];
    }

    default:
      throw new Error(`Painel desconhecido: ${panel}`);
  }
}

async function discordRequest(token: string, url: string, options: RequestInit = {}) {
  const res = await fetch(`https://discord.com/api/v10${url}`, {
    ...options,
    headers: {
      Authorization: `Bot ${token}`,
      "Content-Type": "application/json",
      ...options.headers,
    },
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Discord API erro ${res.status}: ${text}`);
  }
  if (res.status === 204) return null;
  return res.json();
}

async function applyPanel(panel: string, config: BannerConfig) {
  const token = getBotToken(config.bot);

  // Get bot user ID
  const me = await discordRequest(token, "/users/@me");
  const botUserId = me.id;

  // Fetch last 10 messages
  const messages = await discordRequest(token, `/channels/${config.channel_id}/messages?limit=10`);

  // Delete bot messages
  if (Array.isArray(messages)) {
    for (const msg of messages) {
      if (msg.author?.id === botUserId) {
        try {
          await discordRequest(token, `/channels/${config.channel_id}/messages/${msg.id}`, {
            method: "DELETE",
          });
          // Small delay to avoid rate limits
          await new Promise((r) => setTimeout(r, 500));
        } catch {
          // Ignore deletion errors
        }
      }
    }
  }

  // Build and send new panel
  const panelComponents = buildPanelComponents(panel, config.image_url);

  await discordRequest(token, `/channels/${config.channel_id}/messages`, {
    method: "POST",
    body: JSON.stringify({
      components: panelComponents,
      flags: 32768,
    }),
  });
}

export async function GET() {
  try {
    const banners = readBanners();
    return NextResponse.json({ success: true, banners });
  } catch (error) {
    return NextResponse.json(
      { success: false, error: `Erro ao ler banners: ${error instanceof Error ? error.message : String(error)}` },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { panel, action, image_url } = body;

    if (!panel || typeof panel !== "string") {
      return NextResponse.json(
        { success: false, error: "Campo 'panel' é obrigatório" },
        { status: 400 }
      );
    }

    const banners = readBanners();

    if (!banners[panel]) {
      return NextResponse.json(
        { success: false, error: `Painel '${panel}' não encontrado` },
        { status: 404 }
      );
    }

    if (action === "apply") {
      try {
        await applyPanel(panel, banners[panel]);
        return NextResponse.json({
          success: true,
          message: "Painel atualizado no Discord!",
        });
      } catch (error) {
        return NextResponse.json(
          { success: false, error: `Erro ao aplicar no Discord: ${error instanceof Error ? error.message : String(error)}` },
          { status: 500 }
        );
      }
    }

    // Save image_url
    if (typeof image_url !== "string") {
      return NextResponse.json(
        { success: false, error: "Campo 'image_url' deve ser uma string" },
        { status: 400 }
      );
    }

    // Validate URL if not empty
    if (image_url.trim() !== "") {
      try {
        new URL(image_url);
      } catch {
        return NextResponse.json(
          { success: false, error: "URL inválida. Forneça uma URL válida ou deixe em branco." },
          { status: 400 }
        );
      }
    }

    banners[panel].image_url = image_url.trim();
    writeBanners(banners);

    return NextResponse.json({
      success: true,
      message: "Banner salvo com sucesso!",
    });
  } catch (error) {
    return NextResponse.json(
      { success: false, error: `Erro: ${error instanceof Error ? error.message : String(error)}` },
      { status: 500 }
    );
  }
}
