import { z } from "zod";
import type { AdLibraryEntry } 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; }
  .search-info { background: #16213e; border-radius: 12px; padding: 20px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
  .search-info h2 { font-size: 18px; color: #e94560; margin-bottom: 8px; }
  .search-info p { color: #999; font-size: 14px; }
  .ads-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 20px; }
  .ad-card { background: #16213e; border-radius: 12px; padding: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; flex-direction: column; }
  .ad-header { margin-bottom: 12px; }
  .page-name { font-size: 16px; font-weight: 700; color: #e94560; margin-bottom: 4px; }
  .ad-status { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; text-transform: uppercase; }
  .status-active { background: #27ae60; color: #fff; }
  .status-inactive { background: #95a5a6; color: #fff; }
  .ad-body { background: #0f3460; border-radius: 8px; padding: 16px; margin-bottom: 12px; flex-grow: 1; }
  .ad-body p { color: #ddd; font-size: 14px; line-height: 1.6; }
  .platforms { display: flex; gap: 8px; margin-bottom: 12px; }
  .platform-badge { background: #e94560; color: #fff; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
  .ad-meta { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; font-size: 13px; }
  .meta-item { display: flex; flex-direction: column; }
  .meta-label { color: #999; font-size: 11px; text-transform: uppercase; margin-bottom: 4px; }
  .meta-value { color: #fff; font-weight: 600; }
  .dates { color: #777; font-size: 12px; margin-top: 12px; padding-top: 12px; border-top: 1px solid #0f3460; }
  .no-results { background: #16213e; padding: 60px 40px; border-radius: 12px; text-align: center; }
  .no-results h2 { color: #e94560; margin-bottom: 12px; }
  .no-results p { color: #999; }
  .error { background: #16213e; padding: 40px; border-radius: 12px; text-align: center; color: #e94560; }
`;

export function register(server: any, client: any): void {
  server.tool(
    "ad_library_browser",
    "Ad Library Browser - Search competitor ads from Facebook Ad Library",
    {
      search_terms: z.string().optional().describe("Search terms for ad creative/text"),
      page_id: z.string().optional().describe("Facebook Page ID to filter by"),
      country: z.string().optional().default("US").describe("Country code (e.g., US, GB, CA)")
    },
    async (params: { search_terms?: string; page_id?: string; country?: string }) => {
      try {
        if (!params.search_terms && !params.page_id) {
          throw new Error("Either search_terms or page_id must be provided");
        }

        // Build query params
        const queryParams: Record<string, string> = {
          ad_reached_countries: params.country || "US",
          ad_active_status: "ALL",
          fields: "id,ad_creation_time,ad_delivery_start_time,ad_delivery_stop_time,ad_creative_bodies,ad_creative_link_titles,page_id,page_name,publisher_platforms,estimated_audience_size,spend,impressions"
        };

        if (params.search_terms) {
          queryParams.search_terms = params.search_terms;
        }
        if (params.page_id) {
          queryParams.search_page_ids = params.page_id;
        }

        // Fetch from Ad Library API
        const adsResponse = await client.get(
          "/ads_archive",
          queryParams
        ) as { data: AdLibraryEntry[] };
        
        const ads = adsResponse.data || [];

        // Build HTML
        const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ad Library Browser</title>
  <style>${baseStyles}</style>
</head>
<body>
  <div class="container">
    <h1>📚 Ad Library Browser</h1>
    
    <div class="search-info">
      <h2>Search Criteria</h2>
      <p>
        ${params.search_terms ? `Search Terms: <strong>${params.search_terms}</strong><br>` : ''}
        ${params.page_id ? `Page ID: <strong>${params.page_id}</strong><br>` : ''}
        Country: <strong>${params.country || 'US'}</strong>
      </p>
      <p style="margin-top: 8px; color: #e94560; font-weight: 600;">${ads.length} ads found</p>
    </div>
    
    ${ads.length === 0 ? `
    <div class="no-results">
      <h2>No Ads Found</h2>
      <p>Try adjusting your search criteria or check a different country.</p>
    </div>
    ` : `
    <div class="ads-grid">
      ${ads.map((ad: AdLibraryEntry) => {
        const isActive = !ad.ad_delivery_stop_time;
        const creativeBody = ad.ad_creative_bodies?.[0] || "No ad text available";
        const linkTitle = ad.ad_creative_link_titles?.[0] || "";
        const platforms = ad.publisher_platforms || [];
        
        const spendRange = ad.spend 
          ? `$${ad.spend.lower_bound.toLocaleString()} - $${ad.spend.upper_bound.toLocaleString()} ${ad.spend.currency || 'USD'}`
          : null;
        
        const impressionRange = ad.impressions
          ? `${ad.impressions.lower_bound.toLocaleString()} - ${ad.impressions.upper_bound.toLocaleString()}`
          : null;
        
        const audienceSize = ad.estimated_audience_size
          ? `${ad.estimated_audience_size.lower_bound.toLocaleString()} - ${ad.estimated_audience_size.upper_bound.toLocaleString()}`
          : null;

        const startDate = new Date(ad.ad_delivery_start_time).toLocaleDateString();
        const endDate = ad.ad_delivery_stop_time ? new Date(ad.ad_delivery_stop_time).toLocaleDateString() : "Active";

        return `
        <div class="ad-card">
          <div class="ad-header">
            <div class="page-name">${ad.page_name}</div>
            <span class="ad-status status-${isActive ? 'active' : 'inactive'}">
              ${isActive ? '✓ Active' : '⊗ Inactive'}
            </span>
          </div>
          
          ${linkTitle ? `<div style="font-weight: 600; color: #fff; margin-bottom: 8px;">${linkTitle}</div>` : ''}
          
          <div class="ad-body">
            <p>${creativeBody.substring(0, 200)}${creativeBody.length > 200 ? '...' : ''}</p>
          </div>
          
          ${platforms.length > 0 ? `
          <div class="platforms">
            ${platforms.map((p: string) => `<span class="platform-badge">${p === 'facebook' ? 'FB' : p === 'instagram' ? 'IG' : p.toUpperCase()}</span>`).join('')}
          </div>
          ` : ''}
          
          <div class="ad-meta">
            ${spendRange ? `
            <div class="meta-item">
              <div class="meta-label">Est. Spend</div>
              <div class="meta-value">${spendRange}</div>
            </div>
            ` : ''}
            ${impressionRange ? `
            <div class="meta-item">
              <div class="meta-label">Est. Impressions</div>
              <div class="meta-value">${impressionRange}</div>
            </div>
            ` : ''}
            ${audienceSize ? `
            <div class="meta-item">
              <div class="meta-label">Est. Audience</div>
              <div class="meta-value">${audienceSize}</div>
            </div>
            ` : ''}
          </div>
          
          <div class="dates">
            Started: ${startDate} • ${isActive ? 'Currently Active' : `Ended: ${endDate}`}
          </div>
        </div>
      `}).join('')}
    </div>
    `}
  </div>
</body>
</html>`;

        const textSummary = `Ad Library Browser Results\n\n` +
          `${params.search_terms ? `Search: ${params.search_terms}\n` : ''}` +
          `${params.page_id ? `Page: ${params.page_id}\n` : ''}` +
          `Country: ${params.country || 'US'}\n` +
          `Found: ${ads.length} ads\n\n` +
          ads.slice(0, 5).map((ad: AdLibraryEntry) => 
            `${ad.page_name} (${ad.ad_delivery_stop_time ? 'Inactive' : 'Active'})\n` +
            `  ${(ad.ad_creative_bodies?.[0] || '').substring(0, 100)}...`
          ).join('\n\n');

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