import React, { useState, useMemo } from 'react';
import { useApp } from '@modelcontextprotocol/ext-apps/react';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { PageHeader } from '../../components/layout/PageHeader';
import { MetricCard } from '../../components/data/MetricCard';
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;
}

const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const METRICS = ['ctr', 'cpc', 'cpm', 'conversions', 'roas'];

function getHeatColor(value: number, min: number, max: number, hasData: boolean): string {
  if (!hasData) return '#0a1628';
  const range = max - min || 1;
  const normalized = (value - min) / range;
  if (normalized < 0.25) return '#0f3460';
  if (normalized < 0.5) return '#3498db';
  if (normalized < 0.75) return '#e94560';
  return '#ff6b9d';
}

function formatHour(h: number): string {
  return h === 0 ? '12a' : h < 12 ? `${h}a` : h === 12 ? '12p' : `${h - 12}p`;
}

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

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

  const heatmapData: number[][] = data?.heatmapData || Array(7).fill(0).map(() => Array(24).fill(0));
  const counts: number[][] = data?.counts || Array(7).fill(0).map(() => Array(24).fill(0));
  const metric = data?.metric || activeMetric;
  const insights = data?.insights || {};

  const { minValue, maxValue, bestSlot, worstSlot, avgValue } = useMemo(() => {
    let min = Infinity, max = -Infinity;
    let best = { day: 0, hour: 0, value: -Infinity };
    let worst = { day: 0, hour: 0, value: Infinity };
    let total = 0, count = 0;

    for (let d = 0; d < 7; d++) {
      for (let h = 0; h < 24; h++) {
        const val = heatmapData[d]?.[h] || 0;
        const cnt = counts[d]?.[h] || 0;
        if (cnt > 0) {
          min = Math.min(min, val);
          max = Math.max(max, val);
          if (val > best.value) best = { day: d, hour: h, value: val };
          if (val < worst.value) worst = { day: d, hour: h, value: val };
          total += val;
          count++;
        }
      }
    }
    return {
      minValue: min === Infinity ? 0 : min,
      maxValue: max === -Infinity ? 0 : max,
      bestSlot: insights.bestSlot || best,
      worstSlot: insights.worstSlot || worst,
      avgValue: insights.avg || (count > 0 ? total / count : 0),
    };
  }, [heatmapData, counts, insights]);

  const fmtVal = (v: number) => metric === 'ctr' || metric === 'roas' ? v.toFixed(2) : v.toFixed(0);

  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>;

  return (
    <PageHeader title={`🔥 Performance Heatmap — ${metric.toUpperCase()}`} subtitle={data?.datePreset || 'last_7d'}>
      <div className="filter-chips" style={{ marginTop: 6, marginBottom: 8 }}>
        {METRICS.map(m => (
          <button key={m} className={`chip ${activeMetric === m ? 'chip-active' : ''}`} onClick={() => setActiveMetric(m)}>
            {m.toUpperCase()}
          </button>
        ))}
      </div>

      <div className="card" style={{ padding: 16 }}>
        <div className="heatmap-wrap">
          <div className="heatmap-grid">
            <div />
            {Array.from({ length: 24 }, (_, h) => <div key={h} className="heatmap-hour-label">{formatHour(h)}</div>)}
            {DAYS.map((day, di) => (
              <React.Fragment key={day}>
                <div className="heatmap-day-label">{day}</div>
                {Array.from({ length: 24 }, (_, h) => {
                  const val = heatmapData[di]?.[h] || 0;
                  const cnt = counts[di]?.[h] || 0;
                  const color = getHeatColor(val, minValue, maxValue, cnt > 0);
                  return (
                    <div key={h} className="heatmap-cell" style={{ background: color }} title={`${day} ${h}:00 — ${cnt > 0 ? fmtVal(val) : 'N/A'}`}>
                      {cnt > 0 ? fmtVal(val) : ''}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16, paddingTop: 12, borderTop: '1px solid #0f3460' }}>
          <span style={{ color: '#999', fontSize: 12, fontWeight: 600 }}>Intensity:</span>
          <div style={{ height: 16, width: 200, borderRadius: 3, background: 'linear-gradient(90deg, #0f3460, #3498db, #e94560, #ff6b9d)' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', width: 200, fontSize: 10, color: '#777' }}>
            <span>Low</span><span>Med</span><span>High</span>
          </div>
        </div>
      </div>

      <div className="stats-grid stats-grid-3" style={{ marginTop: 8 }}>
        <MetricCard label={`Average ${metric.toUpperCase()}`} value={avgValue > 0 ? fmtVal(avgValue) : '—'} color="blue" />
        <MetricCard label="Best Time Slot" value={bestSlot.value > -Infinity ? `${DAYS[bestSlot.day]} ${bestSlot.hour}:00` : '—'} color="green" />
        <MetricCard label="Worst Time Slot" value={worstSlot.value < Infinity ? `${DAYS[worstSlot.day]} ${worstSlot.hour}:00` : '—'} color="red" />
      </div>
    </PageHeader>
  );
}
