import { z } from "zod";
import type { InsightRow, DatePreset } from "../types/meta-api.js";

const baseStyles = `
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #1a1a2e; color: #eee; padding: 20px; }
  .container { max-width: 900px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .funnel-container { background: #16213e; border-radius: 12px; padding: 40px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .funnel-stage { margin-bottom: 32px; position: relative; }
  .stage-bar { height: 80px; background: linear-gradient(90deg, #e94560, #ff6b9d); border-radius: 8px; position: relative; display: flex; align-items: center; padding: 0 24px; justify-content: space-between; box-shadow: 0 4px 8px rgba(233,69,96,0.3); }
  .stage-label { font-size: 16px; font-weight: 700; color: #fff; }
  .stage-value { font-size: 24px; font-weight: 700; color: #fff; }
  .stage-arrow { text-align: center; color: #e94560; font-size: 32px; margin: -8px 0; }
  .stage-metrics { display: flex; gap: 32px; margin-top: 12px; font-size: 13px; }
  .metric { color: #999; }
  .metric span { color: #e94560; font-weight: 600; margin-left: 4px; }
  .dropoff { color: #e74c3c; font-weight: 600; }
  .conversion-rate { color: #27ae60; font-weight: 600; }
  .cost-summary { background: #16213e; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .cost-summary h2 { font-size: 20px; color: #e94560; margin-bottom: 16px; }
  .cost-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; }
  .cost-card { background: #0f3460; border-radius: 8px; padding: 16px; text-align: center; }
  .cost-card h3 { font-size: 11px; color: #999; text-transform: uppercase; margin-bottom: 8px; }
  .cost-card .value { font-size: 20px; font-weight: 700; color: #fff; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "funnel_analyzer",
    "Funnel Analyzer - Visualize conversion funnel from impressions to purchases with drop-off rates",
    {
      account_id: z.string().describe("Ad Account ID (format: act_XXXXX)"),
      campaign_id: z.string().optional().describe("Filter by specific campaign ID (optional)"),
      date_preset: z.enum([
        "today", "yesterday", "last_3d", "last_7d", "last_14d", "last_28d", "last_30d"
      ]).optional().default("last_7d").describe("Date range preset")
    },
    async (params: { account_id: string; campaign_id?: string; date_preset?: DatePreset }) => {
      try {
        // Fetch insights
        const insightsPath = params.campaign_id 
          ? `/${params.campaign_id}/insights` 
          : `/${params.account_id}/insights`;
        
        const insightsResponse = await client.get(
          insightsPath,
          {
            level: params.campaign_id ? "campaign" : "account",
            date_preset: params.date_preset || "last_7d",
            fields: "impressions,clicks,spend,actions,outbound_clicks"
          }
        ) as { data: InsightRow[] };
        
        const insights = insightsResponse.data;

        // Aggregate data
        let totalImpressions = 0;
        let totalClicks = 0;
        let totalSpend = 0;
        let totalLandingPageViews = 0;
        let totalLeads = 0;
        let totalPurchases = 0;

        insights.forEach((insight: InsightRow) => {
          totalImpressions += parseInt(insight.impressions || "0");
          totalClicks += parseInt(insight.clicks || "0");
          totalSpend += parseFloat(insight.spend || "0");

          // Extract action counts
          const actions = insight.actions || [];
          actions.forEach((action: { action_type: string; value?: string }) => {
            const value = parseInt(action.value || "0");
            if (action.action_type === "landing_page_view" || action.action_type === "link_click") {
              totalLandingPageViews += value;
            }
            if (action.action_type === "lead" || action.action_type === "offsite_conversion.fb_pixel_lead" || action.action_type === "add_to_cart") {
              totalLeads += value;
            }
            if (action.action_type === "purchase" || action.action_type === "offsite_conversion.fb_pixel_purchase") {
              totalPurchases += value;
            }
          });
        });

        // Fallback: if no landing page views, use clicks
        if (totalLandingPageViews === 0) {
          totalLandingPageViews = totalClicks;
        }

        // Calculate funnel stages
        const stages = [
          { name: "Impressions", value: totalImpressions, width: 100 },
          { name: "Clicks", value: totalClicks, width: totalImpressions > 0 ? (totalClicks / totalImpressions) * 100 : 0 },
          { name: "Landing Page Views", value: totalLandingPageViews, width: totalImpressions > 0 ? (totalLandingPageViews / totalImpressions) * 100 : 0 },
          { name: "Leads / Add to Cart", value: totalLeads, width: totalImpressions > 0 ? (totalLeads / totalImpressions) * 100 : 0 },
          { name: "Purchases", value: totalPurchases, width: totalImpressions > 0 ? (totalPurchases / totalImpressions) * 100 : 0 }
        ];

        // Calculate conversion rates and drop-offs
        const conversionRates = stages.map((stage, i) => {
          if (i === 0) return 100;
          const prevValue = stages[i - 1].value;
          return prevValue > 0 ? (stage.value / prevValue) * 100 : 0;
        });

        const dropoffs = stages.map((stage, i) => {
          if (i === 0) return 0;
          const prevValue = stages[i - 1].value;
          const dropoff = prevValue - stage.value;
          return prevValue > 0 ? (dropoff / prevValue) * 100 : 0;
        });

        // Calculate costs per stage
        const cpm = totalImpressions > 0 ? (totalSpend / totalImpressions) * 1000 : 0;
        const cpc = totalClicks > 0 ? totalSpend / totalClicks : 0;
        const cplpv = totalLandingPageViews > 0 ? totalSpend / totalLandingPageViews : 0;
        const cpl = totalLeads > 0 ? totalSpend / totalLeads : 0;
        const cpa = totalPurchases > 0 ? totalSpend / totalPurchases : 0;

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Funnel Analyzer</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>🔄 Funnel Analyzer</h1>
    
    <div class="funnel-container">
      ${stages.map((stage, i) => `
        <div class="funnel-stage">
          <div class="stage-bar" style="width: ${Math.max(stage.width, 20)}%;">
            <div class="stage-label">${stage.name}</div>
            <div class="stage-value">${stage.value.toLocaleString()}</div>
          </div>
          <div class="stage-metrics">
            ${i > 0 ? `
              <div class="metric">Conversion Rate: <span class="conversion-rate">${conversionRates[i].toFixed(2)}%</span></div>
              <div class="metric">Drop-off: <span class="dropoff">${dropoffs[i].toFixed(2)}%</span></div>
            ` : ''}
          </div>
        </div>
        ${i < stages.length - 1 ? '<div class="stage-arrow">↓</div>' : ''}
      `).join('')}
    </div>
    
    <div class="cost-summary">
      <h2>💰 Cost Per Stage</h2>
      <div class="cost-grid">
        <div class="cost-card">
          <h3>CPM</h3>
          <div class="value">$${cpm.toFixed(2)}</div>
        </div>
        <div class="cost-card">
          <h3>CPC</h3>
          <div class="value">$${cpc.toFixed(2)}</div>
        </div>
        <div class="cost-card">
          <h3>Cost/LPV</h3>
          <div class="value">${cplpv > 0 ? `$${cplpv.toFixed(2)}` : '-'}</div>
        </div>
        <div class="cost-card">
          <h3>CPL</h3>
          <div class="value">${cpl > 0 ? `$${cpl.toFixed(2)}` : '-'}</div>
        </div>
        <div class="cost-card">
          <h3>CPA</h3>
          <div class="value">${cpa > 0 ? `$${cpa.toFixed(2)}` : '-'}</div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>`;

        const textSummary = `Funnel Analyzer (${params.date_preset || "last_7d"})\n\n` +
          stages.map((stage, i) => 
            `${stage.name}: ${stage.value.toLocaleString()}` + 
            (i > 0 ? ` (${conversionRates[i].toFixed(2)}% conversion, ${dropoffs[i].toFixed(2)}% drop-off)` : '')
          ).join('\n') + 
          `\n\nCosts: CPM $${cpm.toFixed(2)} | CPC $${cpc.toFixed(2)} | CPL $${cpl.toFixed(2)} | CPA $${cpa.toFixed(2)}`;

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/funnel-analyzer",
              mimeType: "text/html",
              text: html
            }
          },
          content: [{ type: "text", text: textSummary }]
        };
      } catch (error: any) {
        const errorHtml = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Error</title><style>${baseStyles}</style></head>
<body><div class="container"><div class="error"><h2>⚠️ Error Loading Funnel</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/funnel-analyzer", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    },
    { title: "🔄 Funnel Analyzer", readOnlyHint: true }
  );
}
