import { useState, useRef, useEffect } from 'react';
import { insights } from '../lib/api';

function Sparkline({ history, movement }) {
  const canvasRef = useRef();
  useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const ctx = c.getContext('2d');
    ctx.clearRect(0, 0, c.width, c.height);
    const valid = (history || []).filter(v => v != null);
    if (valid.length < 2) return;
    const w = c.width, h = c.height;
    const mn = Math.min(...valid), mx = Math.max(...valid), range = mx - mn || 1;
    const pts = (history || []).map((v, i) => ({
      x: (i / (history.length - 1)) * (w - 4) + 2,
      y: v == null ? null : h - 2 - ((v - mn) / range) * (h - 4),
    })).filter(p => p.y != null);
    const col = movement === 'up' ? '#1D9E75' : movement === 'down' ? '#E24B4A' : '#888780';
    ctx.strokeStyle = col; ctx.lineWidth = 1.5; ctx.lineJoin = 'round';
    ctx.beginPath();
    pts.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
    ctx.stroke();
    const last = pts[pts.length - 1];
    ctx.fillStyle = col; ctx.beginPath(); ctx.arc(last.x, last.y, 2.5, 0, Math.PI * 2); ctx.fill();
  }, [history, movement]);
  return <canvas ref={canvasRef} width={56} height={24} style={{ display: 'block' }} />;
}

function PosBadge({ pos }) {
  if (!pos && pos !== 0) return <span className="pbadge p20p">—</span>;
  const p = parseFloat(pos);
  const cls = p <= 3 ? 'p13' : p <= 10 ? 'p410' : p <= 20 ? 'p1120' : 'p20p';
  return <span className={`pbadge ${cls}`}>#{Math.round(p)}</span>;
}

function MoveBadge({ movement, delta }) {
  if (movement === 'new') return <span className="mbadge mnw">✦ New</span>;
  if (!delta && delta !== 0) return <span className="mbadge mst">—</span>;
  if (Math.abs(delta) < 0.5) return <span className="mbadge mst">— Stable</span>;
  if (delta > 0) return <span className="mbadge mup">↑ +{Math.round(delta)}</span>;
  return <span className="mbadge mdn">↓ {Math.round(delta)}</span>;
}

function fmtNum(n) {
  if (n == null) return '—';
  if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
  return String(n);
}

