import { z } from "zod";

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; }
  .progress-bar { background: #0f3460; height: 8px; border-radius: 4px; margin-bottom: 32px; overflow: hidden; }
  .progress-fill { height: 100%; background: linear-gradient(90deg, #e94560, #ff6b9d); transition: width 0.3s; }
  .step-indicator { display: flex; justify-content: space-between; margin-bottom: 40px; }
  .step { flex: 1; text-align: center; position: relative; }
  .step-number { width: 40px; height: 40px; border-radius: 50%; background: #0f3460; color: #999; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px; font-weight: 700; border: 2px solid #0f3460; }
  .step.active .step-number { background: #e94560; color: #fff; border-color: #e94560; }
  .step.completed .step-number { background: #27ae60; color: #fff; border-color: #27ae60; }
  .step-label { font-size: 12px; color: #999; }
  .step.active .step-label { color: #e94560; font-weight: 600; }
  .content-section { background: #16213e; border-radius: 12px; padding: 32px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .content-section h2 { font-size: 22px; color: #e94560; margin-bottom: 20px; }
  .objective-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; }
  .objective-card { background: #0f3460; border-radius: 12px; padding: 24px; text-align: center; cursor: pointer; transition: all 0.3s; border: 2px solid transparent; }
  .objective-card:hover { border-color: #e94560; transform: translateY(-4px); }
  .objective-card.selected { border-color: #e94560; background: #1a2a4e; }
  .objective-icon { font-size: 40px; margin-bottom: 12px; }
  .objective-title { font-size: 16px; font-weight: 700; color: #fff; margin-bottom: 8px; }
  .objective-desc { font-size: 12px; color: #999; line-height: 1.5; }
  .info-grid { display: grid; grid-template-columns: 200px 1fr; gap: 16px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid #0f3460; }
  .info-grid:last-child { border-bottom: none; }
  .info-label { color: #999; font-weight: 600; }
  .info-value { color: #fff; }
  .tag-list { display: flex; flex-wrap: wrap; gap: 8px; }
  .tag { background: #e94560; color: #fff; padding: 6px 14px; border-radius: 20px; font-size: 12px; }
  .form-group { margin-bottom: 20px; }
  .form-label { display: block; color: #999; font-weight: 600; margin-bottom: 8px; font-size: 14px; }
  .form-value { color: #fff; font-size: 16px; padding: 12px; background: #0f3460; border-radius: 8px; }
  .review-section { background: #0f3460; border-radius: 8px; padding: 20px; margin-bottom: 20px; }
  .review-section h3 { font-size: 16px; color: #e94560; margin-bottom: 12px; }
  .confirm-box { background: #27ae60; color: #fff; padding: 24px; border-radius: 12px; text-align: center; font-size: 18px; font-weight: 700; margin-top: 24px; }
  .navigation { display: flex; justify-content: space-between; margin-top: 24px; }
  .nav-hint { color: #999; font-size: 14px; font-style: italic; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any): void {
  server.tool(
    "campaign_builder",
    "Campaign Builder Wizard - Multi-step guided campaign creation interface",
    {
      account_id: z.string().describe("Ad Account ID (format: act_XXXXX)"),
      step: z.number().min(1).max(5).describe("Current wizard step (1-5)"),
      wizard_data: z.string().optional().describe("JSON string of accumulated wizard data from previous steps")
    },
    async (params: { account_id: string; step: number; wizard_data?: string }) => {
      try {
        // Parse wizard data
        const data = params.wizard_data ? JSON.parse(params.wizard_data) : {};

        const progressPercent = (params.step / 5) * 100;

        let stepContent = "";

        // Step 1: Objective Selection
        if (params.step === 1) {
          const objectives = [
            { id: "OUTCOME_AWARENESS", icon: "👁️", title: "Awareness", desc: "Show your ads to people most likely to remember them" },
            { id: "OUTCOME_TRAFFIC", icon: "🔗", title: "Traffic", desc: "Send people to a destination like your website" },
            { id: "OUTCOME_ENGAGEMENT", icon: "❤️", title: "Engagement", desc: "Get more messages, video views, or post engagement" },
            { id: "OUTCOME_LEADS", icon: "📝", title: "Leads", desc: "Collect leads for your business" },
            { id: "OUTCOME_APP_PROMOTION", icon: "📱", title: "App Promotion", desc: "Find new people to install your app" },
            { id: "OUTCOME_SALES", icon: "💰", title: "Sales", desc: "Find people likely to purchase your product" }
          ];

          stepContent = `
            <div class="content-section">
              <h2>Choose Your Campaign Objective</h2>
              <p style="color: #999; margin-bottom: 24px;">Select the goal that best represents what you want your campaign to achieve.</p>
              
              <div class="objective-grid">
                ${objectives.map(obj => `
                  <div class="objective-card ${data.objective === obj.id ? 'selected' : ''}">
                    <div class="objective-icon">${obj.icon}</div>
                    <div class="objective-title">${obj.title}</div>
                    <div class="objective-desc">${obj.desc}</div>
                  </div>
                `).join('')}
              </div>
            </div>
            
            <div class="navigation">
              <div class="nav-hint">Select an objective to continue to Step 2</div>
              <div class="nav-hint">→ Next: Audience Targeting</div>
            </div>
          `;
        }

        // Step 2: Audience Targeting
        else if (params.step === 2) {
          const targeting = data.targeting || {};
          stepContent = `
            <div class="content-section">
              <h2>Audience Targeting</h2>
              <p style="color: #999; margin-bottom: 24px;">Define who will see your ads.</p>
              
              <div class="info-grid">
                <div class="info-label">Locations</div>
                <div class="info-value">${targeting.countries?.join(', ') || 'United States'}</div>
              </div>
              
              <div class="info-grid">
                <div class="info-label">Age Range</div>
                <div class="info-value">${targeting.age_min || 18} - ${targeting.age_max || 65}+</div>
              </div>
              
              <div class="info-grid">
                <div class="info-label">Gender</div>
                <div class="info-value">${targeting.genders ? (targeting.genders.includes(1) && targeting.genders.includes(2) ? 'All' : targeting.genders.includes(1) ? 'Male' : 'Female') : 'All'}</div>
              </div>
              
              ${targeting.interests && targeting.interests.length > 0 ? `
              <div class="info-grid">
                <div class="info-label">Interests</div>
                <div class="info-value">
                  <div class="tag-list">
                    ${targeting.interests.map((i: any) => `<span class="tag">${i.name || i.id}</span>`).join('')}
                  </div>
                </div>
              </div>
              ` : ''}
              
              ${targeting.custom_audiences && targeting.custom_audiences.length > 0 ? `
              <div class="info-grid">
                <div class="info-label">Custom Audiences</div>
                <div class="info-value">
                  <div class="tag-list">
                    ${targeting.custom_audiences.map((ca: any) => `<span class="tag">${ca.name || ca.id}</span>`).join('')}
                  </div>
                </div>
              </div>
              ` : ''}
            </div>
            
            <div class="navigation">
              <div class="nav-hint">← Back: Objective</div>
              <div class="nav-hint">→ Next: Budget & Schedule</div>
            </div>
          `;
        }

        // Step 3: Budget & Schedule
        else if (params.step === 3) {
          const budget = data.budget || {};
          stepContent = `
            <div class="content-section">
              <h2>Budget & Schedule</h2>
              <p style="color: #999; margin-bottom: 24px;">Set your campaign budget and schedule.</p>
              
              <div class="form-group">
                <div class="form-label">Budget Type</div>
                <div class="form-value">${budget.type || 'Daily Budget'}</div>
              </div>
              
              <div class="form-group">
                <div class="form-label">Budget Amount</div>
                <div class="form-value">$${budget.amount || '50.00'} per day</div>
              </div>
              
              <div class="form-group">
                <div class="form-label">Start Date</div>
                <div class="form-value">${budget.start_date || new Date().toLocaleDateString()}</div>
              </div>
              
              <div class="form-group">
                <div class="form-label">End Date</div>
                <div class="form-value">${budget.end_date || 'Run continuously'}</div>
              </div>
              
              <div class="form-group">
                <div class="form-label">Bid Strategy</div>
                <div class="form-value">${budget.bid_strategy || 'Lowest Cost'}</div>
              </div>
            </div>
            
            <div class="navigation">
              <div class="nav-hint">← Back: Audience</div>
              <div class="nav-hint">→ Next: Creative</div>
            </div>
          `;
        }

        // Step 4: Creative
        else if (params.step === 4) {
          const creative = data.creative || {};
          stepContent = `
            <div class="content-section">
              <h2>Ad Creative</h2>
              <p style="color: #999; margin-bottom: 24px;">Your ad format and creative assets.</p>
              
              <div class="form-group">
                <div class="form-label">Ad Format</div>
                <div class="form-value">${creative.format || 'Single Image'}</div>
              </div>
              
              ${creative.headline ? `
              <div class="form-group">
                <div class="form-label">Headline</div>
                <div class="form-value">${creative.headline}</div>
              </div>
              ` : ''}
              
              ${creative.body ? `
              <div class="form-group">
                <div class="form-label">Ad Text</div>
                <div class="form-value">${creative.body}</div>
              </div>
              ` : ''}
              
              ${creative.cta ? `
              <div class="form-group">
                <div class="form-label">Call to Action</div>
                <div class="form-value">${creative.cta}</div>
              </div>
              ` : ''}
              
              <div class="form-group">
                <div class="form-label">Creative Preview</div>
                <div style="background: #0f3460; border-radius: 8px; padding: 40px; text-align: center; color: #777;">
                  📷 ${creative.format || 'Single Image'} Preview
                </div>
              </div>
            </div>
            
            <div class="navigation">
              <div class="nav-hint">← Back: Budget & Schedule</div>
              <div class="nav-hint">→ Next: Review & Confirm</div>
            </div>
          `;
        }

        // Step 5: Review & Confirm
        else if (params.step === 5) {
          const objective = data.objective || "OUTCOME_TRAFFIC";
          const targeting = data.targeting || {};
          const budget = data.budget || {};
          const creative = data.creative || {};

          stepContent = `
            <div class="content-section">
              <h2>Review Your Campaign</h2>
              <p style="color: #999; margin-bottom: 24px;">Review all settings before launching.</p>
              
              <div class="review-section">
                <h3>📊 Objective</h3>
                <div class="info-value">${objective.replace('OUTCOME_', '')}</div>
              </div>
              
              <div class="review-section">
                <h3>👥 Audience</h3>
                <div class="info-value">
                  ${targeting.countries?.join(', ') || 'United States'}<br>
                  Ages ${targeting.age_min || 18} - ${targeting.age_max || 65}+<br>
                  ${targeting.genders ? (targeting.genders.includes(1) && targeting.genders.includes(2) ? 'All Genders' : targeting.genders.includes(1) ? 'Male' : 'Female') : 'All Genders'}
                </div>
              </div>
              
              <div class="review-section">
                <h3>💰 Budget & Schedule</h3>
                <div class="info-value">
                  ${budget.type || 'Daily'}: $${budget.amount || '50.00'}<br>
                  Start: ${budget.start_date || 'Today'}<br>
                  ${budget.end_date ? `End: ${budget.end_date}` : 'Run continuously'}
                </div>
              </div>
              
              <div class="review-section">
                <h3>🎨 Creative</h3>
                <div class="info-value">
                  Format: ${creative.format || 'Single Image'}<br>
                  ${creative.headline ? `Headline: ${creative.headline}<br>` : ''}
                  ${creative.cta ? `CTA: ${creative.cta}` : ''}
                </div>
              </div>
              
              <div class="confirm-box">
                ✅ Ready to Launch Campaign
              </div>
            </div>
            
            <div class="navigation">
              <div class="nav-hint">← Back: Creative</div>
              <div class="nav-hint">Use API to create this campaign</div>
            </div>
          `;
        }

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Campaign Builder</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>🎯 Campaign Builder Wizard</h1>
    
    <div class="progress-bar">
      <div class="progress-fill" style="width: ${progressPercent}%;"></div>
    </div>
    
    <div class="step-indicator">
      ${[1, 2, 3, 4, 5].map(s => `
        <div class="step ${s < params.step ? 'completed' : s === params.step ? 'active' : ''}">
          <div class="step-number">${s < params.step ? '✓' : s}</div>
          <div class="step-label">
            ${s === 1 ? 'Objective' : s === 2 ? 'Audience' : s === 3 ? 'Budget' : s === 4 ? 'Creative' : 'Review'}
          </div>
        </div>
      `).join('')}
    </div>
    
    ${stepContent}
  </div>
</body>
</html>`;

        const textSummary = `Campaign Builder - Step ${params.step}/5\n\n` +
          (params.step === 1 ? "Select campaign objective" :
           params.step === 2 ? "Define audience targeting" :
           params.step === 3 ? "Set budget and schedule" :
           params.step === 4 ? "Configure ad creative" :
           "Review and confirm campaign");

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