import { FastifyReply, FastifyRequest } from "fastify";
import {
  gravityFormsService,
  FilteredFormEntry,
} from "../../services/gravity-forms-service";
import { gfApiKey, gfApiSecret } from "../../utils/env";

// Interfaces pour les paramètres
interface FormQueryParams {
  limit?: number;
  page?: number;
  search?: string;
}

/**
 * HEALTH CHECK - Test de connexion API
 */
export async function getHealthCheck(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    console.log("🔍 Health check - Testing WordPress API connection...");

    const forms = await gravityFormsService.getAllForms();
    const formCount = Object.keys(forms).length;

    return reply.code(200).send({
      success: true,
      status: "healthy",
      message: "Connexion WordPress API fonctionnelle",
      details: {
        forms_count: formCount,
        forms_available: Object.keys(forms).map((id) => ({
          id,
          title: forms[id].title,
        })),
        timestamp: new Date().toISOString(),
      },
    });
  } catch (error: any) {
    console.error("❌ Health Check Failed:", error.message);
    return reply.code(503).send({
      success: false,
      status: "unhealthy",
      message: "Erreur de connexion à WordPress API",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * BUSINESS PLAN - Formulaire ID 7 - FORMAT ALIGNÉ SUR /services/business-plan
 */
export async function getBusinessPlan(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const params = req.query as FormQueryParams;
    const limit = params.limit || 50;

    console.log("🔄 Fetching Business Plan data (Gravity Forms)…");
    const entries: FilteredFormEntry[] =
      await gravityFormsService.getFormEntries("7");

    const legitEntries = entries.filter((entry) => entry.is_legit);

    const paginatedEntries = params.page
      ? legitEntries.slice((params.page - 1) * limit, params.page * limit)
      : legitEntries.slice(0, limit);

    console.log(
      `✅ Business Plan (WP): ${legitEntries.length}/${entries.length} entrées valides`
    );

    const rows = paginatedEntries.map((entry) => ({
      id: entry.id,
      firstName: entry.prenom || "",
      lastName: entry.nom || "",
      nationality: entry.nationalite || "",
      phoneNumber: entry.telephone || "",
      email: entry.email || "",
      projectIdea: entry.projet || "",
      location: entry.ville || "",
      educationAndExperience: entry.formation || "",
      financingPlan: entry.besoins || "",
      createdAt: entry.date_created,
    }));

    // Retourne un TABLEAU simple, comme /services/business-plan
    return reply.code(200).send(rows);
  } catch (error: any) {
    console.error("❌ Business Plan (WP) Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération des données Business Plan (WP)",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * ACCOMPAGNEMENT - Formulaire ID 6 - FORMAT ALIGNÉ
 */
export async function getAccompagnement(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const params = req.query as FormQueryParams;
    const limit = params.limit || 50;

    console.log("🔄 Fetching Accompagnement data (Gravity Forms)…");
    const entries: FilteredFormEntry[] =
      await gravityFormsService.getFormEntries("6");

    const legitEntries = entries.filter((entry) => entry.is_legit);

    const paginatedEntries = params.page
      ? legitEntries.slice((params.page - 1) * limit, params.page * limit)
      : legitEntries.slice(0, limit);

    console.log(
      `✅ Accompagnement (WP): ${legitEntries.length}/${entries.length} entrées valides`
    );

    const rows = paginatedEntries.map((entry) => ({
      id: entry.id,
      firstName: entry.prenom || "",
      lastName: entry.nom || "",
      nationality: entry.nationalite || "",
      phoneNumber: entry.telephone || "",
      email: entry.email || "",
      projectIdea: entry.projet || "",
      location: entry.ville || "",
      educationAndExperience: entry.formation || "",
      financingPlan: entry.besoins || "",
      createdAt: entry.date_created,
    }));

    return reply.code(200).send(rows);
  } catch (error: any) {
    console.error("❌ Accompagnement (WP) Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération des données Accompagnement (WP)",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * ÉTUDE DE MARCHÉ - Formulaire ID 8 - FORMAT ALIGNÉ
 */
export async function getMarketResearch(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const params = req.query as FormQueryParams;
    const limit = params.limit || 50;

    console.log("🔄 Fetching Market Research data (Gravity Forms)…");
    const entries: FilteredFormEntry[] =
      await gravityFormsService.getFormEntries("8");

    const legitEntries = entries.filter((entry) => entry.is_legit);

    const paginatedEntries = params.page
      ? legitEntries.slice((params.page - 1) * limit, params.page * limit)
      : legitEntries.slice(0, limit);

    console.log(
      `✅ Market Research (WP): ${legitEntries.length}/${entries.length} entrées valides`
    );

    const rows = paginatedEntries.map((entry) => ({
      id: entry.id,
      firstName: entry.prenom || "",
      lastName: entry.nom || "",
      nationality: entry.nationalite || "",
      phoneNumber: entry.telephone || "",
      email: entry.email || "",
      projectIdea: entry.projet || "",
      location: entry.ville || "",
      educationAndExperience: entry.formation || "",
      financingPlan: entry.besoins || "",
      createdAt: entry.date_created,
    }));

    return reply.code(200).send(rows);
  } catch (error: any) {
    console.error("❌ Market Research (WP) Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération des données Étude de marché (WP)",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * NETWORKING - Formulaire ID 9 - FORMAT ALIGNÉ
 */
export async function getNetworking(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const params = req.query as FormQueryParams;
    const limit = params.limit || 50;

    console.log("🔄 Fetching Networking data (Gravity Forms)…");
    const entries: FilteredFormEntry[] =
      await gravityFormsService.getFormEntries("9");

    const legitEntries = entries.filter((entry) => entry.is_legit);

    const paginatedEntries = params.page
      ? legitEntries.slice((params.page - 1) * limit, params.page * limit)
      : legitEntries.slice(0, limit);

    console.log(
      `✅ Networking (WP): ${legitEntries.length}/${entries.length} entrées valides`
    );

    const rows = paginatedEntries.map((entry) => ({
      id: entry.id,
      firstName: entry.prenom || "",
      lastName: entry.nom || "",
      nationality: entry.nationalite || "",
      phoneNumber: entry.telephone || "",
      email: entry.email || "",
      projectIdea: entry.projet || "",
      location: entry.ville || "",
      educationAndExperience: entry.formation || "",
      financingPlan: entry.besoins || "",
      createdAt: entry.date_created,
    }));

    return reply.code(200).send(rows);
  } catch (error: any) {
    console.error("❌ Networking (WP) Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération des données Networking (WP)",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * SOURCING - Formulaire ID 10 - FORMAT ALIGNÉ
 */
export async function getSourcing(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const params = req.query as FormQueryParams;
    const limit = params.limit || 50;

    console.log("🔄 Fetching Sourcing data (Gravity Forms)…");
    const entries: FilteredFormEntry[] =
      await gravityFormsService.getFormEntries("10");

    const legitEntries = entries.filter((entry) => entry.is_legit);

    const paginatedEntries = params.page
      ? legitEntries.slice((params.page - 1) * limit, params.page * limit)
      : legitEntries.slice(0, limit);

    console.log(
      `✅ Sourcing (WP): ${legitEntries.length}/${entries.length} entrées valides`
    );

    const rows = paginatedEntries.map((entry) => ({
      id: entry.id,
      firstName: entry.prenom || "",
      lastName: entry.nom || "",
      nationality: entry.nationalite || "",
      phoneNumber: entry.telephone || "",
      email: entry.email || "",
      projectIdea: entry.projet || "",
      location: entry.ville || "",
      educationAndExperience: entry.formation || "",
      financingPlan: entry.besoins || "",
      createdAt: entry.date_created,
    }));

    return reply.code(200).send(rows);
  } catch (error: any) {
    console.error("❌ Sourcing (WP) Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération des données Sourcing (WP)",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * PROSPECTING - Formulaire ID 11 - FORMAT ALIGNÉ
 */
export async function getProspecting(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const params = req.query as FormQueryParams;
    const limit = params.limit || 50;

    console.log("🔄 Fetching Prospecting data (Gravity Forms)…");
    const entries: FilteredFormEntry[] =
      await gravityFormsService.getFormEntries("11");

    const legitEntries = entries.filter((entry) => entry.is_legit);

    const paginatedEntries = params.page
      ? legitEntries.slice((params.page - 1) * limit, params.page * limit)
      : legitEntries.slice(0, limit);

    console.log(
      `✅ Prospecting (WP): ${legitEntries.length}/${entries.length} entrées valides`
    );

    const rows = paginatedEntries.map((entry) => ({
      id: entry.id,
      firstName: entry.prenom || "",
      lastName: entry.nom || "",
      nationality: entry.nationalite || "",
      phoneNumber: entry.telephone || "",
      email: entry.email || "",
      projectIdea: entry.projet || "",
      location: entry.ville || "",
      educationAndExperience: entry.formation || "",
      financingPlan: entry.besoins || "",
      createdAt: entry.date_created,
    }));

    return reply.code(200).send(rows);
  } catch (error: any) {
    console.error("❌ Prospecting (WP) Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération des données Prospection (WP)",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * TOUS LES FORMULAIRES - Liste simple
 */
export async function getAllForms(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    console.log("🔄 Fetching all forms...");
    const forms = await gravityFormsService.getAllForms();

    const formsList = Object.keys(forms).map((formId) => ({
      id: formId,
      title: forms[formId].title,
      entries_count: 0,
    }));

    console.log(`✅ All forms: ${formsList.length} formulaires trouvés`);

    return reply.code(200).send({
      success: true,
      metadata: {
        total_forms: formsList.length,
        generated_at: new Date().toISOString(),
      },
      forms: formsList,
    });
  } catch (error: any) {
    console.error("❌ All Forms Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération de la liste des formulaires",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * STATISTIQUES GLOBALES SIMPLIFIÉES
 */
export async function getFormStats(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    console.log("🔄 Fetching forms statistics...");

    const forms = await gravityFormsService.getAllForms();
    const formIds = Object.keys(forms);

    const entriesByForm = await Promise.all(
      formIds.map(async (id) => ({
        id,
        count: (await gravityFormsService.getFormEntries(id)).length,
      }))
    );

    return reply.code(200).send({
      success: true,
      forms: entriesByForm.map((f) => ({
        id: f.id,
        title: forms[f.id].title,
        entries_count: f.count,
      })),
    });
  } catch (error: any) {
    console.error("❌ Forms Stats Error:", error.message);
    return reply.code(500).send({
      success: false,
      message: "Erreur lors de la récupération des statistiques",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * TOUTES LES DONNÉES (SIMPLE AGRÉGATION)
 */
export async function getAllData(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    console.log("🔄 Fetching all forms data...");

    const forms = await gravityFormsService.getAllForms();
    const formIds = Object.keys(forms);

    const allEntriesByForm = await Promise.all(
      formIds.map(async (id) => ({
        id,
        title: forms[id].title,
        entries: await gravityFormsService.getFormEntries(id),
      }))
    );

    return reply.code(200).send({
      success: true,
      forms: allEntriesByForm,
    });
  } catch (error: any) {
    console.error("❌ All Data Error:", error.message);
    return reply.code(500).send({
      success: false,
      message:
        "Erreur lors de la récupération de toutes les données",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}

/**
 * RECHERCHE
 */
export async function searchEntries(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const query = req.query as { q: string; form_id?: string };

    if (!query.q) {
      return reply.code(400).send({
        success: false,
        message: "Le paramètre de recherche 'q' est requis",
      });
    }

    console.log(`🔍 Searching for: "${query.q}" in forms...`);

    const forms = await gravityFormsService.getAllForms();
    const formIds = query.form_id ? [query.form_id] : Object.keys(forms);

    const searchResults: any[] = [];
    const searchTerm = query.q.toLowerCase();

    for (const formId of formIds) {
      try {
        const entries = await gravityFormsService.getFormEntries(formId);
        const legitEntries = entries.filter((entry) => entry.is_legit);

        const matchingEntries = legitEntries.filter(
          (entry) =>
            (entry.nom &&
              entry.nom.toLowerCase().includes(searchTerm)) ||
            (entry.email &&
              entry.email.toLowerCase().includes(searchTerm)) ||
            (entry.telephone &&
              entry.telephone.includes(searchTerm)) ||
            (entry.projet &&
              entry.projet.toLowerCase().includes(searchTerm))
        );

        if (matchingEntries.length > 0) {
          searchResults.push({
            form_id: formId,
            form_title: forms[formId].title,
            matches: matchingEntries.length,
            entries: matchingEntries,
          });
        }
      } catch (error) {
        console.error(
          `❌ Recherche échouée pour le formulaire ${formId}:`,
          error
        );
      }
    }

    return reply.code(200).send({
      success: true,
      metadata: {
        search_term: query.q,
        total_results: searchResults.reduce(
          (sum, result) => sum + result.matches,
          0
        ),
        forms_searched: formIds.length,
        forms_with_results: searchResults.length,
      },
      results: searchResults,
    });
  } catch (error: any) {
    console.error("❌ Search Error:", error.message);
    return reply.code(500).send({
      success: false,
      message: "Erreur lors de la recherche",
      error: error.message,
    });
  }
}

/**
 * DIAGNOSTIC SIMPLE
 */
export async function getGFDiagnostic(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    console.log("🔍 Diagnostic détaillé Gravity Forms...");

    const forms = await gravityFormsService.getAllForms();

    return reply.code(200).send({
      success: true,
      diagnostic: {
        auth_method: gfApiKey && gfApiSecret ? "key_secret" : "basic_auth",
        connection_ok: true,
        forms_count: Object.keys(forms).length,
        environment: {
          has_gf_api_key: !!process.env.GF_API_KEY,
          has_gf_api_secret: !!process.env.GF_API_SECRET,
          gf_key_prefix:
            process.env.GF_API_KEY?.substring(0, 10) + "..." || "none",
          timestamp: new Date().toISOString(),
        },
      },
    });
  } catch (error: any) {
    console.error("❌ Diagnostic Error:", error.message);
    return reply.code(500).send({
      success: false,
      message: "Erreur lors du diagnostic",
      error: error.message,
      timestamp: new Date().toISOString(),
    });
  }
}