export default function KeywordTracker({ keywords = [], loading }) {
  const [filter, setFilter]       = useState('all');
  const [sortBy, setSortBy]       = useState('clicks');
  const [expandedKw, setExpandedKw] = useState(null);
  const [kwInsight, setKwInsight]   = useState({});
  const [loadingInsight, setLoadingInsight] = useState(null);

  const counts = {
    up:     keywords.filter(k => k.movement === 'up').length,
    down:   keywords.filter(k => k.movement === 'down').length,
    stable: keywords.filter(k => k.movement === 'stable').length,
    new:    keywords.filter(k => k.movement === 'new').length,
  };

  const filtered = keywords
    .filter(k => filter === 'all' || k.movement === filter)
    .sort((a, b) => {
      if (sortBy === 'clicks')      return (b.clicks || 0) - (a.clicks || 0);
      if (sortBy === 'impressions') return (b.impressions || 0) - (a.impressions || 0);
      if (sortBy === 'position')    return (a.position || 999) - (b.position || 999);
      if (sortBy === 'ctr')         return (b.ctr || 0) - (a.ctr || 0);
      return 0;
    });

  const handleKwClick = async (kw) => {
    if (expandedKw === kw.keyword) { setExpandedKw(null); return; }
    setExpandedKw(kw.keyword);
    if (!kwInsight[kw.keyword]) {
      setLoadingInsight(kw.keyword);
      try {
        const res = await insights.keyword({
          keyword: kw.keyword,
          position: kw.position,
          prevPosition: kw.prevPosition,
          searchVolume: kw.searchVolume,
          clicks: kw.clicks,
          impressions: kw.impressions,
          ctr: kw.ctr,
        });
        setKwInsight(p => ({ ...p, [kw.keyword]: res.recommendations }));
      } catch {
        setKwInsight(p => ({ ...p, [kw.keyword]: 'Could not load recommendations.' }));
      }
      finally { setLoadingInsight(null); }
    }
  };

  const filterBtns = [
    { key: 'all',    label: 'All queries',          cls: 'fall' },
    { key: 'up',     label: `↑ Improved (${counts.up})`,   cls: 'fup' },
    { key: 'down',   label: `↓ Declined (${counts.down})`, cls: 'fdn' },
    { key: 'stable', label: `— Stable (${counts.stable})`, cls: 'fst' },
  ];

  const sortBtns = [
    { key: 'clicks',      label: 'Clicks' },
    { key: 'impressions', label: 'Impressions' },
    { key: 'position',    label: 'Position' },
    { key: 'ctr',         label: 'CTR' },
  ];

  if (loading) return <div className="skeleton" style={{ height: 300, borderRadius: 8 }} />;

  return (
    <div>
      {/* Summary counts */}
      <div className="kw-summary">
        <div className="ksum"><div className="ksum-lbl">Improved</div><div className="ksum-val up">{counts.up}</div></div>
        <div className="ksum"><div className="ksum-lbl">Declined</div><div className="ksum-val dn">{counts.down}</div></div>
        <div className="ksum"><div className="ksum-lbl">Stable</div><div className="ksum-val">{counts.stable}</div></div>
        <div className="ksum"><div className="ksum-lbl">Total queries</div><div className="ksum-val info">{keywords.length}</div></div>
      </div>

      {/* Filters + sort */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
        <div className="filters" style={{ margin: 0 }}>
          {filterBtns.map(f => (
            <button key={f.key} className={`fbtn ${f.cls} ${filter === f.key ? 'active' : ''}`} onClick={() => setFilter(f.key)}>
              {f.label}
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
          <span style={{ fontSize: 11, color: 'var(--text2)', marginRight: 2 }}>Sort:</span>
          {sortBtns.map(s => (
            <button key={s.key} onClick={() => setSortBy(s.key)}
              style={{ fontSize: 11, padding: '3px 8px', borderRadius: 5, border: '0.5px solid var(--border2)', background: sortBy === s.key ? 'var(--surface)' : 'transparent', color: sortBy === s.key ? 'var(--text)' : 'var(--text2)', cursor: 'pointer', fontWeight: sortBy === s.key ? 500 : 400 }}>
              {s.label}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div style={{ overflowX: 'auto' }}>
        <table className="kwtable">
          <thead>
            <tr>
              <th style={{ width: '30%' }}>Query (from GSC)</th>
              <th className="rc" style={{ width: '8%' }}>Pos</th>
              <th className="rc" style={{ width: '8%' }}>Prev</th>
              <th className="rc" style={{ width: '11%' }}>Change</th>
              <th className="rr" style={{ width: '8%' }}>Clicks</th>
              <th className="rr" style={{ width: '10%' }}>Impr.</th>
              <th className="rr" style={{ width: '7%' }}>CTR</th>
              <th className="rr" style={{ width: '10%' }}>7d trend</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((kw, i) => (
              <>
                <tr key={kw.keyword} onClick={() => handleKwClick(kw)} style={{ cursor: 'pointer' }}>
                  <td>
                    <div style={{ fontWeight: 500, color: 'var(--text)', fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {kw.keyword}
                    </div>
                  </td>
                  <td className="rc"><PosBadge pos={kw.position} /></td>
                  <td className="rc"><PosBadge pos={kw.prevPosition} /></td>
                  <td className="rc"><MoveBadge movement={kw.movement} delta={kw.positionDelta} /></td>
                  <td className="rr" style={{ fontSize: 11, fontWeight: 500, color: 'var(--text)' }}>{fmtNum(kw.clicks)}</td>
                  <td className="rr" style={{ fontSize: 11, color: 'var(--text2)' }}>{fmtNum(kw.impressions)}</td>
                  <td className="rr" style={{ fontSize: 11, color: 'var(--text2)' }}>{kw.ctr != null ? kw.ctr + '%' : '—'}</td>
                  <td className="rr"><Sparkline history={kw.positionHistory} movement={kw.movement} /></td>
                </tr>
                {expandedKw === kw.keyword && (
                  <tr key={kw.keyword + '_exp'}>
                    <td colSpan={8} style={{ background: 'var(--blue-bg)', padding: '10px 14px', fontSize: 12, color: 'var(--blue-text)', lineHeight: 1.6 }}>
                      {loadingInsight === kw.keyword
                        ? 'Generating AI recommendations…'
                        : <pre style={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit', margin: 0 }}>{kwInsight[kw.keyword]}</pre>
                      }
                    </td>
                  </tr>
                )}
              </>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={8} style={{ padding: '20px 0', textAlign: 'center', fontSize: 12, color: 'var(--text2)' }}>No queries match this filter.</td></tr>
            )}
          </tbody>
        </table>
      </div>
      <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 8 }}>
        {filtered.length} of {keywords.length} queries · Source: Google Search Console · Comparison vs previous {28} days
      </div>
    </div>
  );
}
