import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../../auth/AuthProvider';
import {
  getCampaignHealth, getBudgetPacing, getPostCampaignReport,
  getRecommendations, getInitiativeRecommendations,
  dismissRecommendation, resolveRecommendation
} from '../../services/intelligenceApi';

/* ─── Formatters ─── */
const fmtNum = (n) => n != null ? Number(n).toLocaleString() : '—';
const fmtCur = (n) => n != null ? '$' + Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '$0.00';
const fmtPct = (n) => n != null ? Number(n).toFixed(1) + '%' : '—';
const fmtDate = (d) => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '—';
const fmtDateFull = (d) => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '—';
const timeAgo = (d) => {
  if (!d) return '';
  const diff = Math.floor((Date.now() - new Date(d).getTime()) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  return `${Math.floor(diff / 86400)}d ago`;
};

const channelLabel = (ch) => ({
  google_ads: 'Google Ads', google: 'Google Ads', meta: 'Meta', tiktok: 'TikTok'
})[(ch || '').toLowerCase()] || ch;

const severityConfig = {
  critical: { label: 'Critical', css: 'sev-critical', icon: '⚠' },
  warning:  { label: 'Warning',  css: 'sev-warning',  icon: '⚡' },
  info:     { label: 'Info',     css: 'sev-info',     icon: 'ℹ' },
};

const healthColors = {
  green:  { label: 'Healthy', css: 'health-green',  dot: '🟢' },
  yellow: { label: 'Needs Attention', css: 'health-yellow', dot: '🟡' },
  red:    { label: 'Action Required', css: 'health-red',    dot: '🔴' },
};

const TABS = [
  { id: 'health', label: 'Health Overview', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
  { id: 'recommendations', label: 'Recommendations', icon: 'M13 10V3L4 14h7v7l9-11h-7z' },
  { id: 'pacing', label: 'Budget Pacing', icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z' },
];

/* ═══════════════════════════════════════════════════
   Main Intelligence View
   ═══════════════════════════════════════════════════ */
export default function Intelligence({ onNavigate }) {
  const { sessionToken } = useAuth();
  const [activeTab, setActiveTab] = useState('health');
  const [health, setHealth] = useState(null);
  const [recommendations, setRecommendations] = useState(null);
  const [recCounts, setRecCounts] = useState({ critical: 0, warning: 0, info: 0 });
  const [loading, setLoading] = useState(true);
  const [selectedInitiative, setSelectedInitiative] = useState(null);
  const [pacing, setPacing] = useState(null);
  const [report, setReport] = useState(null);
  const [pacingLoading, setPacingLoading] = useState(false);

  const loadHealth = useCallback(async () => {
    if (!sessionToken) return;
    setLoading(true);
    const res = await getCampaignHealth(sessionToken);
    if (res.ok && res.data) {
      setHealth(res.data.initiatives || []);
    }
    setLoading(false);
  }, [sessionToken]);

  const loadRecommendations = useCallback(async () => {
    if (!sessionToken) return;
    const res = await getRecommendations(sessionToken);
    if (res.ok && res.data) {
      setRecommendations(res.data.recommendations || []);
      setRecCounts({
        critical: res.data.criticalCount || 0,
        warning: res.data.warningCount || 0,
        info: res.data.infoCount || 0,
      });
    }
  }, [sessionToken]);

  useEffect(() => {
    loadHealth();
    loadRecommendations();
  }, [loadHealth, loadRecommendations]);

  const loadPacing = useCallback(async (initiativeId) => {
    if (!sessionToken) return;
    setPacingLoading(true);
    setPacing(null);
    setReport(null);
    const [pacingRes, reportRes] = await Promise.all([
      getBudgetPacing(initiativeId, sessionToken),
      getPostCampaignReport(initiativeId, sessionToken)
    ]);
    if (pacingRes.ok && pacingRes.data) setPacing(pacingRes.data);
    if (reportRes.ok && reportRes.data) setReport(reportRes.data);
    setPacingLoading(false);
  }, [sessionToken]);

  const handleDismiss = async (recId) => {
    const res = await dismissRecommendation(recId, sessionToken);
    if (res.ok) {
      loadRecommendations();
      loadHealth();
    }
  };

  const handleResolve = async (recId) => {
    const res = await resolveRecommendation(recId, sessionToken);
    if (res.ok) {
      loadRecommendations();
      loadHealth();
    }
  };

  const selectInitiative = (init) => {
    const id = init.initiativeId || init.iniId;
    setSelectedInitiative(init);
    loadPacing(id);
  };

  const totalAlerts = recCounts.critical + recCounts.warning + recCounts.info;

  return (
    <div className="intelligence-view">
      <div className="view-header">
        <div>
          <h1>Campaign Intelligence</h1>
          <p className="view-subtitle">Real-time health monitoring, recommendations, and budget pacing</p>
        </div>
        {totalAlerts > 0 && (
          <div className="intel-alert-summary">
            {recCounts.critical > 0 && (
              <span className="intel-alert-badge sev-critical">{recCounts.critical} Critical</span>
            )}
            {recCounts.warning > 0 && (
              <span className="intel-alert-badge sev-warning">{recCounts.warning} Warning</span>
            )}
            {recCounts.info > 0 && (
              <span className="intel-alert-badge sev-info">{recCounts.info} Info</span>
            )}
          </div>
        )}
      </div>

      {/* Tabs */}
      <div className="intel-tabs">
        {TABS.map(tab => (
          <button
            key={tab.id}
            className={`intel-tab ${activeTab === tab.id ? 'active' : ''}`}
            onClick={() => setActiveTab(tab.id)}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d={tab.icon} />
            </svg>
            {tab.label}
            {tab.id === 'recommendations' && totalAlerts > 0 && (
              <span className="tab-badge">{totalAlerts}</span>
            )}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div className="intel-content">
        {activeTab === 'health' && (
          <HealthOverview
            health={health}
            loading={loading}
            onSelectInitiative={selectInitiative}
            onRefresh={loadHealth}
          />
        )}
        {activeTab === 'recommendations' && (
          <RecommendationsPanel
            recommendations={recommendations}
            loading={loading}
            onDismiss={handleDismiss}
            onResolve={handleResolve}
          />
        )}
        {activeTab === 'pacing' && (
          <PacingView
            health={health}
            selectedInitiative={selectedInitiative}
            pacing={pacing}
            report={report}
            loading={pacingLoading}
            onSelectInitiative={selectInitiative}
          />
        )}
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   Health Overview Tab
   ═══════════════════════════════════════════════════ */
function HealthOverview({ health, loading, onSelectInitiative, onRefresh }) {
  if (loading) {
    return (
      <div className="loading-placeholder padded">
        {[1,2,3].map(i => <div key={i} className="skeleton skeleton-row" style={{height:'80px', marginBottom:'12px'}} />)}
      </div>
    );
  }

  if (!health || health.length === 0) {
    return (
      <div className="empty-state">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        <h3>No active campaigns</h3>
        <p>Campaign health data will appear here once you have active campaigns running.</p>
      </div>
    );
  }

  return (
    <div>
      <div className="intel-section-header">
        <h3>Active Campaigns</h3>
        <button className="btn btn-sm btn-outline" onClick={onRefresh}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 4v6h6M23 20v-6h-6"/><path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/></svg>
          Refresh
        </button>
      </div>

      <div className="health-grid">
        {health.map((init, i) => {
          const channels = init.channels ? (typeof init.channels === 'string' ? JSON.parse(init.channels) : init.channels) : [];
          const worstHealth = channels.reduce((worst, ch) => {
            const h = ch.healthStatus || 'green';
            if (h === 'red') return 'red';
            if (h === 'yellow' && worst !== 'red') return 'yellow';
            return worst;
          }, 'green');
          const hc = healthColors[worstHealth] || healthColors.green;

          return (
            <div key={i} className={`health-card ${hc.css}`} onClick={() => onSelectInitiative(init)}>
              <div className="health-card-header">
                <div className="health-card-title">
                  <span className="health-dot">{hc.dot}</span>
                  <span>{init.name || 'Untitled'}</span>
                </div>
                <span className={`health-status-label ${hc.css}`}>{hc.label}</span>
              </div>

              <div className="health-card-meta">
                <span>{init.objective || 'Campaign'}</span>
                <span>•</span>
                <span>{fmtCur(init.totalBudget)}</span>
                <span>•</span>
                <span>{fmtDateFull(init.startDate)} – {fmtDateFull(init.endDate)}</span>
              </div>

              {channels.length > 0 && (
                <div className="health-channels">
                  {channels.map((ch, j) => {
                    const chHealth = healthColors[ch.healthStatus || 'green'] || healthColors.green;
                    return (
                      <div key={j} className={`health-channel-row ${chHealth.css}`}>
                        <div className="health-channel-info">
                          <span className="health-channel-dot">{chHealth.dot}</span>
                          <span className="health-channel-name">{channelLabel(ch.channelType)}</span>
                        </div>
                        <div className="health-channel-stats">
                          <span title="Impressions (7d)">{fmtNum(ch.impressions7d)} imp</span>
                          <span title="Clicks (7d)">{fmtNum(ch.clicks7d)} clicks</span>
                          <span title="CTR (7d)">{fmtPct(ch.ctr7d)} CTR</span>
                          <span title="Spend (7d)">{fmtCur(ch.spend7d)}</span>
                        </div>
                        <div className="health-channel-alerts">
                          {ch.criticalAlerts > 0 && <span className="alert-count sev-critical">{ch.criticalAlerts}</span>}
                          {ch.warningAlerts > 0 && <span className="alert-count sev-warning">{ch.warningAlerts}</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   Recommendations Panel
   ═══════════════════════════════════════════════════ */
function RecommendationsPanel({ recommendations, loading, onDismiss, onResolve }) {
  const [filter, setFilter] = useState('all');

  if (loading) {
    return (
      <div className="loading-placeholder padded">
        {[1,2,3].map(i => <div key={i} className="skeleton skeleton-row" style={{height:'72px', marginBottom:'12px'}} />)}
      </div>
    );
  }

  const filtered = filter === 'all' ? recommendations :
    recommendations?.filter(r => r.severity === filter) || [];

  return (
    <div>
      <div className="intel-section-header">
        <h3>Active Recommendations</h3>
        <div className="rec-filters">
          {[
            { key: 'all', label: 'All' },
            { key: 'critical', label: 'Critical' },
            { key: 'warning', label: 'Warning' },
            { key: 'info', label: 'Info' },
          ].map(f => (
            <button
              key={f.key}
              className={`btn btn-sm ${filter === f.key ? 'btn-primary' : 'btn-outline'}`}
              onClick={() => setFilter(f.key)}
            >
              {f.label}
            </button>
          ))}
        </div>
      </div>

      {!filtered || filtered.length === 0 ? (
        <div className="empty-state">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
          <h3>{filter === 'all' ? 'All clear!' : `No ${filter} recommendations`}</h3>
          <p>Your campaigns are performing within expected parameters.</p>
        </div>
      ) : (
        <div className="rec-list">
          {filtered.map((rec, i) => {
            const sev = severityConfig[rec.severity] || severityConfig.info;
            return (
              <div key={rec.recommendationId || i} className={`rec-card ${sev.css}`}>
                <div className="rec-card-header">
                  <span className={`rec-severity ${sev.css}`}>{sev.icon} {sev.label}</span>
                  <span className="rec-category">{rec.category}</span>
                  <span className="rec-channel">{channelLabel(rec.channelType)}</span>
                  <span className="rec-time">{timeAgo(rec.createdAt)}</span>
                </div>
                <div className="rec-card-body">
                  <p className="rec-initiative">{rec.initiativeName}</p>
                  <p className="rec-message">{rec.message}</p>
                  {rec.metricValue != null && (
                    <div className="rec-metric">
                      Current: <strong>{Number(rec.metricValue).toFixed(2)}</strong>
                      {rec.threshold != null && <> · Threshold: <strong>{Number(rec.threshold).toFixed(2)}</strong></>}
                    </div>
                  )}
                </div>
                <div className="rec-card-actions">
                  <button className="btn btn-sm btn-outline" onClick={() => onResolve(rec.recommendationId)}>
                    ✓ Resolve
                  </button>
                  <button className="btn btn-sm btn-ghost" onClick={() => onDismiss(rec.recommendationId)}>
                    Dismiss
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   Budget Pacing View
   ═══════════════════════════════════════════════════ */
function PacingView({ health, selectedInitiative, pacing, report, loading, onSelectInitiative }) {
  if (!selectedInitiative && health && health.length > 0) {
    return (
      <div>
        <div className="intel-section-header">
          <h3>Select a Campaign</h3>
        </div>
        <div className="pacing-select-grid">
          {health.map((init, i) => (
            <button key={i} className="pacing-select-card" onClick={() => onSelectInitiative(init)}>
              <span className="pacing-select-name">{init.name || 'Untitled'}</span>
              <span className="pacing-select-meta">{fmtCur(init.totalBudget)} · {init.objective || 'Campaign'}</span>
            </button>
          ))}
        </div>
      </div>
    );
  }

  if (!selectedInitiative) {
    return (
      <div className="empty-state">
        <h3>No campaigns available</h3>
        <p>Budget pacing data will appear here once you have active campaigns.</p>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="loading-placeholder padded">
        {[1,2,3,4].map(i => <div key={i} className="skeleton skeleton-row" style={{height:'60px', marginBottom:'12px'}} />)}
      </div>
    );
  }

  return (
    <div>
      <div className="intel-section-header">
        <h3>{selectedInitiative.name || 'Campaign'} — Budget Pacing</h3>
        <button className="btn btn-sm btn-outline" onClick={() => onSelectInitiative(null)}>
          ← Back
        </button>
      </div>

      {/* Pacing Overview */}
      {pacing && (
        <div className="pacing-overview">
          <div className="stats-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
            <div className="stat-card">
              <div className="stat-label">Total Budget</div>
              <div className="stat-value">{fmtCur(pacing.totalBudget)}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Spent to Date</div>
              <div className="stat-value">{fmtCur(pacing.actualSpendToDate)}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Expected Spend</div>
              <div className="stat-value">{fmtCur(pacing.expectedSpendToDate)}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Pacing</div>
              <div className={`stat-value ${
                pacing.overallPacingPct > 120 ? 'text-red' :
                pacing.overallPacingPct < 50 ? 'text-orange' : 'text-green'
              }`}>
                {fmtPct(pacing.overallPacingPct)}
              </div>
            </div>
          </div>

          {/* Pacing Bar */}
          <div className="pacing-bar-container">
            <div className="pacing-bar-labels">
              <span>Day {pacing.elapsedDays} of {pacing.campaignDays}</span>
              <span>{fmtCur(pacing.actualSpendToDate)} of {fmtCur(pacing.totalBudget)}</span>
            </div>
            <div className="pacing-bar">
              <div className="pacing-bar-expected" style={{width: `${Math.min((pacing.elapsedDays / pacing.campaignDays) * 100, 100)}%`}} />
              <div className={`pacing-bar-actual ${
                pacing.overallPacingPct > 120 ? 'overpacing' :
                pacing.overallPacingPct < 50 ? 'underpacing' : 'on-track'
              }`} style={{width: `${Math.min((pacing.actualSpendToDate / pacing.totalBudget) * 100, 100)}%`}} />
            </div>
            <div className="pacing-bar-legend">
              <span><span className="legend-dot expected"></span> Expected</span>
              <span><span className="legend-dot actual"></span> Actual</span>
            </div>
          </div>

          {/* Channel Pacing */}
          {pacing.channelPacing && (
            <div className="content-card" style={{marginTop: '20px'}}>
              <div className="content-card-header"><h3>Channel Breakdown</h3></div>
              <div className="content-card-body">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>Channel</th>
                      <th>Allocated</th>
                      <th>Spent</th>
                      <th>Utilization</th>
                      <th>Projected Total</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(typeof pacing.channelPacing === 'string' ? JSON.parse(pacing.channelPacing) : pacing.channelPacing).map((ch, i) => (
                      <tr key={i}>
                        <td style={{fontWeight: 500}}>{channelLabel(ch.channelType)}</td>
                        <td>{fmtCur(ch.allocatedBudget)}</td>
                        <td>{fmtCur(ch.totalSpend)}</td>
                        <td>{fmtPct(ch.budgetUtilPct)}</td>
                        <td>{fmtCur(ch.projectedTotalSpend)}</td>
                        <td>
                          <span className={`status-badge-sm status-${ch.pacingStatus === 'on_track' ? 'active' : ch.pacingStatus === 'overpacing' ? 'error' : 'paused'}`}>
                            {ch.pacingStatus === 'on_track' ? 'On Track' : ch.pacingStatus === 'overpacing' ? 'Overpacing' : 'Underpacing'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Post-Campaign Report Summary */}
      {report && report.totals && (
        <div style={{marginTop: '24px'}}>
          <h3 style={{fontSize: '16px', fontWeight: 600, marginBottom: '16px'}}>Performance Summary</h3>
          <div className="stats-grid" style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
            {(() => {
              const t = typeof report.totals === 'string' ? JSON.parse(report.totals) : report.totals;
              return [
                { label: 'Impressions', value: fmtNum(t.totalImpressions) },
                { label: 'Clicks', value: fmtNum(t.totalClicks) },
                { label: 'CTR', value: fmtPct(t.overallCtr) },
                { label: 'Avg CPC', value: fmtCur(t.overallCpc) },
                { label: 'Conversions', value: fmtNum(t.totalConversions) },
              ].map((s, i) => (
                <div key={i} className="stat-card">
                  <div className="stat-label">{s.label}</div>
                  <div className="stat-value" style={{fontSize: '20px'}}>{s.value}</div>
                </div>
              ));
            })()}
          </div>

          {/* Channel Comparison */}
          {report.channelComparison && (
            <div className="content-card" style={{marginTop: '20px'}}>
              <div className="content-card-header"><h3>Cross-Platform Comparison</h3></div>
              <div className="content-card-body">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>Channel</th>
                      <th>Impressions</th>
                      <th>Clicks</th>
                      <th>CTR</th>
                      <th>CPC</th>
                      <th>Spend</th>
                      <th>Conv.</th>
                      <th>ROAS</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(typeof report.channelComparison === 'string' ? JSON.parse(report.channelComparison) : report.channelComparison).map((ch, i) => (
                      <tr key={i}>
                        <td style={{fontWeight: 500}}>{channelLabel(ch.channelType)}</td>
                        <td>{fmtNum(ch.totalImpressions)}</td>
                        <td>{fmtNum(ch.totalClicks)}</td>
                        <td>{fmtPct(ch.ctr)}</td>
                        <td>{fmtCur(ch.cpc)}</td>
                        <td>{fmtCur(ch.totalSpend)}</td>
                        <td>{fmtNum(ch.totalConversions)}</td>
                        <td>{ch.roas != null ? Number(ch.roas).toFixed(2) + 'x' : '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
