import { z } from "zod";
import type { Experiment, InsightRow } 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: 1200px; margin: 0 auto; }
  h1 { font-size: 28px; margin-bottom: 24px; color: #fff; }
  .experiment-info { background: #16213e; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .experiment-info h2 { font-size: 20px; color: #e94560; margin-bottom: 12px; }
  .info-row { display: flex; gap: 12px; margin-bottom: 8px; font-size: 14px; }
  .info-label { color: #999; min-width: 120px; }
  .info-value { color: #fff; font-weight: 600; }
  .variants-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 20px; }
  .variant-card { background: #16213e; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); position: relative; }
  .variant-card.winner { border: 3px solid #27ae60; }
  .winner-badge { position: absolute; top: -12px; right: 20px; background: #27ae60; color: #fff; padding: 6px 16px; border-radius: 20px; font-weight: 700; font-size: 12px; text-transform: uppercase; box-shadow: 0 4px 8px rgba(39,174,96,0.4); }
  .variant-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
  .variant-header h3 { font-size: 18px; color: #e94560; }
  .variant-type { background: #0f3460; color: #fff; padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; text-transform: uppercase; }
  .metrics-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 16px; }
  .metric-item { background: #0f3460; border-radius: 8px; padding: 12px; }
  .metric-item h4 { font-size: 11px; color: #999; text-transform: uppercase; margin-bottom: 4px; }
  .metric-item .value { font-size: 20px; font-weight: 700; color: #fff; }
  .confidence-section { background: #0f3460; border-radius: 8px; padding: 16px; margin-top: 12px; }
  .confidence-bar { height: 24px; background: #1a1a2e; border-radius: 12px; overflow: hidden; margin: 12px 0; }
  .confidence-fill { height: 100%; background: linear-gradient(90deg, #e94560, #27ae60); display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; color: #fff; }
  .lift-badge { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: 20px; font-weight: 700; font-size: 14px; margin-top: 8px; }
  .lift-positive { background: #27ae60; color: #fff; }
  .lift-negative { background: #e74c3c; color: #fff; }
  .warning { background: #f39c12; color: #fff; padding: 12px 16px; border-radius: 8px; margin-bottom: 24px; font-weight: 600; font-size: 14px; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "ab_test_results",
    "A/B Test Results - Compare control vs treatment variants with statistical significance",
    {
      experiment_id: z.string().describe("Experiment/Study ID")
    },
    async (params: { experiment_id: string }) => {
      try {
        // Fetch experiment details
        const experiment = await client.get(
          `/${params.experiment_id}`,
          { fields: "id,name,description,type,status,start_time,end_time,control_ids,treatment_ids,winner_campaign_id,results" }
        ) as Experiment;

        // Fetch insights for all variants (control + treatments)
        const allCampaignIds = [...experiment.control_ids, ...experiment.treatment_ids];
        
        const variantData = await Promise.all(
          allCampaignIds.map(async (campaignId: string) => {
            try {
              const insights = await client.get(
                `/${campaignId}/insights`,
                {
                  level: "campaign",
                  fields: "spend,impressions,clicks,ctr,cpc,actions,action_values,purchase_roas"
                }
              ) as { data: InsightRow[] };
              
              const insight = insights.data[0] || {};
              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 cpa = conversionCount > 0 ? spend / conversionCount : 0;
              const roas = spend > 0 ? revenueValue / spend : 0;

              const isControl = experiment.control_ids.includes(campaignId);
              const isWinner = experiment.winner_campaign_id === campaignId;

              return {
                campaignId,
                isControl,
                isWinner,
                spend,
                impressions,
                clicks,
                ctr,
                cpc,
                conversions: conversionCount,
                cpa,
                roas
              };
            } catch (e) {
              console.error(`Error fetching insights for campaign ${campaignId}:`, e);
              return null;
            }
          })
        );

        const variants = variantData.filter(v => v !== null);

        // Find control variant
        const control = variants.find(v => v?.isControl);

        // Calculate lifts and confidence
        const variantsWithStats = variants.map((variant: any) => {
          if (!variant || !control || variant.isControl) return variant;

          // Calculate lift percentages
          const ctrLift = control.ctr > 0 ? ((variant.ctr - control.ctr) / control.ctr) * 100 : 0;
          const cpaLift = control.cpa > 0 ? ((control.cpa - variant.cpa) / control.cpa) * 100 : 0; // Inverse: lower is better
          const roasLift = control.roas > 0 ? ((variant.roas - control.roas) / control.roas) * 100 : 0;

          // Simple confidence calculation (placeholder - real implementation would use proper statistical tests)
          const sampleSize = variant.impressions;
          const confidence = Math.min(95, (sampleSize / 10000) * 100);

          return {
            ...variant,
            ctrLift,
            cpaLift,
            roasLift,
            confidence
          };
        });

        // Check if significant
        const hasSignificantResult = variantsWithStats.some((v: any) => v && !v.isControl && (v.confidence || 0) >= 95);

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>A/B Test Results</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>🧪 A/B Test Results</h1>
    
    <div class="experiment-info">
      <h2>${experiment.name || 'Experiment ' + experiment.id}</h2>
      ${experiment.description ? `<p style="color: #ddd; margin-bottom: 12px;">${experiment.description}</p>` : ''}
      <div class="info-row">
        <div class="info-label">Status:</div>
        <div class="info-value">${experiment.status}</div>
      </div>
      <div class="info-row">
        <div class="info-label">Start Time:</div>
        <div class="info-value">${new Date(experiment.start_time).toLocaleDateString()}</div>
      </div>
      ${experiment.end_time ? `
      <div class="info-row">
        <div class="info-label">End Time:</div>
        <div class="info-value">${new Date(experiment.end_time).toLocaleDateString()}</div>
      </div>
      ` : ''}
    </div>
    
    ${!hasSignificantResult ? `
    <div class="warning">
      ⚠️ Not Yet Significant - Confidence level below 95%. Continue test for more reliable results.
    </div>
    ` : ''}
    
    <div class="variants-grid">
      ${variantsWithStats.map((variant: any) => {
        if (!variant) return '';
        
        return `
        <div class="variant-card ${variant.isWinner ? 'winner' : ''}">
          ${variant.isWinner ? '<div class="winner-badge">🏆 Winner</div>' : ''}
          
          <div class="variant-header">
            <h3>${variant.isControl ? 'Control' : 'Treatment'}</h3>
            <div class="variant-type">${variant.isControl ? 'A' : 'B'}</div>
          </div>
          
          <div class="metrics-grid">
            <div class="metric-item">
              <h4>Spend</h4>
              <div class="value">$${variant.spend.toFixed(2)}</div>
            </div>
            <div class="metric-item">
              <h4>Impressions</h4>
              <div class="value">${variant.impressions.toLocaleString()}</div>
            </div>
            <div class="metric-item">
              <h4>CTR</h4>
              <div class="value">${variant.ctr.toFixed(2)}%</div>
            </div>
            <div class="metric-item">
              <h4>CPC</h4>
              <div class="value">$${variant.cpc.toFixed(2)}</div>
            </div>
            <div class="metric-item">
              <h4>Conversions</h4>
              <div class="value">${variant.conversions}</div>
            </div>
            <div class="metric-item">
              <h4>CPA</h4>
              <div class="value">${variant.cpa > 0 ? `$${variant.cpa.toFixed(2)}` : '-'}</div>
            </div>
            <div class="metric-item">
              <h4>ROAS</h4>
              <div class="value">${variant.roas > 0 ? `${variant.roas.toFixed(2)}x` : '-'}</div>
            </div>
          </div>
          
          ${!variant.isControl && variant.confidence ? `
          <div class="confidence-section">
            <h4 style="font-size: 12px; color: #999; text-transform: uppercase; margin-bottom: 8px;">Statistical Confidence</h4>
            <div class="confidence-bar">
              <div class="confidence-fill" style="width: ${variant.confidence}%;">
                ${variant.confidence.toFixed(1)}%
              </div>
            </div>
            
            ${variant.roasLift !== undefined ? `
            <div class="lift-badge ${variant.roasLift >= 0 ? 'lift-positive' : 'lift-negative'}">
              ${variant.roasLift >= 0 ? '↑' : '↓'} ${Math.abs(variant.roasLift).toFixed(1)}% ROAS Lift
            </div>
            ` : ''}
          </div>
          ` : ''}
        </div>
      `}).join('')}
    </div>
  </div>
</body>
</html>`;

        const textSummary = `A/B Test Results: ${experiment.name || experiment.id}\n\n` +
          `Status: ${experiment.status}\n` +
          `${hasSignificantResult ? 'Significant results found' : 'Not yet significant (< 95% confidence)'}\n` +
          `${experiment.winner_campaign_id ? `Winner: ${experiment.winner_campaign_id}` : 'No winner declared yet'}\n\n` +
          variants.map(v => v ? `${v.isControl ? 'Control' : 'Treatment'}: ${v.impressions.toLocaleString()} impressions, $${v.spend.toFixed(2)} spend, ${v.ctr.toFixed(2)}% CTR, ${v.roas.toFixed(2)}x ROAS` : '').join('\n');

        return {
          structuredContent: {
            type: "resource",
            resource: {
              uri: "meta-ads://app/ab-test-results",
              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 A/B Test Results</h2><p>${error.message}</p></div></div></body>
</html>`;
        
        return {
          structuredContent: {
            type: "resource",
            resource: { uri: "meta-ads://app/ab-test-results", mimeType: "text/html", text: errorHtml }
          },
          content: [{ type: "text", text: `Error: ${error.message}` }]
        };
      }
    },
    { title: "🧪 A/B Test Results", readOnlyHint: true }
  );
}
