import React, { useState } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
import '../../styles/base.css';
import '../../styles/interactive.css';

function extractData(result: CallToolResult): any {
  const sc = (result as any).structuredContent;
  if (sc) return sc;
  for (const item of result.content || []) {
    if (item.type === 'text') { try { return JSON.parse(item.text); } catch {} }
  }
  return null;
}

export function App() {
  const [data, setData] = useState<any>((window as any).__MCP_APP_DATA__ || null);

  const { isConnected, error } = useApp({
    appInfo: { name: 'Audience Builder', version: '1.0.0' },
    capabilities: {},
    onAppCreated: (app) => {
      app.ontoolresult = async (result) => {
        const parsed = extractData(result);
        if (parsed) setData(parsed);
      };
    },
  });

  if (error) return <div className="error-state"><h3>Error</h3><p>{error.message}</p></div>;
  if (!isConnected) return <div className="loading-state"><div className="loading-spinner" /><p>Connecting...</p></div>;
  if (!data) return <div className="loading-state"><div className="loading-spinner" /><p>Waiting for data...</p></div>;

  const targeting = data?.targeting || data || {};
  const ageMin = targeting.age_min || targeting.ageMin || 18;
  const ageMax = targeting.age_max || targeting.ageMax || 65;
  const genders = targeting.genders || [1, 2];
  const hasMale = genders.includes(1);
  const hasFemale = genders.includes(2);
  const genderAll = hasMale && hasFemale;

  const countries: string[] = targeting.geo_locations?.countries || targeting.countries || [];
  const regions: any[] = targeting.geo_locations?.regions || targeting.regions || [];
  const cities: any[] = targeting.geo_locations?.cities || targeting.cities || [];
  const interests: any[] = targeting.interests || [];
  const behaviors: any[] = targeting.behaviors || [];
  const customAudiences: any[] = targeting.custom_audiences || targeting.customAudiences || [];

  const reach = data?.reach || {};
  const estimatedLower = reach.lower || reach.users_lower_bound || 0;
  const estimatedUpper = reach.upper || reach.users_upper_bound || 0;
  const estimatedMid = estimatedLower > 0 ? Math.round((estimatedLower + estimatedUpper) / 2) : 0;

  const ageRangeLeft = ((ageMin - 18) / (65 - 18)) * 100;
  const ageRangeWidth = ((ageMax - ageMin) / (65 - 18)) * 100;

  return (
    <PageHeader title="👥 Audience Builder" subtitle="Targeting visualization">
      {(countries.length > 0 || regions.length > 0 || cities.length > 0) && (
        <div className="card" style={{ marginTop: 8 }}>
          <div className="card-header"><div className="card-title">🌍 Locations</div></div>
          <div className="card-body p-md">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {countries.map((c, i) => <span key={i} className="tag">📍 {c}</span>)}
              {regions.map((r: any, i) => <span key={`r${i}`} className="tag">📍 {r.key || r.name || 'Region'}</span>)}
              {cities.map((c: any, i) => <span key={`c${i}`} className="tag">📍 {c.key || c.name || 'City'}</span>)}
            </div>
          </div>
        </div>
      )}

      <div className="card" style={{ marginTop: 8 }}>
        <div className="card-header"><div className="card-title">🎂 Age Range</div></div>
        <div className="card-body p-md">
          <div className="age-bar-wrap">
            <div className="age-highlight" style={{ left: `${ageRangeLeft}%`, width: `${ageRangeWidth}%` }} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#999', marginTop: 4 }}>
            <span>18</span><span>25</span><span>35</span><span>45</span><span>55</span><span>65+</span>
          </div>
          <div style={{ textAlign: 'center', marginTop: 10, color: '#e94560', fontWeight: 600, fontSize: 14 }}>
            Ages {ageMin} — {ageMax}
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 8 }}>
        <div className="card-header"><div className="card-title">⚧️ Gender</div></div>
        <div className="card-body p-md">
          <div className="gender-split">
            <div className="gender-card">
              <div style={{ fontSize: 12, color: '#e94560', marginBottom: 4, fontWeight: 600 }}>Male</div>
              <div className="gender-pct">{genderAll ? '50%' : hasMale ? '100%' : '0%'}</div>
            </div>
            <div className="gender-card">
              <div style={{ fontSize: 12, color: '#e94560', marginBottom: 4, fontWeight: 600 }}>Female</div>
              <div className="gender-pct">{genderAll ? '50%' : hasFemale ? '100%' : '0%'}</div>
            </div>
          </div>
        </div>
      </div>

      {interests.length > 0 && (
        <div className="card" style={{ marginTop: 8 }}>
          <div className="card-header"><div className="card-title">💡 Interests ({interests.length})</div></div>
          <div className="card-body p-md">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {interests.map((i: any, idx) => <span key={idx} className="tag">{i.name || i.id}</span>)}
            </div>
          </div>
        </div>
      )}

      {behaviors.length > 0 && (
        <div className="card" style={{ marginTop: 8 }}>
          <div className="card-header"><div className="card-title">🎯 Behaviors ({behaviors.length})</div></div>
          <div className="card-body p-md">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {behaviors.map((b: any, idx) => <span key={idx} className="tag">{b.name || b.id}</span>)}
            </div>
          </div>
        </div>
      )}

      {customAudiences.length > 0 && (
        <div className="card" style={{ marginTop: 8 }}>
          <div className="card-header"><div className="card-title">📋 Custom Audiences ({customAudiences.length})</div></div>
          <div className="card-body p-md">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {customAudiences.map((ca: any, idx) => <span key={idx} className="tag">{ca.name || ca.id}</span>)}
            </div>
          </div>
        </div>
      )}

      <div className="card" style={{ marginTop: 8, textAlign: 'center', padding: 20 }}>
        <div style={{ fontSize: 13, color: '#999', fontWeight: 600, textTransform: 'uppercase', marginBottom: 8 }}>📊 Estimated Reach</div>
        {estimatedMid > 0 ? (
          <>
            <div className="reach-value-lg">{estimatedMid.toLocaleString()}</div>
            <div className="reach-range">Range: {estimatedLower.toLocaleString()} — {estimatedUpper.toLocaleString()}</div>
          </>
        ) : (
          <div style={{ color: '#999', fontSize: 14 }}>Reach estimate unavailable</div>
        )}
      </div>
    </PageHeader>
  );
}
