import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import Plot from 'react-plotly.js'
import { TrendingUp, TrendingDown, Minus, AlertTriangle, ChevronDown } from 'lucide-react'
import api from '../api'

const fmtDate = (d: Date) =>
  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`

interface AnalysisHotel {
  hotel_id: number
  hotel_name: string
  last_scraped: string | null
  date_count: number
}

interface StrategyLabel {
  label: string
  advance_discount_pct: number
  weekend_premium_pct: number
  avg_sold_out_rate_pct: number
  peak_months: string[]
}

interface HotelAnalysis {
  strategy: StrategyLabel
  advance_curve: { days_ahead: number; avg_price: number; sample_count: number }[]
  dow_breakdown: { dow: number; dow_name: string; avg_price: number; count: number }[]
  sold_out_pattern: { stay_date: string; sold_out_pct: number }[]
}

interface TimelineEntry {
  scraped_at: string
  room_id: string
  rate_id: string
  room_label: string
  rate_label: string
  price_incl: number | null
  availability: number
}

interface ComparisonRow {
  hotel_id: number
  hotel_name: string
  our_rate: number | null
  their_rate: number | null
  price_index: number | null
  days_checked: number
}

const DOW = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
const PLOT_LAYOUT_BASE = {
  paper_bgcolor: 'transparent',
  plot_bgcolor: 'transparent',
  font: { family: 'Inter, system-ui, sans-serif', size: 12, color: '#60748b' },
  margin: { t: 20, r: 16, b: 48, l: 48 },
  showlegend: false,
  xaxis: { gridcolor: '#e5e9f0', zeroline: false },
  yaxis: { gridcolor: '#e5e9f0', zeroline: false },
}

function strategyIcon(label: string) {
  if (label.includes('Discount')) return <TrendingDown size={16} strokeWidth={1.75} color="var(--warning)" />
  if (label.includes('Premium')) return <TrendingUp size={16} strokeWidth={1.75} color="var(--success)" />
  if (label.includes('Yield')) return <TrendingUp size={16} strokeWidth={1.75} color="var(--gold)" />
  return <Minus size={16} strokeWidth={1.75} color="var(--text-mid)" />
}

function priceIndexClass(idx: number | null) {
  if (idx == null) return 'badge badge-neutral'
  if (idx > 105) return 'badge badge-success'
  if (idx < 85) return 'badge badge-danger'
  if (idx < 95) return 'badge badge-warning'
  return 'badge badge-neutral'
}

export default function RateAnalysis() {
  const [selectedHotel, setSelectedHotel] = useState<number | null>(null)
  const [timelineDate, setTimelineDate] = useState(fmtDate(new Date(Date.now() + 30 * 86400000)))
  const [compFrom, setCompFrom] = useState(fmtDate(new Date()))
  const [compTo, setCompTo] = useState(fmtDate(new Date(Date.now() + 29 * 86400000)))

  const { data: hotels } = useQuery<AnalysisHotel[]>({
    queryKey: ['analysis-hotels'],
    queryFn: () => api.get('/analysis/hotels').then(r => r.data),
  })

  const { data: analysis, isLoading: analysisLoading } = useQuery<HotelAnalysis>({
    queryKey: ['analysis-hotel', selectedHotel],
    queryFn: () => api.get(`/analysis/hotel/${selectedHotel}`).then(r => r.data),
    enabled: !!selectedHotel,
  })

  const { data: timeline } = useQuery<TimelineEntry[]>({
    queryKey: ['analysis-timeline', selectedHotel, timelineDate],
    queryFn: () => api.get(`/analysis/hotel/${selectedHotel}/timeline`, {
      params: { date: timelineDate }
    }).then(r => r.data),
    enabled: !!selectedHotel,
  })

  const { data: comparison, isLoading: compLoading } = useQuery<ComparisonRow[]>({
    queryKey: ['analysis-comparison', compFrom, compTo],
    queryFn: () => api.get('/analysis/comparison', {
      params: { from_date: compFrom, to_date: compTo }
    }).then(r => r.data),
    enabled: !!(compFrom && compTo),
  })

  const presets = [
    { label: '7d', days: 7 }, { label: '14d', days: 14 },
    { label: '30d', days: 30 },
  ]

  return (
    <div>
      <div className="page-header">
        <div>
          <div className="page-title">Rate Analysis</div>
          <div className="page-subtitle">Competitor pricing structure and advance purchase behaviour</div>
        </div>
      </div>

      {/* Comparison table — full width, no hotel needed */}
      <section style={{ marginBottom: 24 }}>
        <div className="card">
          <div className="card-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>Market Comparison</span>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              {presets.map(p => (
                <button key={p.label} className="btn btn-outline btn-sm"
                  onClick={() => { setCompFrom(fmtDate(new Date())); setCompTo(fmtDate(new Date(Date.now() + p.days * 86400000))) }}>
                  {p.label}
                </button>
              ))}
              <input type="date" style={{ width: 130 }} value={compFrom} onChange={e => setCompFrom(e.target.value)} />
              <span style={{ color: 'var(--text-mid)', fontSize: 12 }}>to</span>
              <input type="date" style={{ width: 130 }} value={compTo} onChange={e => setCompTo(e.target.value)} />
            </div>
          </div>
          {compLoading ? (
            <div className="loading-state"><div className="spinner" />Loading…</div>
          ) : (
            <div className="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Competitor</th>
                    <th>Our Avg Rate</th>
                    <th>Their Avg Rate</th>
                    <th>Price Index</th>
                    <th>Dates Checked</th>
                  </tr>
                </thead>
                <tbody>
                  {(comparison || []).length === 0 && (
                    <tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--text-mid)', padding: 24 }}>No comparison data available.</td></tr>
                  )}
                  {(comparison || []).map(row => (
                    <tr key={row.hotel_id}>
                      <td>
                        <button onClick={() => setSelectedHotel(row.hotel_id)}
                          style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--gold)', fontWeight: 600, padding: 0, fontSize: 13 }}>
                          {row.hotel_name}
                        </button>
                      </td>
                      <td>{row.our_rate ? `£${Number(row.our_rate).toFixed(2)}` : '—'}</td>
                      <td style={{ fontWeight: 600 }}>{row.their_rate ? `£${Number(row.their_rate).toFixed(2)}` : '—'}</td>
                      <td>
                        {row.price_index != null ? (
                          <span className={priceIndexClass(row.price_index)}>
                            {row.price_index.toFixed(0)}
                          </span>
                        ) : '—'}
                      </td>
                      <td style={{ color: 'var(--text-mid)' }}>{row.days_checked}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </section>

      {/* Hotel selector for deep analysis */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end' }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-mid)', display: 'block', marginBottom: 4 }}>
              Competitor — deep analysis
            </label>
            <select style={{ width: 260 }} value={selectedHotel || ''}
              onChange={e => setSelectedHotel(e.target.value ? parseInt(e.target.value) : null)}>
              <option value="">Select a competitor…</option>
              {(hotels || []).map(h => (
                <option key={h.hotel_id} value={h.hotel_id}>{h.hotel_name}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {selectedHotel && analysisLoading && (
        <div className="loading-state"><div className="spinner" />Loading analysis…</div>
      )}

      {selectedHotel && !analysisLoading && analysis && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Strategy card */}
          <div className="card">
            <div className="card-header">Pricing Strategy</div>
            <div className="card-body" style={{ display: 'flex', gap: 32, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                {strategyIcon(analysis.strategy.label)}
                <span style={{ fontWeight: 700, fontSize: 15 }}>{analysis.strategy.label}</span>
              </div>
              <StatChip label="Advance Discount" value={`${analysis.strategy.advance_discount_pct.toFixed(1)}%`}
                hint="price delta from 90→7 days ahead" />
              <StatChip label="Weekend Premium" value={`${analysis.strategy.weekend_premium_pct.toFixed(1)}%`}
                hint="Fri-Sun vs Mon-Thu" />
              <StatChip label="Sold-Out Rate" value={`${analysis.strategy.avg_sold_out_rate_pct.toFixed(1)}%`}
                hint="% of scraped dates with no availability" />
              {analysis.strategy.peak_months.length > 0 && (
                <StatChip label="Peak Months" value={analysis.strategy.peak_months.join(', ')} hint="" />
              )}
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
            {/* Advance purchase curve */}
            <div className="card">
              <div className="card-header">Advance Purchase Curve</div>
              <div className="card-body" style={{ height: 260 }}>
                {analysis.advance_curve.length > 0 ? (
                  <Plot
                    style={{ width: '100%', height: '100%' }}
                    data={[{
                      type: 'scatter',
                      mode: 'lines+markers',
                      x: analysis.advance_curve.map(p => p.days_ahead),
                      y: analysis.advance_curve.map(p => p.avg_price),
                      line: { color: '#c9a84c', width: 2 },
                      marker: { size: 4, color: '#c9a84c' },
                      hovertemplate: '%{x} days ahead: £%{y:.2f}<extra></extra>',
                    }]}
                    layout={{
                      ...PLOT_LAYOUT_BASE,
                      xaxis: { ...PLOT_LAYOUT_BASE.xaxis, title: { text: 'Days ahead', font: { size: 11 } }, autorange: 'reversed' },
                      yaxis: { ...PLOT_LAYOUT_BASE.yaxis, title: { text: 'Avg price (£)', font: { size: 11 } }, tickprefix: '£' },
                    }}
                    config={{ displayModeBar: false, responsive: true }}
                    useResizeHandler
                  />
                ) : (
                  <div className="empty-state">Not enough data yet.</div>
                )}
              </div>
            </div>

            {/* DOW breakdown */}
            <div className="card">
              <div className="card-header">Day-of-Week Breakdown</div>
              <div className="card-body" style={{ height: 260 }}>
                {analysis.dow_breakdown.length > 0 ? (
                  <Plot
                    style={{ width: '100%', height: '100%' }}
                    data={[{
                      type: 'bar',
                      x: analysis.dow_breakdown.map(d => d.dow_name),
                      y: analysis.dow_breakdown.map(d => d.avg_price),
                      marker: {
                        color: analysis.dow_breakdown.map(d =>
                          d.dow >= 5 ? '#c9a84c' : '#3b82f6'
                        ),
                      },
                      hovertemplate: '%{x}: £%{y:.2f}<extra></extra>',
                    }]}
                    layout={{
                      ...PLOT_LAYOUT_BASE,
                      yaxis: { ...PLOT_LAYOUT_BASE.yaxis, tickprefix: '£' },
                    }}
                    config={{ displayModeBar: false, responsive: true }}
                    useResizeHandler
                  />
                ) : (
                  <div className="empty-state">Not enough data yet.</div>
                )}
              </div>
            </div>
          </div>

          {/* Rate timeline */}
          <div className="card">
            <div className="card-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>Rate Timeline — How Rates Changed for One Date</span>
              <input type="date" style={{ width: 140 }} value={timelineDate}
                onChange={e => setTimelineDate(e.target.value)} />
            </div>
            <div className="card-body" style={{ height: 280 }}>
              {(timeline || []).length === 0 ? (
                <div className="empty-state">No timeline data for this date.</div>
              ) : (
                <Plot
                  style={{ width: '100%', height: '100%' }}
                  data={buildTimelineTraces(timeline || [])}
                  layout={{
                    ...PLOT_LAYOUT_BASE,
                    showlegend: true,
                    legend: { font: { size: 11 }, bgcolor: 'transparent' },
                    margin: { t: 20, r: 120, b: 48, l: 56 },
                    xaxis: { ...PLOT_LAYOUT_BASE.xaxis },
                    yaxis: { ...PLOT_LAYOUT_BASE.yaxis, tickprefix: '£' },
                  }}
                  config={{ displayModeBar: false, responsive: true }}
                  useResizeHandler
                />
              )}
            </div>
          </div>
        </div>
      )}

      {!selectedHotel && (
        <div className="empty-state" style={{ marginTop: 0 }}>
          Select a competitor above to view their pricing strategy and advance purchase curve.
        </div>
      )}
    </div>
  )
}

function StatChip({ label, value, hint }: { label: string; value: string; hint: string }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <span style={{ fontSize: 11, color: 'var(--text-mid)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</span>
      <span style={{ fontSize: 18, fontWeight: 700, color: 'var(--text-dark)', lineHeight: 1 }}>{value}</span>
      {hint && <span style={{ fontSize: 11, color: 'var(--text-mid)' }}>{hint}</span>}
    </div>
  )
}

function buildTimelineTraces(entries: TimelineEntry[]) {
  const byRoom: Record<string, TimelineEntry[]> = {}
  for (const e of entries) {
    const key = e.room_label || e.room_id
    if (!byRoom[key]) byRoom[key] = []
    byRoom[key].push(e)
  }

  const colors = ['#c9a84c', '#3b82f6', '#10b981', '#ef4444', '#8b5cf6', '#f59e0b']
  return Object.entries(byRoom).map(([room, pts], i) => ({
    type: 'scatter' as const,
    mode: 'lines+markers' as const,
    name: room,
    x: pts.map(p => p.scraped_at),
    y: pts.map(p => p.price_incl ?? null),
    line: { color: colors[i % colors.length], width: 2 },
    marker: { size: 5, color: colors[i % colors.length] },
    hovertemplate: `${room}: £%{y:.2f}<extra></extra>`,
  }))
}
