import { useState, useEffect, useRef, useCallback } from 'react'
import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send, ChevronDown, ChevronUp } from 'lucide-react'
import { summariesApi, type Summary } from '@/api/summaries'
import { reportsApi } from '@/api/reports'
import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Markdown } from '@/components/ui/markdown'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth'

// ── Text-selection floating button ─────────────────────────────────────────

function useTextSelection(containerRef: React.RefObject<HTMLElement>) {
  const [selection, setSelection] = useState<{ text: string; x: number; y: number } | null>(null)

  useEffect(() => {
    function readSelection() {
      const sel = window.getSelection()
      const text = sel?.toString().trim()
      if (!text || !containerRef.current) { setSelection(null); return }
      const range = sel!.getRangeAt(0)
      const rect = range.getBoundingClientRect()
      const containerRect = containerRef.current.getBoundingClientRect()
      setSelection({
        text,
        x: rect.left - containerRect.left + rect.width / 2,
        y: rect.top - containerRect.top - 8,
      })
    }
    function onMouseUp() { readSelection() }
    // On mobile, selectionchange fires after the user lifts their finger
    function onSelectionChange() {
      const sel = window.getSelection()
      if (!sel?.toString().trim()) setSelection(null)
      else readSelection()
    }
    function onPointerDown(e: PointerEvent) {
      if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
    }
    document.addEventListener('mouseup', onMouseUp)
    document.addEventListener('selectionchange', onSelectionChange)
    document.addEventListener('pointerdown', onPointerDown)
    return () => {
      document.removeEventListener('mouseup', onMouseUp)
      document.removeEventListener('selectionchange', onSelectionChange)
      document.removeEventListener('pointerdown', onPointerDown)
    }
  }, [containerRef])

  return selection
}

// ── Context panel (extraits + question) ────────────────────────────────────

