import React, { useState, useEffect } from 'react';

// ── localStorage keys (must match FacebookAdsPanel.tsx) ───────────────────────
const LS_CACHE = 'fb_ads_summary_cache';
const LS_RATE  = 'fb_exchange_rate';

// ── Types ──────────────────────────────────────────────────────────────────────
interface AdsCache {
  spend_usd:   number;
  spend_bdt:   number;
  purchases:   number;
  roas:        number;
  clicks:      number;
  impressions: number;
  ctr:         number;
  cpc:         number;
  rate?:       number;
  preset?:     string;
  updatedAt?:  number;
}

interface UbaidiAdsMarketerProps {
  showToast: (msg: string, type?: 'success' | 'error') => void;
}

// ── Helpers ────────────────────────────────────────────────────────────────────
const fmt  = (n: number, d = 2) => n.toFixed(d);
const fmtK = (n: number) =>
  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M`
  : n >= 1_000   ? `${(n / 1_000).toFixed(1)}K`
  : String(Math.round(n));

const presetLabel: Record<string, string> = {
  today:      'আজ',
  last_7d:    'শেষ ৭ দিন',
  this_month: 'এই মাস',
  last_30d:   'শেষ ৩০ দিন',
  this_year:  'এই বছর',
};

function roasColor(roas: number): string {
  if (roas >= 8)  return '#4ade80';
  if (roas >= 5)  return '#fbbf24';
  if (roas >= 2)  return '#f97316';
  return '#f87171';
}

function roasLabel(roas: number): string {
  if (roas >= 8)  return '⭐ Excellent';
  if (roas >= 5)  return '✅ Good';
  if (roas >= 2)  return '⚠️ Average';
  return '❌ Low ROAS';
}

/** Format the cached data into a text prompt for the AI */
function formatDataForAI(d: AdsCache): string {
  const period = presetLabel[d.preset || 'last_7d'] || d.preset || 'selected period';
  const ctr    = d.ctr  > 0 ? fmt(d.ctr,  2) + '%' : 'N/A';
  const cpc    = d.cpc  > 0 ? '$' + fmt(d.cpc, 2)   : 'N/A';
  const bdt    = d.rate || 110;

  return `Facebook Ads Performance Data (${period}):
