import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { RefreshCw, Bot, Clock } from 'lucide-react'
import api from '../api'

interface AIInsight {
  id: number
  generated_at: string
  content: string
  model: string
  input_tokens: number
  output_tokens: number
  triggered_by: string
}

function formatAge(iso: string): string {
  const ms = Date.now() - new Date(iso).getTime()
  const mins = Math.floor(ms / 60000)
  if (mins < 1) return 'just now'
  if (mins < 60) return `${mins}m ago`
  const hours = Math.floor(mins / 60)
  if (hours < 24) return `${hours}h ago`
  return `${Math.floor(hours / 24)}d ago`
}

function escHtml(s: string): string {
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
}

function renderContent(text: string) {
  return text.split('\n').map((line, i) => {
    const safe = escHtml(line)
    const processed = safe.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    if (line.startsWith('- ') || line.startsWith('* ')) {
      return (
        <div key={i} style={{ display: 'flex', gap: 8, marginBottom: 4 }}>
          <span style={{ color: 'var(--gold)', flexShrink: 0 }}>•</span>
          <span dangerouslySetInnerHTML={{ __html: processed.slice(2) }} />
        </div>
      )
    }
    if (line.startsWith('## ') || line.startsWith('# ')) {
      const txt = line.replace(/^#+\s*/, '')
      return <p key={i} style={{ fontWeight: 600, marginTop: 12, marginBottom: 6, color: 'var(--text-dark)' }}>{txt}</p>
    }
    if (line.trim() === '') return <div key={i} style={{ height: 8 }} />
    return <p key={i} style={{ marginBottom: 4 }} dangerouslySetInnerHTML={{ __html: processed }} />
  })
}

export default function Dashboard() {
  const qc = useQueryClient()
  const [genError, setGenError] = useState<string | null>(null)

  const { data: insight, isLoading } = useQuery<AIInsight | null>({
    queryKey: ['ai-insights-latest'],
    queryFn: () => api.get('/ai-insights/latest').then(r => r.data),
    refetchInterval: 5 * 60_000,
  })

  const generate = useMutation({
    mutationFn: () => api.post('/ai-insights/generate').then(r => r.data),
    onSuccess: () => {
      setGenError(null)
      qc.invalidateQueries({ queryKey: ['ai-insights-latest'] })
    },
    onError: (err: any) => {
      setGenError(err.response?.data?.detail || 'Failed to generate insight')
    },
  })

  return (
    <div>
      <div className="page-header">
        <div>
          <div className="page-title">Dashboard</div>
          <div className="page-subtitle">Daily AI-generated forecast summary</div>
        </div>
        <button
          className="btn btn-primary"
          onClick={() => generate.mutate()}
          disabled={generate.isPending}
        >
          <RefreshCw size={14} strokeWidth={1.75} />
          {generate.isPending ? 'Generating…' : 'Generate Now'}
        </button>
      </div>

      {genError && (
        <div style={{ background: '#fee2e2', border: '1px solid #fca5a5', borderRadius: 8, padding: '10px 14px', marginBottom: 16, color: '#dc2626', fontSize: 13 }}>
          {genError}
        </div>
      )}

      <div className="card">
        <div className="card-header">
          <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Bot size={16} strokeWidth={1.75} color="var(--gold)" />
            AI Insight
          </span>
          {insight && (
            <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--text-mid)', fontWeight: 400 }}>
              <Clock size={12} strokeWidth={1.75} />
              {formatAge(insight.generated_at)}
              {insight.model && <span style={{ marginLeft: 6, background: '#f1f5f9', borderRadius: 4, padding: '1px 6px' }}>{insight.model}</span>}
            </span>
          )}
        </div>
        <div className="card-body" style={{ fontSize: 13.5, lineHeight: 1.65, color: 'var(--text-dark)' }}>
          {isLoading && (
            <div className="loading-state">
              <div className="spinner" />
              Loading insight…
            </div>
          )}
          {!isLoading && !insight && (
            <div className="empty-state">
              <Bot size={32} strokeWidth={1.75} color="var(--text-mid)" style={{ margin: '0 auto 12px' }} />
              <p>No insight generated yet.</p>
              <p style={{ marginTop: 6 }}>Click <strong>Generate Now</strong> to produce a daily summary.</p>
            </div>
          )}
          {insight && (
            <>
              <div style={{ marginBottom: 16 }}>{renderContent(insight.content)}</div>
              {(insight.input_tokens || insight.output_tokens) && (
                <div style={{ fontSize: 11, color: 'var(--text-mid)', marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--card-border)' }}>
                  {insight.input_tokens}↑ / {insight.output_tokens}↓ tokens
                  · {insight.triggered_by}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
