import { useState } from 'react'
import { Brain, TrendingUp, TrendingDown, RefreshCw, Zap, AlertTriangle, BookOpen, Target, Eye, Clock, ChevronRight } from 'lucide-react'
import clsx from 'clsx'
import { usePortfolioReportData, useGeneratePortfolioReport, useAiReportsList, useAiReport } from '../hooks/useApi'
import { useQueryClient } from '@tanstack/react-query'

const SCENARIO_META: Record<string, { label: string; color: string; emoji: string }> = {
  goldilocks:      { label: 'Goldilocks',      color: '#22c55e', emoji: '🌟' },
  desinflation:    { label: 'Désinflation',    color: '#06b6d4', emoji: '❄️' },
  soft_landing:    { label: 'Soft Landing',    color: '#3b82f6', emoji: '🛬' },
  reflation:       { label: 'Reflation',       color: '#f97316', emoji: '🔥' },
  stagflation:     { label: 'Stagflation',     color: '#eab308', emoji: '⚡' },
  inflation_shock: { label: 'Inflation Shock', color: '#ef4444', emoji: '💥' },
  recession:       { label: 'Récession',       color: '#8b5cf6', emoji: '📉' },
  crise_liquidite: { label: 'Crise Liquidité', color: '#ec4899', emoji: '🚨' },
  incertain:       { label: 'Incertain',       color: '#64748b', emoji: '❓' },
}

function ScenarioBadge({ dominant }: { dominant: string }) {
  const m = SCENARIO_META[dominant] ?? SCENARIO_META.incertain
  return (
    <span
      className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] font-semibold"
      style={{ background: `${m.color}22`, color: m.color, border: `1px solid ${m.color}44` }}
    >
      {m.emoji} {m.label}
    </span>
  )
}

function PnlBar({ pnl }: { pnl: number }) {
  const pos = pnl >= 0
  const width = Math.min(Math.abs(pnl), 200) / 2 // cap at 100% width
  return (
    <div className="flex items-center gap-2">
      <span className={clsx('font-bold font-mono text-sm w-16 text-right', pos ? 'text-emerald-400' : 'text-red-400')}>
        {pos ? '+' : ''}{pnl.toFixed(1)}%
      </span>
      <div className="flex-1 h-1.5 bg-dark-700 rounded-full overflow-hidden">
        <div
          className="h-full rounded-full"
          style={{ width: `${width}%`, background: pos ? '#22c55e' : '#ef4444' }}
        />
      </div>
    </div>
  )
}

function ScoreTrend({ trend }: { trend: number[] }) {
  if (!trend || trend.length === 0) return <span className="text-slate-700 text-xs">—</span>
  return (
    <div className="flex items-end gap-0.5 h-6">
      {trend.map((s, i) => (
        <div
          key={i}
          className="w-2 rounded-sm"
          style={{
            height: `${Math.max(3, (s ?? 0) / 100 * 24)}px`,
            background: (s ?? 0) >= 60 ? '#22c55e' : (s ?? 0) >= 40 ? '#eab308' : '#64748b',
          }}
          title={`${s}/100`}
        />
      ))}
    </div>
  )
}

