import { z } from "zod";
import type { InsightRow, DatePreset, AdAccount } 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: 1000px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .chart-container { background: #16213e; border-radius: 12px; padding: 32px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .chart { position: relative; height: 300px; display: flex; align-items: flex-end; gap: 8px; margin-top: 24px; }
  .chart-bar { flex: 1; background: linear-gradient(180deg, #e94560, #ff6b9d); border-radius: 4px 4px 0 0; position: relative; min-height: 4px; }
  .chart-bar:hover { opacity: 0.8; }
  .chart-value { position: absolute; top: -24px; left: 50%; transform: translateX(-50%); font-size: 11px; color: #e94560; font-weight: 600; white-space: nowrap; }
  .chart-label { text-align: center; font-size: 10px; color: #999; margin-top: 8px; }
  .budget-line { position: absolute; top: 0; left: 0; right: 0; border-top: 2px dashed #27ae60; }
  .budget-label { position: absolute; right: 0; top: -20px; font-size: 11px; color: #27ae60; font-weight: 600; }
  .pacing-section { background: #16213e; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .pacing-bar-container { height: 40px; background: #0f3460; border-radius: 8px; overflow: hidden; position: relative; margin: 16px 0; }
  .pacing-bar-fill { height: 100%; background: linear-gradient(90deg, #e94560, #ff6b9d); display: flex; align-items: center; justify-content: flex-end; padding-right: 12px; font-weight: 700; font-size: 14px; color: #fff; }
  .pacing-indicator { display: inline-flex; align-items: center; gap: 8px; padding: 8px 16px; border-radius: 20px; font-weight: 600; font-size: 13px; margin-top: 12px; }
  .pacing-on-track { background: #27ae60; color: #fff; }
  .pacing-under { background: #f39c12; color: #fff; }
  .pacing-over { background: #e74c3c; color: #fff; }
  .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; }
  .stat-card { background: #0f3460; border-radius: 8px; padding: 20px; }
  .stat-card h3 { font-size: 12px; color: #999; text-transform: uppercase; margin-bottom: 8px; }
  .stat-card .value { font-size: 24px; font-weight: 700; color: #e94560; }
  .stat-card .sublabel { font-size: 11px; color: #777; margin-top: 4px; }
  .change-positive { color: #27ae60; }
  .change-negative { color: #e74c3c; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "spend_tracker",
    "Spend Tracker - Daily spend visualization with budget pacing and projections",
    {
      account_id: z.string().describe("Ad Account ID (format: act_XXXXX)"),
      date_preset: z.enum([
        "last_7d", "last_14d", "last_28d", "last_30d", "last_90d", "this_month"
      ]).optional().default("last_30d").describe("Date range preset")
    },
    async (params: { account_id: string; date_preset?: DatePreset }) => {
      try {
        // Fetch account info for budget
        const account = await client.get(
          `/${params.account_id}`,
          { fields: "id,name,spend_cap,amount_spent,currency" }
        ) as AdAccount;

        const totalBudget = parseFloat(account.spend_cap || "0") / 100;

        // Fetch daily insights
        const insightsResponse = await client.get(
          `/${params.account_id}/insights`,
          {
            level: "account",
            date_preset: params.date_preset || "last_30d",
            time_increment: "1",
            fields: "spend,date_start"
          }
        ) as { data: InsightRow[] };
        const dailyData = insightsResponse.data;

        // Sort by date
        dailyData.sort((a: InsightRow, b: InsightRow) => a.date_start.localeCompare(b.date_start));

        // Calculate totals
        const totalSpend = dailyData.reduce((sum: number, day: InsightRow) => sum + parseFloat(day.spend || "0"), 0);
        const avgDailySpend = dailyData.length > 0 ? totalSpend / dailyData.length : 0;
        
        // Day-over-day change (last day vs previous day)
        const dayOverDayChange = dailyData.length >= 2 
          ? ((parseFloat(dailyData[dailyData.length - 1].spend || "0") - parseFloat(dailyData[dailyData.length - 2].spend || "0")) / parseFloat(dailyData[dailyData.length - 2].spend || "1")) * 100
          : 0;

        // Projected spend (based on average daily spend)
        const daysInPeriod = dailyData.length;
        const projectedEndSpend = avgDailySpend * daysInPeriod;

        // Pacing
        const budgetPacing = totalBudget > 0 ? (totalSpend / totalBudget) * 100 : 0;
        const pacingStatus = budgetPacing > 110 ? "over" : budgetPacing < 90 ? "under" : "on-track";
        const pacingLabel = pacingStatus === "over" ? "Overspending" : pacingStatus === "under" ? "Underspending" : "On Track";

        // Find max spend for chart scaling
        const maxDailySpend = Math.max(...dailyData.map((d: InsightRow) => parseFloat(d.spend || "0")));
        const budgetLinePosition = totalBudget > 0 && avgDailySpend > 0 
          ? ((avgDailySpend / maxDailySpend) * 100) 
          : 0;

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Spend Tracker</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>💰 Spend Tracker</h1>
    
    <div class="chart-container">
      <h2 style="color: #fff; margin-bottom: 8px;">Daily Spend (${params.date_preset || "last_30d"})</h2>
      <div class="chart">
        ${budgetLinePosition > 0 ? `
        <div class="budget-line" style="top: ${100 - budgetLinePosition}%;">
          <div class="budget-label">Avg Daily: $${avgDailySpend.toFixed(2)}</div>
        </div>
        ` : ''}
        ${dailyData.map((day: InsightRow) => {
          const spend = parseFloat(day.spend || "0");
          const height = maxDailySpend > 0 ? (spend / maxDailySpend) * 100 : 0;
          const date = new Date(day.date_start);
          const label = `${date.getMonth() + 1}/${date.getDate()}`;
          return `
            <div style="flex: 1; display: flex; flex-direction: column; align-items: center;">
              <div class="chart-bar" style="height: ${height}%;">
                <div class="chart-value">$${spend.toFixed(0)}</div>
              </div>
              <div class="chart-label">${label}</div>
            </div>
          `;
        }).join('')}
      </div>
    </div>
    
    ${totalBudget > 0 ? `
    <div class="pacing-section">
      <h2 style="color: #fff; margin-bottom: 8px;">Budget Pacing</h2>
      <div class="pacing-bar-container">
        <div class="pacing-bar-fill" style="width: ${Math.min(budgetPacing, 100)}%;">
          ${budgetPacing.toFixed(1)}%
        </div>
      </div>
      <div style="display: flex; justify-content: space-between; font-size: 13px; color: #999;">
        <span>$${totalSpend.toFixed(2)} spent</span>
        <span>$${totalBudget.toFixed(2)} budget</span>
      </div>
      <div class="pacing-indicator pacing-${pacingStatus}">
        ${pacingStatus === "over" ? "⚠️" : pacingStatus === "under" ? "📉" : "✅"} ${pacingLabel}
      </div>
    </div>
    ` : ''}
    
    <div class="stats-grid">
      <div class="stat-card">
        <h3>Total Spend</h3>
        <div class="value">$${totalSpend.toFixed(2)}</div>
        <div class="sublabel">${params.date_preset || "last_30d"}</div>
      </div>
      <div class="stat-card">
        <h3>Avg Daily Spend</h3>
        <div class="value">$${avgDailySpend.toFixed(2)}</div>
        <div class="sublabel">per day</div>
      </div>
      <div class="stat-card">
        <h3>Projected Spend</h3>
        <div class="value">$${projectedEndSpend.toFixed(2)}</div>
        <div class="sublabel">end of period</div>
      </div>
      <div class="stat-card">
        <h3>Day-over-Day</h3>
        <div class="value ${dayOverDayChange >= 0 ? 'change-positive' : 'change-negative'}">
          ${dayOverDayChange >= 0 ? '+' : ''}${dayOverDayChange.toFixed(1)}%
        </div>
        <div class="sublabel">change</div>
      </div>
    </div>
  </div>
</body>
</html>`;

        const textSummary = `Spend Tracker (${params.date_preset || "last_30d"})\n\n` +
          `Total Spend: $${totalSpend.toFixed(2)}\n` +
          `Budget: $${totalBudget.toFixed(2)} (${budgetPacing.toFixed(1)}% utilized)\n` +
          `Pacing: ${pacingLabel}\n` +
          `Avg Daily: $${avgDailySpend.toFixed(2)}\n` +
          `Projected End: $${projectedEndSpend.toFixed(2)}\n` +
          `Day-over-Day: ${dayOverDayChange >= 0 ? '+' : ''}${dayOverDayChange.toFixed(1)}%`;

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