- Total Spend: $${fmt(d.spend_usd)} (≈ ৳${d.spend_bdt.toLocaleString()})
- Total Purchases/Sales: ${d.purchases}
- ROAS (Return on Ad Spend): ${d.roas > 0 ? fmt(d.roas, 2) + 'x' : 'N/A'}
- Total Clicks: ${fmtK(d.clicks)}
- Total Impressions: ${fmtK(d.impressions)}
- CTR (Click-Through Rate): ${ctr}
- CPC (Cost Per Click): ${cpc}
- Exchange Rate Used: $1 = ৳${bdt}
- Cost Per Purchase: ${d.purchases > 0 && d.spend_usd > 0 ? '$' + fmt(d.spend_usd / d.purchases, 2) : 'N/A'}`;
}

/* ─── Stat Card ─────────────────────────────────────────────────────────────── */
function KPICard({ icon, label, value, sub, color, bg, border }: {
  icon: string; label: string; value: string; sub: string;
  color: string; bg: string; border: string;
}) {
  return (
    <div style={{ background: bg, border: `1px solid ${border}`, borderRadius: 20, padding: '18px 20px', flex: 1, minWidth: 130 }}>
      <p style={{ margin: '0 0 8px', fontSize: 10, fontWeight: 800, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.6px' }}>
        {icon} {label}
      </p>
      <p style={{ margin: '0 0 4px', fontSize: 24, fontWeight: 900, color, lineHeight: 1 }}>{value}</p>
      <p style={{ margin: 0, fontSize: 11, color: '#64748b' }}>{sub}</p>
    </div>
  );
}

/* ── Bullet point renderer ───────────────────────────────────────────────────── */
function renderAnalysis(text: string) {
  // Split on bullet chars or numbered list
  const lines = text.split('\n').filter(l => l.trim());
  return lines.map((line, i) => {
    const isBullet = /^[•\-\*\d]/.test(line.trim());
    return (
      <div key={i} style={{
        display: 'flex', gap: 10, alignItems: 'flex-start',
        marginBottom: 14,
        padding: isBullet ? '12px 16px' : '0',
        background: isBullet ? 'rgba(139,92,246,0.07)' : 'transparent',
        borderLeft: isBullet ? '3px solid rgba(139,92,246,0.5)' : 'none',
        borderRadius: isBullet ? '0 12px 12px 0' : 0,
      }}>
        <p style={{
          margin: 0, fontSize: 13.5, lineHeight: 1.7,
          color: isBullet ? '#e2e8f0' : '#94a3b8',
          fontWeight: isBullet ? 500 : 400,
        }}>
          {line.trim()}
        </p>
      </div>
    );
  });
}

/* ══════════════════════════════════════════════════════════════════════════════
   Main Component
══════════════════════════════════════════════════════════════════════════════ */
export default function UbaidiAdsMarketer({ showToast }: UbaidiAdsMarketerProps) {
  const [cache, setCache]       = useState<AdsCache | null>(null);
  const [analysis, setAnalysis] = useState<string>('');
  const [loading, setLoading]   = useState(false);
  const [hasAnalyzed, setHasAnalyzed] = useState(false);

  // ── Load cache from localStorage ──────────────────────────────────────────
  const loadCache = () => {
    try {
      const raw = localStorage.getItem(LS_CACHE);
      if (raw) {
        const parsed = JSON.parse(raw) as AdsCache;
        // Override rate from LS_RATE if available
        const storedRate = parseFloat(localStorage.getItem(LS_RATE) || '0');
        if (storedRate > 0) parsed.rate = storedRate;
        setCache(parsed);
      } else {
        setCache(null);
      }
    } catch {
      setCache(null);
    }
  };

  useEffect(() => {
    loadCache();
    // Listen for updates from FacebookAdsPanel
    const handler = () => loadCache();
    window.addEventListener('fb_ads_cache_updated', handler);
    return () => window.removeEventListener('fb_ads_cache_updated', handler);
  }, []);

  // ── Fetch AI analysis ────────────────────────────────────────────────────
  const fetchAnalysis = async () => {
    if (!cache) {
      showToast('❌ Facebook Ads ডেটা নেই। আগে Facebook Ads ট্যাব থেকে ডেটা লোড করুন।', 'error');
      return;
    }

    setLoading(true);
    setAnalysis('');

    try {
      const dataString = formatDataForAI(cache);
      const res = await fetch('/api/ads/analyze', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ data: dataString, period: cache.preset || 'last_7_days' }),
      });

      const result = await res.json();

      if (result.success && result.analysis) {
        setAnalysis(result.analysis);
        setHasAnalyzed(true);
      } else {
        showToast('❌ ' + (result.error || 'AI বিশ্লেষণ ব্যর্থ হয়েছে।'), 'error');
      }
    } catch (err) {
      showToast('❌ সংযোগ সমস্যা। একটু পরে আবার চেষ্টা করুন।', 'error');
    } finally {
      setLoading(false);
    }
  };

  const updatedAgo = cache?.updatedAt
    ? (() => {
        const diff = Date.now() - cache.updatedAt;
        const mins = Math.floor(diff / 60000);
        if (mins < 1)   return 'এইমাত্র';
        if (mins < 60)  return `${mins} মিনিট আগে`;
        const hrs = Math.floor(mins / 60);
        if (hrs < 24)   return `${hrs} ঘণ্টা আগে`;
        return `${Math.floor(hrs / 24)} দিন আগে`;
      })()
    : null;

  /* ── RENDER ── */
  return (
    <div style={{ fontFamily: "'Inter','Hind Siliguri',sans-serif", paddingBottom: 60, maxWidth: 960, margin: '0 auto' }}>

      {/* ── HERO HEADER ─────────────────────────────────────────────────────── */}
      <div style={{
        background: 'linear-gradient(135deg, #1a0533 0%, #2d1b69 45%, #1e1b4b 100%)',
        borderRadius: 28, padding: '28px 30px', marginBottom: 24,
        border: '1px solid rgba(139,92,246,0.3)',
        boxShadow: '0 20px 60px rgba(79,70,229,0.25)',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Decorative glow orbs */}
        <div style={{ position: 'absolute', top: -40, right: -40, width: 160, height: 160, borderRadius: '50%', background: 'radial-gradient(circle, rgba(139,92,246,0.25) 0%, transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', bottom: -30, left: 100, width: 100, height: 100, borderRadius: '50%', background: 'radial-gradient(circle, rgba(99,102,241,0.2) 0%, transparent 70%)', pointerEvents: 'none' }} />

        <div style={{ position: 'relative', zIndex: 1, display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
          {/* AI icon */}
          <div style={{
            width: 60, height: 60, borderRadius: 18, flexShrink: 0,
            background: 'linear-gradient(135deg, #7c3aed, #4f46e5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 28, boxShadow: '0 8px 24px rgba(124,58,237,0.5)',
          }}>🤖</div>
          <div style={{ flex: 1 }}>
            <h1 style={{ margin: 0, fontSize: 26, fontWeight: 900, color: '#fff', letterSpacing: '-0.5px' }}>
              Ubaidi Ads Marketer
            </h1>
            <p style={{ margin: '4px 0 0', fontSize: 13, color: 'rgba(199,210,254,0.7)', fontWeight: 500 }}>
              AI-powered Facebook Ads insights &amp; recommendations — powered by Ubaidi AI (OpenRouter)
            </p>
          </div>
          {cache && (
            <div style={{
              background: 'rgba(16,185,129,0.12)', border: '1px solid rgba(16,185,129,0.3)',
              borderRadius: 12, padding: '8px 14px', textAlign: 'center', flexShrink: 0,
            }}>
              <p style={{ margin: 0, fontSize: 10, fontWeight: 800, color: '#34d399', textTransform: 'uppercase', letterSpacing: '0.5px' }}>ডেটা আছে ✓</p>
              <p style={{ margin: '2px 0 0', fontSize: 11, color: '#64748b' }}>
                {presetLabel[cache.preset || ''] || cache.preset} · {updatedAgo}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* ── NO CACHE STATE ───────────────────────────────────────────────────── */}
      {!cache && (
        <div style={{
          background: 'rgba(245,158,11,0.07)', border: '1px dashed rgba(245,158,11,0.35)',
          borderRadius: 20, padding: '32px 28px', marginBottom: 24, textAlign: 'center',
        }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>📡</div>
          <p style={{ margin: '0 0 6px', fontSize: 17, fontWeight: 800, color: '#fbbf24' }}>
            Facebook Ads ডেটা পাওয়া যায়নি
          </p>
          <p style={{ margin: '0 0 16px', fontSize: 13, color: '#94a3b8', lineHeight: 1.6 }}>
            প্রথমে <strong style={{ color: '#e2e8f0' }}>Facebook Ads</strong> ট্যাবে যান এবং আপনার API connect করুন।<br />
            ডেটা লোড হলে এখানে এসে বিশ্লেষণ করুন।
          </p>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            background: 'rgba(245,158,11,0.15)', border: '1px solid rgba(245,158,11,0.3)',
            borderRadius: 12, padding: '10px 18px', color: '#fbbf24', fontSize: 12, fontWeight: 700,
          }}>
            💡 Facebook Ads ট্যাবে যান → ডেটা লোড করুন → এখানে ফিরে আসুন
          </div>
        </div>
      )}

      {/* ── KPI CARDS ────────────────────────────────────────────────────────── */}
      {cache && (
        <>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 20 }}>
            <KPICard
              icon="💸" label="Total Spend"
              value={`$${fmt(cache.spend_usd)}`}
              sub={`≈ ৳${cache.spend_bdt.toLocaleString()}`}
              color="#f87171" bg="rgba(248,113,113,0.1)" border="rgba(248,113,113,0.22)"
            />
            <KPICard
              icon="🛍" label="Purchases"
              value={String(cache.purchases)}
              sub={cache.purchases > 0 && cache.spend_usd > 0
                ? `$${fmt(cache.spend_usd / cache.purchases)} / sale`
                : 'No sales'}
              color="#4ade80" bg="rgba(74,222,128,0.1)" border="rgba(74,222,128,0.22)"
            />
            <KPICard
              icon="📈" label="ROAS"
              value={cache.roas > 0 ? `${fmt(cache.roas, 1)}x` : '—'}
              sub={cache.roas > 0 ? roasLabel(cache.roas) : 'N/A'}
              color={cache.roas > 0 ? roasColor(cache.roas) : '#64748b'}
              bg={cache.roas >= 5 ? 'rgba(74,222,128,0.08)' : cache.roas >= 2 ? 'rgba(251,191,36,0.08)' : 'rgba(248,113,113,0.08)'}
              border={cache.roas >= 5 ? 'rgba(74,222,128,0.2)' : cache.roas >= 2 ? 'rgba(251,191,36,0.2)' : 'rgba(248,113,113,0.2)'}
            />
            <KPICard
              icon="👁" label="Impressions"
              value={fmtK(cache.impressions)}
              sub={`CTR ${fmt(cache.ctr)}%`}
              color="#818cf8" bg="rgba(129,140,248,0.1)" border="rgba(129,140,248,0.22)"
            />
            <KPICard
              icon="🖱" label="Clicks"
              value={fmtK(cache.clicks)}
              sub={`CPC $${fmt(cache.cpc)}`}
              color="#38bdf8" bg="rgba(56,189,248,0.1)" border="rgba(56,189,248,0.22)"
            />
          </div>

          {/* ── DATA PREVIEW ───────────────────────────────────────────────── */}
          <div style={{
            background: '#0a0f1e', border: '1px solid rgba(99,102,241,0.18)',
            borderRadius: 20, padding: '18px 22px', marginBottom: 20,
          }}>
            <p style={{ margin: '0 0 10px', fontSize: 11, fontWeight: 800, color: '#475569', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
              📋 AI-তে যা পাঠানো হবে
            </p>
            <pre style={{
              margin: 0, fontSize: 12, color: '#64748b', lineHeight: 1.8,
              fontFamily: "'JetBrains Mono','Fira Code',monospace",
              whiteSpace: 'pre-wrap', wordBreak: 'break-word',
            }}>
              {formatDataForAI(cache)}
            </pre>
          </div>
        </>
      )}

      {/* ── ANALYZE BUTTON ───────────────────────────────────────────────────── */}
      <div style={{
        background: '#0f172a', border: '1px solid rgba(139,92,246,0.2)',
        borderRadius: 24, padding: '28px 28px', marginBottom: 24, textAlign: 'center',
      }}>
        <p style={{ margin: '0 0 6px', fontSize: 15, fontWeight: 900, color: '#e2e8f0' }}>
          🤖 AI দিয়ে আমার Ads বিশ্লেষণ করুন
        </p>
        <p style={{ margin: '0 0 20px', fontSize: 12, color: '#64748b' }}>
          {cache
            ? 'Ubaidi AI আপনার Facebook Ads ডেটা বিশ্লেষণ করে ৫টি expert পরামর্শ দেবে।'
            : 'Facebook Ads ডেটা লোড করুন, তারপর বিশ্লেষণ করুন।'}
        </p>

        <button
          onClick={fetchAnalysis}
          disabled={loading || !cache}
          style={{
            padding: '16px 40px',
            borderRadius: 16, border: 'none', cursor: loading || !cache ? 'not-allowed' : 'pointer',
            fontSize: 15, fontWeight: 900, letterSpacing: '-0.2px',
            background: loading || !cache
              ? 'rgba(139,92,246,0.2)'
              : 'linear-gradient(135deg, #7c3aed 0%, #4f46e5 100%)',
            color: '#fff',
            boxShadow: loading || !cache ? 'none' : '0 8px 28px rgba(124,58,237,0.45)',
            transition: 'all 0.25s',
            display: 'inline-flex', alignItems: 'center', gap: 10,
          }}
          onMouseEnter={e => { if (!loading && cache) (e.currentTarget as HTMLButtonElement).style.transform = 'translateY(-2px)'; }}
          onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.transform = 'none'; }}
        >
          {loading ? (
            <>
              <span style={{ display: 'inline-block', animation: 'uamSpin 0.8s linear infinite' }}>⏳</span>
              Ubaidi বিশ্লেষণ করছে...
            </>
          ) : (
            <>🤖 Analyze My Ads</>
          )}
        </button>

        {loading && (
          <p style={{ margin: '14px 0 0', fontSize: 12, color: '#64748b' }}>
            AI উত্তর তৈরি করছে — এটি ৫–৩০ সেকেন্ড সময় নিতে পারে ☕
          </p>
        )}
      </div>

      {/* ── AI RESPONSE ──────────────────────────────────────────────────────── */}
      {hasAnalyzed && analysis && (
        <div style={{
          background: 'linear-gradient(160deg, #0d0b1e 0%, #0f172a 100%)',
          border: '1px solid rgba(139,92,246,0.25)',
          borderRadius: 24, overflow: 'hidden',
          boxShadow: '0 20px 60px rgba(124,58,237,0.15)',
          animation: 'uamFadeIn 0.5s ease',
        }}>
          {/* Header */}
          <div style={{
            background: 'linear-gradient(135deg, rgba(124,58,237,0.25), rgba(79,70,229,0.18))',
            borderBottom: '1px solid rgba(139,92,246,0.18)',
            padding: '18px 24px',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 14,
              background: 'linear-gradient(135deg, #7c3aed, #4f46e5)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 20, flexShrink: 0, boxShadow: '0 4px 14px rgba(124,58,237,0.5)',
            }}>💡</div>
            <div>
              <p style={{ margin: 0, fontSize: 16, fontWeight: 900, color: '#fff' }}>Ubaidi Says:</p>
              <p style={{ margin: '2px 0 0', fontSize: 11, color: '#a78bfa' }}>
                {presetLabel[cache?.preset || ''] || 'Selected period'} — এর Facebook Ads বিশ্লেষণ
              </p>
            </div>
            <button
              onClick={() => setAnalysis('')}
              style={{
                marginLeft: 'auto', background: 'rgba(255,255,255,0.07)',
                border: 'none', borderRadius: 10, padding: '7px 12px',
                color: '#64748b', fontSize: 11, fontWeight: 700, cursor: 'pointer',
              }}
            >
              ✕ Close
            </button>
          </div>

          {/* Body */}
          <div style={{ padding: '24px 28px' }}>
            {renderAnalysis(analysis)}
          </div>

          {/* Footer */}
          <div style={{
            borderTop: '1px solid rgba(139,92,246,0.1)',
            padding: '14px 28px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8,
          }}>
            <p style={{ margin: 0, fontSize: 11, color: '#334155' }}>
              🤖 Powered by Ubaidi AI (OpenRouter / openai/gpt-oss-120b:free) · এই পরামর্শ AI-generated — যাচাই করে সিদ্ধান্ত নিন
            </p>
            <button
              onClick={fetchAnalysis}
              disabled={loading}
              style={{
                background: 'rgba(124,58,237,0.15)', border: '1px solid rgba(124,58,237,0.3)',
                borderRadius: 10, padding: '7px 16px', color: '#a78bfa',
                fontSize: 11, fontWeight: 800, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 6,
              }}
            >
              🔄 আবার বিশ্লেষণ করুন
            </button>
          </div>
        </div>
      )}

      {/* ── TIPS FOOTER ─────────────────────────────────────────────────────── */}
      {!hasAnalyzed && !loading && (
        <div style={{
          background: '#0a0f1e', border: '1px solid rgba(99,102,241,0.12)',
          borderRadius: 20, padding: '20px 24px',
        }}>
          <p style={{ margin: '0 0 12px', fontSize: 11, fontWeight: 800, color: '#475569', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
            💡 কীভাবে ব্যবহার করবেন
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 10 }}>
            {[
              { step: '1', text: '📊 Facebook Ads ট্যাবে যান ও API connect করুন' },
              { step: '2', text: '🔄 ডেটা লোড হলে এই পেজে ফিরে আসুন' },
              { step: '3', text: '🤖 "Analyze My Ads" বাটনে click করুন' },
              { step: '4', text: '💡 Ubaidi-র পরামর্শ অনুযায়ী Ads optimize করুন' },
            ].map(s => (
              <div key={s.step} style={{
                background: 'rgba(99,102,241,0.07)', border: '1px solid rgba(99,102,241,0.14)',
                borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'flex-start', gap: 10,
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 8, background: 'rgba(139,92,246,0.25)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 900, color: '#a78bfa', flexShrink: 0,
                }}>
                  {s.step}
                </div>
                <p style={{ margin: 0, fontSize: 12, color: '#64748b', lineHeight: 1.5 }}>{s.text}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── CSS ─────────────────────────────────────────────────────────────── */}
      <style>{`
        @keyframes uamSpin    { to { transform: rotate(360deg); } }
        @keyframes uamFadeIn  { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
      `}</style>
    </div>
  );
}
