import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useInstitutionalReports, useInstitutionalStats, useRefreshInstitutionalReports } from '../hooks/useApi'
import { useQueryClient } from '@tanstack/react-query'
import { RefreshCw, TrendingUp, TrendingDown, Minus, AlertTriangle, Star, CheckCircle, Clock, Users, ExternalLink } from 'lucide-react'
import clsx from 'clsx'
import { format } from 'date-fns'

interface InstitutionalReport {
  id: number
  report_type: string
  report_date: string
  fetch_date: string
  title: string
  source: string
  importance: number
  category: string
  key_points: string[]
  trading_implications: string
  signal_energy: string
  signal_metals: string
  signal_indices: string
  signal_forex: string
  ai_summary: string
  absorbed_score: number | null
  injected_in_cycle_id: string | null
}

const SIGNAL_CONFIG: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
  bullish:  { label: 'Bullish',  color: 'text-emerald-400 bg-emerald-900/30 border-emerald-700/40', icon: <TrendingUp className="w-3 h-3" /> },
  bearish:  { label: 'Bearish',  color: 'text-red-400 bg-red-900/30 border-red-700/40',           icon: <TrendingDown className="w-3 h-3" /> },
  neutral:  { label: 'Neutral',  color: 'text-slate-400 bg-slate-800/50 border-slate-700/40',      icon: <Minus className="w-3 h-3" /> },
}

const ASSET_CLASSES = ['energy', 'metals', 'indices', 'forex'] as const

function SignalBadge({ signal, label }: { signal: string; label: string }) {
  const cfg = SIGNAL_CONFIG[signal] ?? SIGNAL_CONFIG.neutral
  return (
    <span className={clsx('inline-flex items-center gap-1 px-1.5 py-0.5 rounded border text-xs font-medium', cfg.color)}>
      {cfg.icon}
      <span className="text-slate-400 mr-0.5">{label}:</span>
      {cfg.label}
    </span>
  )
}

function ImportanceStars({ n }: { n: number }) {
  return (
    <span className="flex items-center gap-0.5">
      {[1, 2, 3].map(i => (
        <Star
          key={i}
          className={clsx('w-3 h-3', i <= n ? 'text-amber-400 fill-amber-400' : 'text-slate-700')}
        />
      ))}
    </span>
  )
}

function AbsorptionBadge({ score }: { score: number | null }) {
  if (score === null || score === undefined) {
    return (
      <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-slate-700/40 bg-slate-800/50 text-slate-500 text-xs">
        <Clock className="w-3 h-3" />
        Not absorbed
      </span>
    )
  }
  const pct = Math.round(score * 100)
  const isAbsorbed = pct >= 30
  return (
    <span className={clsx(
      'inline-flex items-center gap-1 px-1.5 py-0.5 rounded border text-xs font-medium',
      isAbsorbed
        ? 'text-blue-400 bg-blue-900/30 border-blue-700/40'
        : 'text-slate-500 bg-slate-800/50 border-slate-700/40'
    )}>
      <CheckCircle className="w-3 h-3" />
      {isAbsorbed ? `Absorbed ${pct}%` : `Low ${pct}%`}
    </span>
  )
}

const TYPE_COLORS: Record<string, string> = {
  cot:          'bg-purple-900/30 text-purple-300 border-purple-700/40',
  eia:          'bg-orange-900/30 text-orange-300 border-orange-700/40',
  earnings:     'bg-blue-900/30 text-blue-300 border-blue-700/40',
  vx_curve:     'bg-rose-900/30 text-rose-300 border-rose-700/40',
  central_bank: 'bg-cyan-900/30 text-cyan-300 border-cyan-700/40',
  sentiment:    'bg-yellow-900/30 text-yellow-300 border-yellow-700/40',
}

const TYPE_LABELS: Record<string, string> = {
  cot:          'COT',
  eia:          'EIA',
  earnings:     'Earnings',
  vx_curve:     'VX Curve',
  central_bank: 'Central Banks',
  sentiment:    'Sentiment',
}