function ContextPanel({
  excerpts,
  onRemove,
  onClear,
  onSubmit,
}: {
  excerpts: string[]
  onRemove: (i: number) => void
  onClear: () => void
  onSubmit: (question: string) => Promise<void>
}) {
  const [question, setQuestion] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [showExcerpts, setShowExcerpts] = useState(false)

  async function submit() {
    if (!question.trim() || submitting) return
    setSubmitting(true)
    try {
      await onSubmit(question)
      setSubmitted(true)
      setQuestion('')
      setTimeout(() => setSubmitted(false), 2000)
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="fixed bottom-16 left-0 right-0 z-40 flex flex-col bg-card border-t shadow-2xl overflow-hidden md:bottom-4 md:left-auto md:right-4 md:w-96 md:rounded-xl md:border">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
        <button
          className="text-sm font-semibold flex items-center gap-2 hover:text-primary transition-colors"
          onClick={() => setShowExcerpts(v => !v)}
        >
          <MessageSquarePlus className="h-4 w-4 text-primary" />
          Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
          <span className="md:hidden">{showExcerpts ? <ChevronDown className="h-3 w-3" /> : <ChevronUp className="h-3 w-3" />}</span>
        </button>
        <button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
          Tout effacer
        </button>
      </div>

      {/* Extraits — toujours visible sur desktop, togglable sur mobile */}
      <div className={`flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0 max-h-[25vh] ${showExcerpts ? 'block' : 'hidden'} md:block`}>
          {excerpts.map((e, i) => (
            <div key={i} className="flex items-start gap-2 group">
              <div className="flex-1 rounded bg-muted/60 px-2 py-1.5 text-xs text-muted-foreground italic line-clamp-3">
                «&nbsp;{e}&nbsp;»
              </div>
              <button
                onClick={() => onRemove(i)}
                className="mt-1 shrink-0 text-muted-foreground hover:text-destructive md:opacity-0 md:group-hover:opacity-100 transition-opacity"
              >
                <X className="h-3 w-3" />
              </button>
            </div>
          ))}
        </div>

      {/* Question */}
      <div className="border-t px-4 py-3 space-y-2">
        <textarea
          className="w-full rounded border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"
          rows={2}
          placeholder="Votre question…"
          value={question}
          onChange={e => setQuestion(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }}
        />
        <Button size="sm" className="w-full" onClick={submit} disabled={!question.trim() || submitting || submitted}>
          {submitting
            ? <><Loader2 className="h-3 w-3 animate-spin" /> Envoi…</>
            : submitted
              ? 'Envoyé !'
              : <><Send className="h-3 w-3" /> Envoyer (Ctrl+Entrée)</>}
        </Button>
      </div>
    </div>
  )
}

// ── Summary content renderer ────────────────────────────────────────────────

function SummaryContent({ content }: { content: string }) {
  return <Markdown content={content} />
}

// ── Dashboard ───────────────────────────────────────────────────────────────

export function Dashboard() {
  const { user } = useAuth()
  const [summaries, setSummaries] = useState<Summary[]>([])
  const [assets, setAssets] = useState<Asset[]>([])
  const [loading, setLoading] = useState(true)
  const [generating, setGenerating] = useState(false)
  const [current, setCurrent] = useState<Summary | null>(null)
  const [excerpts, setExcerpts] = useState<string[]>([])

  const summaryRef = useRef<HTMLDivElement>(null)
  const textSel = useTextSelection(summaryRef as React.RefObject<HTMLElement>)

  useEffect(() => { load() }, [])

  // Poll generating status every 5s
  useEffect(() => {
    const interval = setInterval(async () => {
      try {
        const status = await summariesApi.status()
        const wasGenerating = generating
        setGenerating(status.generating)
        if (wasGenerating && !status.generating) load()
      } catch { /* ignore */ }
    }, 5000)
    return () => clearInterval(interval)
  }, [generating])

  async function load() {
    setLoading(true)
    try {
      const [s, a] = await Promise.all([summariesApi.list(5), assetsApi.list()])
      setSummaries(s ?? [])
      setAssets(a ?? [])
      setCurrent(s?.[0] ?? null)
    } finally { setLoading(false) }
  }

  async function generate() {
    setGenerating(true)
    try {
      const s = await summariesApi.generate()
      setSummaries(prev => [s, ...prev])
      setCurrent(s)
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Erreur lors de la génération')
    } finally { setGenerating(false) }
  }

  const addExcerpt = useCallback(() => {
    if (!textSel) return
    setExcerpts(prev => [...prev, textSel.text])
    window.getSelection()?.removeAllRanges()
  }, [textSel])

  async function submitQuestion(question: string) {
    await reportsApi.create({
      summary_id: current?.id,
      excerpts,
      question,
    })
    setExcerpts([])
  }

  return (
    <div className="p-4 md:p-6 space-y-6">
      {/* Generating banner */}
      {generating && (
        <div className="flex items-center gap-3 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
          <Loader2 className="h-4 w-4 animate-spin shrink-0" />
          Génération d'un résumé IA en cours — cela peut prendre plusieurs minutes…
        </div>
      )}

      {/* Header */}
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Bonjour 👋</h1>
          <p className="text-muted-foreground text-sm">{user?.email}</p>
        </div>
        <Button onClick={generate} disabled={generating || assets.length === 0}>
          {generating ? <><Spinner className="h-4 w-4" /> Génération…</> : <><Sparkles className="h-4 w-4" /> Générer un résumé</>}
        </Button>
      </div>

      {assets.length === 0 && !loading && (
        <Card className="border-dashed">
          <CardContent className="py-8 text-center">
            <TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3" />
            <p className="font-medium">Votre watchlist est vide</p>
            <p className="text-sm text-muted-foreground mt-1">Ajoutez des symboles dans la section Watchlist pour obtenir des résumés personnalisés</p>
          </CardContent>
        </Card>
      )}

      {assets.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {assets.map(a => (
            <Badge key={a.id} variant="secondary" className="font-mono">{a.symbol}</Badge>
          ))}
        </div>
      )}

      {/* Résumé actuel */}
      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2 space-y-4">
          {loading ? (
            <div className="flex justify-center py-20"><Spinner /></div>
          ) : current ? (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center gap-2">
                    <Sparkles className="h-5 w-5 text-primary" /> Résumé IA
                  </CardTitle>
                  <div className="flex items-center gap-1 text-xs text-muted-foreground">
                    <Clock className="h-3 w-3" />
                    {new Date(current.generated_at).toLocaleString('fr-FR')}
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div ref={summaryRef} className="relative">
                  <SummaryContent content={current.content} />
                  {/* Desktop: floating button above selection */}
                  {textSel && (
                    <button
                      data-context-action
                      onClick={addExcerpt}
                      className="absolute z-10 hidden md:flex items-center gap-1 rounded-full bg-primary text-primary-foreground text-xs px-2 py-1 shadow-lg hover:bg-primary/90 transition-colors"
                      style={{ left: textSel.x, top: textSel.y, transform: 'translate(-50%, -100%)' }}
                    >
                      <Plus className="h-3 w-3" />
                      Ajouter au contexte
                    </button>
                  )}
                </div>
                {/* Mobile: fixed bottom bar — avoids conflict with native selection menu */}
                {textSel && (
                  <div className="md:hidden fixed bottom-16 left-0 right-0 z-50 flex justify-center px-4 pointer-events-none">
                    <button
                      data-context-action
                      onClick={addExcerpt}
                      className="pointer-events-auto flex items-center gap-2 rounded-full bg-primary text-primary-foreground text-sm px-4 py-2.5 shadow-xl"
                    >
                      <Plus className="h-4 w-4" />
                      Ajouter au contexte
                    </button>
                  </div>
                )}
                <p className="text-xs text-muted-foreground mt-4 italic">
                  Sélectionnez du texte pour l'ajouter au contexte, puis posez une question dans le panneau qui apparaît.
                </p>
              </CardContent>
            </Card>
          ) : (
            <Card className="border-dashed">
              <CardContent className="py-12 text-center text-muted-foreground">
                <Sparkles className="h-8 w-8 mx-auto mb-3 opacity-50" />
                <p>Aucun résumé disponible</p>
                <p className="text-xs mt-1">Cliquez sur "Générer un résumé" pour commencer</p>
              </CardContent>
            </Card>
          )}
        </div>

        {/* Historique résumés */}
        {summaries.length > 1 && (
          <div className="space-y-3">
            <h2 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">Historique</h2>
            {summaries.slice(1).map(s => (
              <Card
                key={s.id}
                className={`cursor-pointer transition-colors hover:border-primary/50 ${current?.id === s.id ? 'border-primary/50' : ''}`}
                onClick={() => setCurrent(s)}
              >
                <CardContent className="py-3">
                  <div className="flex items-center gap-1 text-xs text-muted-foreground mb-1">
                    <Clock className="h-3 w-3" />
                    {new Date(s.generated_at).toLocaleString('fr-FR')}
                  </div>
                  <p className="text-sm line-clamp-3">{s.content.slice(0, 120)}…</p>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Panneau contexte flottant */}
      {excerpts.length > 0 && (
        <ContextPanel
          excerpts={excerpts}
          onRemove={i => setExcerpts(prev => prev.filter((_, idx) => idx !== i))}
          onClear={() => setExcerpts([])}
          onSubmit={submitQuestion}
        />
      )}
    </div>
  )
}
