import { z } from "zod";
import type { Campaign, 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: 1400px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 32px; }
  .summary-card { background: #16213e; border-radius: 12px; padding: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .summary-card h3 { font-size: 13px; color: #999; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
  .summary-card .value { font-size: 28px; font-weight: 700; color: #e94560; }
  .summary-card .label { font-size: 11px; color: #777; margin-top: 4px; }
  table { width: 100%; border-collapse: collapse; background: #16213e; border-radius: 12px; overflow: hidden; }
  thead { background: #0f3460; }
  th { text-align: left; padding: 16px; font-weight: 600; color: #fff; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
  td { padding: 14px 16px; border-top: 1px solid #0f3460; color: #ddd; }
  tr:hover td { background: #1a2a4e; }
  .badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; text-transform: uppercase; }
  .badge-active { background: #27ae60; color: #fff; }
  .badge-paused { background: #f39c12; color: #fff; }
  .badge-error { background: #e74c3c; color: #fff; }
  .pacing-bar { width: 100%; height: 8px; background: #0f3460; border-radius: 4px; overflow: hidden; margin-top: 4px; }
  .pacing-fill { height: 100%; background: linear-gradient(90deg, #e94560, #ff6b9d); transition: width 0.3s; }
  .metric { font-weight: 600; 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(
    "campaign_dashboard",
    "Campaign Dashboard - Overview of all campaigns with key metrics and performance",
    {
      account_id: z.string().describe("Ad Account ID (format: act_XXXXX)"),
      date_preset: z.enum([
        "today", "yesterday", "last_3d", "last_7d", "last_14d", "last_28d", "last_30d",
        "last_90d", "this_month", "last_month"
      ]).optional().default("last_7d").describe("Date range preset")
    },
    async (params: { account_id: string; date_preset?: DatePreset }) => {
      try {
        // Fetch campaigns
        const campaignsResponse = await client.get(
          `/${params.account_id}/campaigns`,
          { fields: "id,name,status,objective,daily_budget,lifetime_budget,budget_remaining" }
        ) as { data: Campaign[] };
        const campaigns = campaignsResponse.data;

        // Fetch insights for all campaigns
        const insightsResponse = await client.get(
          `/${params.account_id}/insights`,
          {
            level: "campaign",
            date_preset: params.date_preset || "last_7d",
            fields: "campaign_id,campaign_name,spend,impressions,clicks,ctr,cpc,actions,action_values,purchase_roas"
          }
        ) as { data: InsightRow[] };
        const insights = insightsResponse.data;

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

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

        const campaignData = campaigns.map((campaign: Campaign) => {
          const insight = insightsMap.get(campaign.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;

          const budget = parseFloat(campaign.daily_budget || campaign.lifetime_budget || "0") / 100;
          const budgetPacing = budget > 0 ? (spend / budget) * 100 : 0;

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

          return {
            campaign,
            spend,
            impressions,
            clicks,
            ctr,
            cpc,
            conversions: conversionCount,
            cpa,
            roas,
            budget,
            budgetPacing: Math.min(budgetPacing, 100)
          };
        });

        // Sort by spend descending
        campaignData.sort((a: any, b: any) => b.spend - a.spend);

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

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Campaign Dashboard</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>📊 Campaign Dashboard</h1>
    
    <div class="summary-grid">
      <div class="summary-card">
        <h3>Total Spend</h3>
        <div class="value">$${totalSpend.toFixed(2)}</div>
        <div class="label">${params.date_preset || "last_7d"}</div>
      </div>
      <div class="summary-card">
        <h3>Total Impressions</h3>
        <div class="value">${totalImpressions.toLocaleString()}</div>
        <div class="label">${campaigns.length} campaigns</div>
      </div>
      <div class="summary-card">
        <h3>Avg CTR</h3>
        <div class="value">${avgCtr.toFixed(2)}%</div>
        <div class="label">${totalClicks.toLocaleString()} clicks</div>
      </div>
      <div class="summary-card">
        <h3>Avg CPC</h3>
        <div class="value">$${avgCpc.toFixed(2)}</div>
        <div class="label">per click</div>
      </div>
      <div class="summary-card">
        <h3>Total Conversions</h3>
        <div class="value">${totalConversions.toLocaleString()}</div>
        <div class="label">purchases/conversions</div>
      </div>
      <div class="summary-card">
        <h3>ROAS</h3>
        <div class="value">${overallRoas.toFixed(2)}x</div>
        <div class="label">$${totalRevenue.toFixed(2)} revenue</div>
      </div>
    </div>

    <table>
      <thead>
        <tr>
          <th>Campaign Name</th>
          <th>Status</th>
          <th>Objective</th>
          <th>Budget</th>
          <th>Spend</th>
          <th>Impressions</th>
          <th>CTR</th>
          <th>CPC</th>
          <th>CPA</th>
          <th>ROAS</th>
        </tr>
      </thead>
      <tbody>
        ${campaignData.map((row: any) => `
          <tr>
            <td><strong>${row.campaign.name}</strong></td>
            <td>
              <span class="badge badge-${row.campaign.status.toLowerCase() === 'active' ? 'active' : row.campaign.status.toLowerCase() === 'paused' ? 'paused' : 'error'}">
                ${row.campaign.status}
              </span>
            </td>
            <td>${row.campaign.objective.replace("OUTCOME_", "")}</td>
            <td>
              $${row.budget.toFixed(2)}
              <div class="pacing-bar">
                <div class="pacing-fill" style="width: ${row.budgetPacing}%"></div>
              </div>
            </td>
            <td class="metric">$${row.spend.toFixed(2)}</td>
            <td>${row.impressions.toLocaleString()}</td>
            <td>${row.ctr.toFixed(2)}%</td>
            <td>$${row.cpc.toFixed(2)}</td>
            <td>${row.conversions > 0 ? `$${row.cpa.toFixed(2)}` : "-"}</td>
            <td class="metric">${row.roas > 0 ? `${row.roas.toFixed(2)}x` : "-"}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
  </div>
</body>
</html>`;

        const textSummary = `Campaign Dashboard (${params.date_preset || "last_7d"})\n\n` +
          `Total Spend: $${totalSpend.toFixed(2)}\n` +
          `Total Impressions: ${totalImpressions.toLocaleString()}\n` +
          `Avg CTR: ${avgCtr.toFixed(2)}%\n` +
          `Avg CPC: $${avgCpc.toFixed(2)}\n` +
          `Total Conversions: ${totalConversions}\n` +
          `ROAS: ${overallRoas.toFixed(2)}x\n\n` +
          `${campaigns.length} campaigns tracked`;

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/campaign-dashboard",
              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 Dashboard</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/campaign-dashboard", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    },
    { title: "📊 Campaign Dashboard", readOnlyHint: true }
  );
}