function ReportCard({ report }: { report: InstitutionalReport }) {
  const [expanded, setExpanded] = useState(false)
  const typeColor = TYPE_COLORS[report.report_type] ?? 'bg-slate-800 text-slate-400 border-slate-700/40'

  return (
    <div className="bg-dark-800 border border-slate-700/40 rounded-lg overflow-hidden hover:border-slate-600/60 transition-colors">
      {/* Header */}
      <div className="p-4 flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap mb-1.5">
            <span className={clsx('px-2 py-0.5 rounded border text-xs font-bold uppercase tracking-wider', typeColor)}>
              {TYPE_LABELS[report.report_type] ?? report.report_type}
            </span>
            <ImportanceStars n={report.importance} />
            <span className="text-slate-500 text-xs">
              {report.report_date}
            </span>
            <AbsorptionBadge score={report.absorbed_score} />
          </div>
          <div className="text-white font-medium text-sm truncate">{report.title}</div>
          <div className="text-slate-500 text-xs mt-0.5">{report.source}</div>
        </div>
        <button
          onClick={() => setExpanded(e => !e)}
          className="text-xs text-slate-400 hover:text-white shrink-0 border border-slate-700/40 rounded px-2 py-1"
        >
          {expanded ? 'Collapse' : 'Expand'}
        </button>
      </div>

      {/* Signal badges row */}
      <div className="px-4 pb-3 flex flex-wrap gap-1.5">
        <SignalBadge signal={report.signal_energy}  label="Energy" />
        <SignalBadge signal={report.signal_metals}  label="Metals" />
        <SignalBadge signal={report.signal_indices} label="Indices" />
        <SignalBadge signal={report.signal_forex}   label="Forex" />
      </div>

      {/* Key points preview (always visible) */}
      {report.key_points?.length > 0 && (
        <div className="px-4 pb-3">
          <ul className="space-y-1">
            {(expanded ? report.key_points : report.key_points.slice(0, 3)).map((kp, i) => {
              const isExtreme = kp.includes('EXTREME')
              return (
                <li key={i} className={clsx(
                  'text-xs flex items-start gap-1.5',
                  isExtreme ? 'text-amber-300' : 'text-slate-300'
                )}>
                  {isExtreme
                    ? <AlertTriangle className="w-3 h-3 text-amber-400 shrink-0 mt-0.5" />
                    : <span className="w-3 text-center text-slate-600 shrink-0">•</span>
                  }
                  {kp}
                </li>
              )
            })}
            {!expanded && report.key_points.length > 3 && (
              <li className="text-xs text-slate-600">+{report.key_points.length - 3} more…</li>
            )}
          </ul>
        </div>
      )}

      {/* Expanded: trading implications + AI summary */}
      {expanded && (
        <div className="border-t border-slate-700/40 p-4 space-y-3">
          {report.trading_implications && (
            <div>
              <div className="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">
                Trading Implications
              </div>
              <div className="bg-amber-900/10 border border-amber-700/30 rounded p-2.5">
                {report.trading_implications.split(' | ').map((impl, i) => (
                  <p key={i} className="text-xs text-amber-200 leading-relaxed">{impl}</p>
                ))}
              </div>
            </div>
          )}
          {report.ai_summary && (
            <div>
              <div className="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-1.5">
                AI Summary
              </div>
              <p className="text-xs text-slate-400 leading-relaxed">{report.ai_summary}</p>
            </div>
          )}
          {report.injected_in_cycle_id && (
            <div className="text-xs text-slate-600">
              Injected in cycle: <span className="font-mono">{report.injected_in_cycle_id.slice(0, 16)}</span>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default function InstitutionalReports() {
  const qc = useQueryClient()
  const [filterType, setFilterType]         = useState<string>('')
  const [filterCategory, setFilterCategory] = useState<string>('')
  const [filterImportance, setFilterImportance] = useState<number>(0)
  const [filterDays, setFilterDays]         = useState<number>(90)

  const params = {
    ...(filterType       ? { report_type: filterType }    : {}),
    ...(filterCategory   ? { category: filterCategory }  : {}),
    ...(filterImportance ? { importance: filterImportance } : {}),
    days: filterDays,
  }

  const { data: reports = [], isLoading, isFetching } = useInstitutionalReports(params)
  const { data: stats } = useInstitutionalStats()
  const refresh = useRefreshInstitutionalReports()

  const handleRefresh = (type?: string) => {
    refresh.mutate(type, {
      onSuccess: () => {
        qc.invalidateQueries({ queryKey: ['institutional-reports'] })
        qc.invalidateQueries({ queryKey: ['institutional-stats'] })
      },
    })
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-xl font-bold text-white">Institutional Reports</h1>
          <p className="text-slate-400 text-sm mt-0.5">
            COT · EIA · Earnings · VX Curve · Central Banks · Sentiment — scheduled daily/weekly
          </p>
        </div>
        <div className="flex flex-wrap gap-1.5">
          {([
            { type: 'cot',          label: 'COT',     cls: 'bg-purple-900/40 text-purple-300 border-purple-700/40 hover:bg-purple-800/50' },
            { type: 'eia',          label: 'EIA',     cls: 'bg-orange-900/40 text-orange-300 border-orange-700/40 hover:bg-orange-800/50' },
            { type: 'earnings',     label: 'Earn.',   cls: 'bg-blue-900/40 text-blue-300 border-blue-700/40 hover:bg-blue-800/50' },
            { type: 'vx_curve',     label: 'VX',      cls: 'bg-rose-900/40 text-rose-300 border-rose-700/40 hover:bg-rose-800/50' },
            { type: 'central_bank', label: 'CB RSS',  cls: 'bg-cyan-900/40 text-cyan-300 border-cyan-700/40 hover:bg-cyan-800/50' },
            { type: 'sentiment',    label: 'Senti.',  cls: 'bg-yellow-900/40 text-yellow-300 border-yellow-700/40 hover:bg-yellow-800/50' },
          ] as const).map(({ type, label, cls }) => (
            <button
              key={type}
              onClick={() => handleRefresh(type)}
              disabled={refresh.isPending}
              className={clsx('flex items-center gap-1 px-2.5 py-1.5 text-xs border rounded disabled:opacity-50', cls)}
            >
              <RefreshCw className={clsx('w-3 h-3', refresh.isPending && 'animate-spin')} />
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Stats bar */}
      {stats && (
        <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
          {[
            { label: 'COT',          value: stats.by_type?.cot ?? 0,          cls: 'text-purple-400' },
            { label: 'EIA',          value: stats.by_type?.eia ?? 0,          cls: 'text-orange-400' },
            { label: 'Earnings',     value: stats.by_type?.earnings ?? 0,     cls: 'text-blue-400' },
            { label: 'VX Curve',     value: stats.by_type?.vx_curve ?? 0,     cls: 'text-rose-400' },
            { label: 'Central Bank', value: stats.by_type?.central_bank ?? 0, cls: 'text-cyan-400' },
            { label: 'Sentiment',    value: stats.by_type?.sentiment ?? 0,    cls: 'text-yellow-400' },
          ].map(({ label, value, cls }) => (
            <div key={label} className="bg-dark-800 border border-slate-700/40 rounded p-3 text-center">
              <div className={clsx('text-xl font-bold', cls)}>{value}</div>
              <div className="text-xs text-slate-500 mt-0.5">{label}</div>
            </div>
          ))}
        </div>
      )}

      {/* Latest dates */}
      {stats && (
        <div className="flex flex-wrap gap-4 text-xs text-slate-500">
          {stats.latest_cot         && <span>COT: <span className="text-purple-400">{stats.latest_cot}</span></span>}
          {stats.latest_eia         && <span>EIA: <span className="text-orange-400">{stats.latest_eia}</span></span>}
          {stats.by_type?.earnings  ? <span>Earnings: <span className="text-blue-400">{Object.keys(stats.by_type).includes('earnings') ? 'tracked' : ''}</span></span> : null}
          <span className="text-slate-600">Total: {stats.total} · Absorbed: {stats.absorbed_count}</span>
        </div>
      )}

      {/* Specialist Desks link */}
      <div className="flex items-center gap-3 bg-indigo-900/20 border border-indigo-700/40 rounded-lg px-4 py-2.5 text-xs text-indigo-300">
        <Users className="w-3.5 h-3.5 shrink-0 text-indigo-400" />
        <span className="flex-1">
          Ces rapports sont <strong>analysés automatiquement</strong> (fetch + scoring IA). Pour gérer le <strong>calendrier des rapports par desk</strong> — ajouter un rapport custom (ex. broyage cacao), planifier les prochaines dates, lier à un desk specialist —
        </span>
        <Link
          to="/specialist-desks"
          className="flex items-center gap-1 bg-indigo-700/40 hover:bg-indigo-600/50 border border-indigo-600/50 rounded px-2.5 py-1 font-medium text-indigo-200 transition-colors shrink-0"
        >
          <ExternalLink className="w-3 h-3" />
          Specialist Desks
        </Link>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 bg-dark-800 border border-slate-700/40 rounded-lg p-3">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-xs text-slate-500">Type:</span>
          <div className="flex flex-wrap gap-1">
            {(['', 'cot', 'eia', 'earnings', 'vx_curve', 'central_bank', 'sentiment'] as const).map(t => (
              <button
                key={t}
                onClick={() => setFilterType(t)}
                className={clsx(
                  'px-2.5 py-1 rounded text-xs font-medium border transition-colors',
                  filterType === t
                    ? 'bg-blue-600 text-white border-blue-500'
                    : 'bg-dark-700 text-slate-400 border-slate-700/40 hover:border-slate-600'
                )}
              >
                {t === '' ? 'All' : (TYPE_LABELS[t] ?? t)}
              </button>
            ))}
          </div>
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-xs text-slate-500">Category:</span>
          <div className="flex flex-wrap gap-1">
            {([
              { v: '',          label: 'All'      },
              { v: 'energy',    label: 'Energy'   },
              { v: 'metals',    label: 'Metals'   },
              { v: 'agri',      label: 'Agri'     },
              { v: 'equities',  label: 'Equities' },
              { v: 'forex',     label: 'Forex'    },
              { v: 'crypto',    label: 'Crypto'   },
              { v: 'bonds',     label: 'Bonds'    },
              { v: 'volatility',label: 'Volatility'},
              { v: 'macro',     label: 'Macro'    },
              { v: 'sentiment', label: 'Sentiment'},
              { v: 'multi',     label: 'Multi'    },
            ]).map(({ v, label }) => (
              <button
                key={v}
                onClick={() => setFilterCategory(v)}
                className={clsx(
                  'px-2.5 py-1 rounded text-xs font-medium border transition-colors',
                  filterCategory === v
                    ? 'bg-blue-600 text-white border-blue-500'
                    : 'bg-dark-700 text-slate-400 border-slate-700/40 hover:border-slate-600'
                )}
              >
                {label}
              </button>
            ))}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <span className="text-xs text-slate-500">Min importance:</span>
          <div className="flex gap-1">
            {[0, 1, 2, 3].map(n => (
              <button
                key={n}
                onClick={() => setFilterImportance(n)}
                className={clsx(
                  'px-2.5 py-1 rounded text-xs font-medium border transition-colors',
                  filterImportance === n
                    ? 'bg-blue-600 text-white border-blue-500'
                    : 'bg-dark-700 text-slate-400 border-slate-700/40 hover:border-slate-600'
                )}
              >
                {n === 0 ? 'Any' : '★'.repeat(n)}
              </button>
            ))}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <span className="text-xs text-slate-500">Period:</span>
          <select
            value={filterDays}
            onChange={e => setFilterDays(Number(e.target.value))}
            className="bg-dark-700 border border-slate-700/40 text-slate-300 text-xs rounded px-2 py-1"
          >
            {[30, 60, 90, 180, 365].map(d => (
              <option key={d} value={d}>{d}d</option>
            ))}
          </select>
        </div>
      </div>

      {/* Report list */}
      {isLoading || isFetching ? (
        <div className="text-center py-12 text-slate-500">
          <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
          Loading reports…
        </div>
      ) : reports.length === 0 ? (
        <div className="text-center py-16 space-y-3">
          <div className="text-slate-600 text-4xl">📋</div>
          <div className="text-slate-400 font-medium">No institutional reports yet</div>
          <p className="text-slate-600 text-sm max-w-sm mx-auto">
            Use the refresh buttons above to fetch reports. COT and EIA require API keys.
            Earnings, VX, Central Bank RSS, and Sentiment fetch automatically.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          <div className="text-xs text-slate-500">{reports.length} report{reports.length > 1 ? 's' : ''}</div>
          {(reports as InstitutionalReport[]).map(r => (
            <ReportCard key={r.id} report={r} />
          ))}
        </div>
      )}
    </div>
  )
}