function MoverCard({ trade, rank, type }: { trade: any; rank: number; type: 'winner' | 'loser' }) {
  const [expanded, setExpanded] = useState(false)
  const pnl = trade.pnl_pct ?? 0
  const sc = trade.scoring_context ?? {}
  const scOut = sc.output ?? {}
  const sg = trade.suggestion_context ?? {}
  const sgOut = sg.output ?? {}
  const buckets: any[] = scOut.buckets ?? []
  const isWinner = type === 'winner'

  return (
    <div className={clsx(
      'card border',
      isWinner ? 'border-emerald-700/20' : 'border-red-700/20'
    )}>
      <div className="flex items-start gap-3">
        {/* Rank */}
        <div className={clsx(
          'w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0',
          isWinner ? 'bg-emerald-900/40 text-emerald-400' : 'bg-red-900/40 text-red-400'
        )}>
          {rank}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center justify-between gap-2 mb-1">
            <div className="flex items-center gap-2 min-w-0">
              <span className="font-semibold text-slate-200 truncate">{trade.pattern_name || trade.pattern_id}</span>
              <span className={clsx('text-[10px] font-semibold px-1.5 py-0.5 rounded',
                trade.direction === 'bearish' ? 'bg-red-900/30 text-red-400' : 'bg-emerald-900/30 text-emerald-400')}>
                {trade.direction === 'bearish' ? '🐻' : '🐂'} {trade.strategy}
              </span>
              <span className="font-mono text-slate-400 text-xs">{trade.underlying}</span>
            </div>
            <button
              onClick={() => setExpanded(v => !v)}
              className="text-slate-600 hover:text-slate-400 shrink-0"
            >
              <Eye className="w-3.5 h-3.5" />
            </button>
          </div>

          <PnlBar pnl={pnl} />

          <div className="flex flex-wrap items-center gap-3 mt-2 text-[11px] text-slate-500">
            <span>Score entrée : <span className="font-mono text-slate-300">{trade.score_at_entry ?? '?'}/100</span></span>
            <span>EV : <span className={clsx('font-mono', (trade.ev_net ?? 0) > 0 ? 'text-emerald-400' : 'text-red-400')}>
              {trade.ev_net != null ? `${(trade.ev_net * 100).toFixed(0)}%` : '—'}
            </span></span>
            {sc.macro_dominant && <ScenarioBadge dominant={sc.macro_dominant} />}
            {sc.geo_score != null && <span>Géo <span className="font-mono text-slate-300">{sc.geo_score}/100</span></span>}
            <span className="ml-auto text-slate-700">{trade.entry_date}</span>
          </div>

          {scOut.key_catalyst && (
            <p className="mt-1.5 text-[11px] text-slate-500 italic">
              Catalyseur : {scOut.key_catalyst}
            </p>
          )}

          {trade.score_trend?.length > 0 && (
            <div className="flex items-center gap-2 mt-2">
              <span className="text-[10px] text-slate-600">Score trend :</span>
              <ScoreTrend trend={trade.score_trend} />
            </div>
          )}

          {expanded && (
            <div className="mt-3 space-y-2 border-t border-slate-800 pt-3 text-xs">
              {/* Thèse d'origine */}
              {(sgOut.macro_fit || sgOut.description) && (
                <div>
                  <span className="text-slate-600 font-medium">Thèse initiale : </span>
                  <span className="text-slate-400">{sgOut.macro_fit || sgOut.description}</span>
                </div>
              )}
              {/* Piliers */}
              {buckets.length > 0 && (
                <div className="grid grid-cols-2 gap-1.5 mt-2">
                  {buckets.map((b: any, i: number) => {
                    const pct = b.max ? Math.round((b.score / b.max) * 100) : 0
                    const color = pct >= 66 ? '#22c55e' : pct >= 33 ? '#eab308' : '#ef4444'
                    return (
                      <div key={i} className="flex items-center gap-2 bg-dark-800 rounded px-2 py-1">
                        <div className="w-10 h-1 bg-dark-700 rounded-full overflow-hidden shrink-0">
                          <div className="h-full rounded-full" style={{ width: `${pct}%`, background: color }} />
                        </div>
                        <span className="text-slate-500 truncate">{b.label ?? b.id}</span>
                        <span className="font-mono ml-auto shrink-0" style={{ color }}>{b.score}/{b.max}</span>
                      </div>
                    )
                  })}
                </div>
              )}
              {scOut.summary && (
                <p className="text-slate-600 italic mt-1">{scOut.summary}</p>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

function ReportSection({ icon: Icon, title, content, color = 'text-slate-300' }: {
  icon: any; title: string; content: string | string[]; color?: string
}) {
  return (
    <div className="space-y-1.5">
      <div className="flex items-center gap-2 text-sm font-semibold text-slate-400">
        <Icon className="w-4 h-4" />
        {title}
      </div>
      {Array.isArray(content) ? (
        <ul className="space-y-1 pl-4">
          {content.map((item, i) => (
            <li key={i} className={clsx('text-sm', color)}>• {item}</li>
          ))}
        </ul>
      ) : (
        <p className={clsx('text-sm leading-relaxed', color)}>{content}</p>
      )}
    </div>
  )
}

export default function RapportIA() {
  const [days, setDays] = useState(30)
  const [selectedHistoryId, setSelectedHistoryId] = useState<number | null>(null)
  const [showHistory, setShowHistory] = useState(false)

  const queryClient = useQueryClient()
  const { data: rawData, isLoading: loadingRaw, refetch } = usePortfolioReportData(days)
  const { mutate: generate, isPending: generating, data: freshReportData, reset: resetFresh } = useGeneratePortfolioReport()
  const { data: historyList } = useAiReportsList()
  const { data: historicReport } = useAiReport(selectedHistoryId)

  const history: any[] = (historyList as any)?.reports ?? []

  // Active report: either a loaded historic one, or the freshly generated one
  const activeHistoric = historicReport as any
  const fresh = freshReportData as any
  const raw = rawData as any

  const rep = selectedHistoryId && activeHistoric ? activeHistoric : fresh
  const report = rep?.report ?? null
  const stats = rep?.stats ?? raw
  const winners = rep?.winners ?? raw?.winners ?? []
  const losers  = rep?.losers  ?? raw?.losers  ?? []
  const avgPnl = stats?.avg_pnl_pct ?? null

  function handleGenerate() {
    setSelectedHistoryId(null)
    resetFresh()
    generate(days, {
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['ai-reports-list'] })
      },
    })
  }

  return (
    <div className="flex h-full">
      {/* History sidebar */}
      {showHistory && (
        <aside className="w-64 shrink-0 border-r border-slate-700/40 bg-dark-800 flex flex-col h-screen sticky top-0 overflow-y-auto">
          <div className="p-3 border-b border-slate-700/40 flex items-center justify-between">
            <span className="text-xs font-semibold text-slate-400 uppercase tracking-wide">Rapports archivés</span>
            <button onClick={() => setShowHistory(false)} className="text-slate-600 hover:text-slate-400 text-xs">✕</button>
          </div>
          {history.length === 0 ? (
            <div className="p-4 text-xs text-slate-600 text-center mt-4">
              Aucun rapport archivé.<br />Générez votre premier rapport.
            </div>
          ) : (
            <div className="flex flex-col divide-y divide-slate-800">
              {history.map((r: any) => {
                const avg = r.stats?.avg_pnl_pct
                const date = r.created_at?.slice(0, 16).replace('T', ' ') ?? ''
                const isActive = selectedHistoryId === r.id
                return (
                  <button
                    key={r.id}
                    onClick={() => { setSelectedHistoryId(r.id) }}
                    className={clsx(
                      'text-left px-3 py-2.5 hover:bg-dark-700/50 transition-colors',
                      isActive && 'bg-blue-900/20 border-l-2 border-blue-500'
                    )}
                  >
                    <div className="flex items-center justify-between mb-0.5">
                      <span className="text-[11px] font-mono text-slate-500">{date}</span>
                      <span className="text-[10px] text-slate-600">{r.days}j</span>
                    </div>
                    {r.report?.headline && (
                      <p className="text-xs text-slate-400 line-clamp-2 leading-snug">{r.report.headline}</p>
                    )}
                    {avg != null && (
                      <span className={clsx('text-[11px] font-mono font-bold mt-1 block',
                        avg >= 0 ? 'text-emerald-400' : 'text-red-400')}>
                        {avg >= 0 ? '+' : ''}{avg.toFixed(1)}% moy.
                      </span>
                    )}
                    {isActive && <ChevronRight className="w-3 h-3 text-blue-400 mt-1" />}
                  </button>
                )
              })}
            </div>
          )}
        </aside>
      )}

      <div className="flex-1 p-6 space-y-6 max-w-5xl overflow-auto">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            {!showHistory && (
              <button
                onClick={() => setShowHistory(true)}
                className="flex items-center gap-1.5 px-2.5 py-1.5 rounded border border-slate-700/40 text-slate-500 hover:text-slate-300 text-xs"
                title={`${history.length} rapport${history.length !== 1 ? 's' : ''} archivé${history.length !== 1 ? 's' : ''}`}
              >
                <Clock className="w-3.5 h-3.5" />
                {history.length > 0 && <span className="font-mono">{history.length}</span>}
              </button>
            )}
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                <Brain className="w-6 h-6 text-blue-400" />
                Rapport IA — Performance & Analyse
                {selectedHistoryId && activeHistoric && (
                  <span className="text-xs font-normal text-slate-500 ml-2">
                    archivé · {activeHistoric.created_at?.slice(0, 10)}
                  </span>
                )}
              </h1>
              <p className="text-sm text-slate-500 mt-0.5">
                Synthèse des top mouvements + explication GPT-4o basée sur les traces de raisonnement
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3">
            {selectedHistoryId && (
              <button
                onClick={() => setSelectedHistoryId(null)}
                className="text-xs text-slate-500 hover:text-slate-300 px-2.5 py-1.5 rounded border border-slate-700/40"
              >
                ← Nouveau
              </button>
            )}
            {/* Période — only relevant for new generation */}
            {!selectedHistoryId && (
              <div className="flex items-center gap-2 text-sm text-slate-400">
                <span>Période :</span>
                {[7, 14, 30, 90].map(d => (
                  <button
                    key={d}
                    onClick={() => setDays(d)}
                    className={clsx(
                      'px-2.5 py-1 rounded text-xs font-medium transition-colors',
                      days === d
                        ? 'bg-blue-900/40 text-blue-300 border border-blue-700/40'
                        : 'bg-dark-700 text-slate-500 hover:text-slate-300'
                    )}
                  >
                    {d}j
                  </button>
                ))}
              </div>
            )}

            {!selectedHistoryId && (
              <button
                onClick={() => refetch()}
                disabled={loadingRaw}
                className="text-slate-600 hover:text-slate-400 disabled:opacity-40"
              >
                <RefreshCw className={clsx('w-4 h-4', loadingRaw && 'animate-spin')} />
              </button>
            )}

            <button
              onClick={handleGenerate}
              disabled={generating}
              className="flex items-center gap-2 px-4 py-2 rounded bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium transition-colors"
            >
              <Zap className={clsx('w-4 h-4', generating && 'animate-pulse')} />
              {generating ? 'Génération GPT-4o…' : 'Générer rapport IA'}
            </button>
          </div>
        </div>

      {/* Stats bar */}
      {(loadingRaw || stats) && (
        <div className="grid grid-cols-3 gap-4">
          {[
            { label: 'Trades total', value: stats?.total_trades ?? '…' },
            { label: 'Trades pricés', value: stats?.priced_count ?? '…' },
            {
              label: 'P&L moyen',
              value: avgPnl != null
                ? <span className={clsx('font-bold', avgPnl >= 0 ? 'text-emerald-400' : 'text-red-400')}>
                    {avgPnl >= 0 ? '+' : ''}{avgPnl.toFixed(1)}%
                  </span>
                : '—'
            },
          ].map(({ label, value }) => (
            <div key={label} className="card text-center">
              <div className="text-2xl font-bold text-white">{value}</div>
              <div className="text-xs text-slate-500 mt-0.5">{label}</div>
            </div>
          ))}
        </div>
      )}

      {/* GPT-4o report */}
      {report && (
        <div className="card border border-blue-700/30 space-y-5">
          <div className="flex items-center gap-2 text-blue-400 font-semibold">
            <Brain className="w-4 h-4" />
            Analyse GPT-4o
          </div>

          {report.headline && (
            <p className="text-base font-medium text-white border-l-2 border-blue-500 pl-3">
              {report.headline}
            </p>
          )}

          <div className="grid grid-cols-2 gap-5">
            {report.winners_analysis && (
              <ReportSection
                icon={TrendingUp}
                title="Pourquoi les gains"
                content={report.winners_analysis}
                color="text-emerald-300"
              />
            )}
            {report.losers_analysis && (
              <ReportSection
                icon={TrendingDown}
                title="Pourquoi les pertes"
                content={report.losers_analysis}
                color="text-red-300"
              />
            )}
          </div>

          {report.regime_assessment && (
            <ReportSection
              icon={Eye}
              title="Alignement régime macro"
              content={report.regime_assessment}
            />
          )}

          {report.key_lessons?.length > 0 && (
            <ReportSection
              icon={BookOpen}
              title="Leçons clés"
              content={report.key_lessons}
              color="text-blue-300"
            />
          )}

          {report.blind_spots && (
            <ReportSection
              icon={AlertTriangle}
              title="Angles morts du scoring"
              content={report.blind_spots}
              color="text-yellow-300"
            />
          )}

          {report.next_cycle_priorities && (
            <ReportSection
              icon={Target}
              title="Priorités prochain cycle"
              content={report.next_cycle_priorities}
              color="text-purple-300"
            />
          )}

          {report.risk_watch && (
            <ReportSection
              icon={AlertTriangle}
              title="Risques à surveiller"
              content={report.risk_watch}
              color="text-orange-300"
            />
          )}
        </div>
      )}

      {/* Top movers */}
      {(winners.length > 0 || losers.length > 0) && (
        <div className="grid grid-cols-2 gap-6">
          {/* Winners */}
          <div className="space-y-3">
            <h2 className="text-sm font-semibold text-emerald-400 uppercase tracking-wide flex items-center gap-2">
              <TrendingUp className="w-4 h-4" /> Top Gains
            </h2>
            {winners.length === 0 ? (
              <div className="card text-center py-8 text-slate-600 text-sm">Aucun trade pricé</div>
            ) : (
              winners.map((t: any, i: number) => (
                <MoverCard key={t.id ?? i} trade={t} rank={i + 1} type="winner" />
              ))
            )}
          </div>

          {/* Losers */}
          <div className="space-y-3">
            <h2 className="text-sm font-semibold text-red-400 uppercase tracking-wide flex items-center gap-2">
              <TrendingDown className="w-4 h-4" /> Top Pertes
            </h2>
            {losers.length === 0 ? (
              <div className="card text-center py-8 text-slate-600 text-sm">Aucun trade pricé</div>
            ) : (
              losers.map((t: any, i: number) => (
                <MoverCard key={t.id ?? i} trade={t} rank={i + 1} type="loser" />
              ))
            )}
          </div>
        </div>
      )}

      {!loadingRaw && !raw && !report && (
        <div className="card text-center py-16 text-slate-600">
          <Brain className="w-12 h-12 mx-auto mb-3 opacity-20" />
          <p className="text-sm">Cliquer "Générer rapport IA" pour lancer l'analyse GPT-4o</p>
          <p className="text-xs mt-1 text-slate-700">
            Le rapport compare les trades gagnants et perdants, identifie les patterns récurrents
            et génère des recommandations pour le prochain cycle.
          </p>
        </div>
      )}
      </div>
    </div>
  )
}
