import { z } from "zod";
import type { Ad, 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: 1600px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  table { width: 100%; border-collapse: collapse; background: #16213e; border-radius: 12px; overflow: hidden; font-size: 13px; }
  thead { background: #0f3460; position: sticky; top: 0; z-index: 10; }
  th { text-align: left; padding: 12px; font-weight: 600; color: #fff; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; }
  td { padding: 10px 12px; border-top: 1px solid #0f3460; color: #ddd; }
  tr:hover td { background: #1a2a4e; }
  .badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 10px; font-weight: 600; text-transform: uppercase; }
  .badge-active { background: #27ae60; color: #fff; }
  .badge-paused { background: #f39c12; color: #fff; }
  .badge-archived { background: #95a5a6; color: #fff; }
  .metric { font-weight: 600; color: #fff; }
  .cell-good { color: #27ae60; }
  .cell-bad { color: #e74c3c; }
  .summary-row { background: #0f3460; font-weight: 700; color: #e94560; }
  .summary-row td { border-top: 2px solid #e94560; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "ad_performance_grid",
    "Ad Performance Grid - Detailed performance metrics for all ads with color-coded insights",
    {
      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 ads
        const adsPath = params.campaign_id 
          ? `/${params.campaign_id}/ads` 
          : `/${params.account_id}/ads`;
        
        const adsResponse = await client.get(
          adsPath,
          { fields: "id,name,status,campaign_id,adset_id", limit: "500" }
        ) as { data: Ad[] };
        const ads = adsResponse.data;

        // Fetch insights for all ads
        const insightsResponse = await client.get(
          params.campaign_id ? `/${params.campaign_id}/insights` : `/${params.account_id}/insights`,
          {
            level: "ad",
            date_preset: params.date_preset || "last_7d",
            fields: "ad_id,ad_name,campaign_name,adset_name,spend,impressions,clicks,ctr,cpc,actions,action_values",
            limit: "500"
          }
        ) as { data: InsightRow[] };
        const insights = insightsResponse.data;

        // Build insights map
        const insightsMap = new Map<string, InsightRow>();
        insights.forEach((insight: InsightRow) => {
          if (insight.ad_id) {
            insightsMap.set(insight.ad_id, insight);
          }
        });

        // Calculate totals and averages
        let totalSpend = 0;
        let totalImpressions = 0;
        let totalClicks = 0;
        let totalConversions = 0;
        let totalRevenue = 0;

        const adData = ads.map((ad: Ad) => {
          const insight = insightsMap.get(ad.id);
          const spend = parseFloat(insight?.spend || "0");
          const impressions = parseInt(insight?.impressions || "0");
          const clicks = parseInt(insight?.clicks || "0");
          const ctr = parseFloat(insight?.ctr || "0");
          const cpc = parseFloat(insight?.cpc || "0");
          
          const conversions = insight?.actions?.find(a => 
            a.action_type === "purchase" || a.action_type === "offsite_conversion.fb_pixel_purchase"
          )?.value || "0";
          const conversionCount = parseInt(conversions);
          
          const revenue = insight?.action_values?.find(a => 
            a.action_type === "purchase" || a.action_type === "offsite_conversion.fb_pixel_purchase"
          )?.value || "0";
          const revenueValue = parseFloat(revenue);
          
          const roas = spend > 0 ? revenueValue / spend : 0;
          const cpa = conversionCount > 0 ? spend / conversionCount : 0;

          totalSpend += spend;
          totalImpressions += impressions;
          totalClicks += clicks;
          totalConversions += conversionCount;
          totalRevenue += revenueValue;

          return {
            ad,
            insight,
            spend,
            impressions,
            clicks,
            ctr,
            cpc,
            conversions: conversionCount,
            cpa,
            roas
          };
        });

        const avgCtr = totalClicks > 0 ? (totalClicks / totalImpressions) * 100 : 0;
        const avgCpc = totalClicks > 0 ? totalSpend / totalClicks : 0;
        const avgCpa = totalConversions > 0 ? totalSpend / totalConversions : 0;
        const avgRoas = totalSpend > 0 ? totalRevenue / totalSpend : 0;

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ad Performance Grid</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>🎯 Ad Performance Grid</h1>
    
    <table>
      <thead>
        <tr>
          <th>Ad Name</th>
          <th>Campaign</th>
          <th>Ad Set</th>
          <th>Status</th>
          <th>Impressions</th>
          <th>Clicks</th>
          <th>CTR</th>
          <th>Spend</th>
          <th>CPC</th>
          <th>Conv.</th>
          <th>CPA</th>
          <th>ROAS</th>
        </tr>
      </thead>
      <tbody>
        ${adData.map((row: any) => {
          const ctrClass = row.ctr > avgCtr ? 'cell-good' : row.ctr < avgCtr * 0.5 ? 'cell-bad' : '';
          const cpcClass = row.cpc < avgCpc && row.cpc > 0 ? 'cell-good' : row.cpc > avgCpc * 1.5 ? 'cell-bad' : '';
          const roasClass = row.roas > avgRoas && row.roas > 0 ? 'cell-good' : row.roas < avgRoas * 0.5 ? 'cell-bad' : '';
          
          return `
          <tr>
            <td><strong>${row.ad.name}</strong></td>
            <td>${row.insight?.campaign_name || '-'}</td>
            <td>${row.insight?.adset_name || '-'}</td>
            <td>
              <span class="badge badge-${row.ad.status.toLowerCase()}">
                ${row.ad.status}
              </span>
            </td>
            <td>${row.impressions.toLocaleString()}</td>
            <td>${row.clicks.toLocaleString()}</td>
            <td class="${ctrClass}">${row.ctr.toFixed(2)}%</td>
            <td class="metric">$${row.spend.toFixed(2)}</td>
            <td class="${cpcClass}">$${row.cpc.toFixed(2)}</td>
            <td>${row.conversions}</td>
            <td>${row.conversions > 0 ? `$${row.cpa.toFixed(2)}` : '-'}</td>
            <td class="metric ${roasClass}">${row.roas > 0 ? `${row.roas.toFixed(2)}x` : '-'}</td>
          </tr>
        `}).join('')}
        <tr class="summary-row">
          <td colspan="4">TOTALS / AVERAGES</td>
          <td>${totalImpressions.toLocaleString()}</td>
          <td>${totalClicks.toLocaleString()}</td>
          <td>${avgCtr.toFixed(2)}%</td>
          <td>$${totalSpend.toFixed(2)}</td>
          <td>$${avgCpc.toFixed(2)}</td>
          <td>${totalConversions}</td>
          <td>${totalConversions > 0 ? `$${avgCpa.toFixed(2)}` : '-'}</td>
          <td>${avgRoas > 0 ? `${avgRoas.toFixed(2)}x` : '-'}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>`;

        const textSummary = `Ad Performance Grid (${params.date_preset || "last_7d"})\n\n` +
          `${ads.length} ads analyzed\n` +
          `Total Spend: $${totalSpend.toFixed(2)}\n` +
          `Total Impressions: ${totalImpressions.toLocaleString()}\n` +
          `Total Clicks: ${totalClicks.toLocaleString()}\n` +
          `Avg CTR: ${avgCtr.toFixed(2)}%\n` +
          `Avg CPC: $${avgCpc.toFixed(2)}\n` +
          `Total Conversions: ${totalConversions}\n` +
          `Avg CPA: $${avgCpa.toFixed(2)}\n` +
          `Avg ROAS: ${avgRoas.toFixed(2)}x`;

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/ad-performance-grid",
              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 Ad Performance</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/ad-performance-grid", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    },
    { title: "🎯 Ad Performance Grid", readOnlyHint: true }
  );
}
