import { useState, useEffect, useCallback } from 'react'
import { Trash2, FileText, Clock, Loader2, XCircle, AlertCircle } from 'lucide-react'
import { reportsApi, type Report } from '@/api/reports'
import { Card, CardContent } from '@/components/ui/card'
import { Markdown } from '@/components/ui/markdown'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import { Badge } from '@/components/ui/badge'

function StatusBadge({ status }: { status: Report['status'] }) {
  if (status === 'generating') return (
    <Badge variant="secondary" className="gap-1 text-xs">
      <Loader2 className="h-3 w-3 animate-spin" /> En cours
    </Badge>
  )
  if (status === 'error') return (
    <Badge variant="destructive" className="gap-1 text-xs">
      <AlertCircle className="h-3 w-3" /> Erreur
    </Badge>
  )
  return null
}

export function Reports() {
  const [reports, setReports] = useState<Report[]>([])
  const [loading, setLoading] = useState(true)

  const load = useCallback(async () => {
    try { setReports((await reportsApi.list()) ?? []) }
    finally { setLoading(false) }
  }, [])

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

  // Poll toutes les 3s tant qu'il y a des rapports en cours
  useEffect(() => {
    const hasGenerating = reports.some(r => r.status === 'generating')
    if (!hasGenerating) return
    const interval = setInterval(load, 3000)
    return () => clearInterval(interval)
  }, [reports, load])

  async function remove(id: string) {
    await reportsApi.delete(id)
    setReports(prev => prev.filter(r => r.id !== id))
  }

  if (loading) return <div className="flex justify-center py-20"><Spinner /></div>

  return (
    <div className="p-4 md:p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Rapports IA</h1>
        <p className="text-muted-foreground text-sm">
          Vos questions posées sur des extraits de résumés, avec les réponses de l'IA.
        </p>
      </div>

      {reports.length === 0 ? (
        <Card className="border-dashed">
          <CardContent className="py-12 text-center text-muted-foreground">
            <FileText className="h-8 w-8 mx-auto mb-3 opacity-50" />
            <p>Aucun rapport enregistré</p>
            <p className="text-xs mt-1">Sélectionnez du texte dans un résumé et posez une question à l'IA.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {reports.map(r => (
            <Card key={r.id} className={r.status === 'generating' ? 'border-primary/30' : ''}>
              <CardContent className="pt-4 pb-4 space-y-3">
                {/* Meta */}
                <div className="flex items-start justify-between gap-4">
                  <div className="flex items-center gap-2 flex-wrap">
                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                      <Clock className="h-3 w-3" />
                      {new Date(r.created_at).toLocaleString('fr-FR')}
                    </div>
                    <StatusBadge status={r.status} />
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive shrink-0"
                    onClick={() => remove(r.id)}
                    title={r.status === 'generating' ? 'Annuler' : 'Supprimer'}
                  >
                    {r.status === 'generating'
                      ? <XCircle className="h-3 w-3" />
                      : <Trash2 className="h-3 w-3" />}
                  </Button>
                </div>

                {/* Extraits de contexte */}
                {r.context_excerpt.split('\n\n---\n\n').map((excerpt, i) => (
                  <div key={i} className="rounded bg-muted/60 px-3 py-2 text-xs text-muted-foreground italic">
                    «&nbsp;{excerpt}&nbsp;»
                  </div>
                ))}

                {/* Question */}
                <p className="text-sm font-medium">{r.question}</p>

                {/* Réponse */}
                {r.status === 'generating' && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Loader2 className="h-4 w-4 animate-spin text-primary" />
                    L'IA génère la réponse…
                  </div>
                )}
                {r.status === 'done' && (
                  <div className="border-t pt-3">
                    <Markdown content={r.answer} />
                  </div>
                )}
                {r.status === 'error' && (
                  <div className="text-sm text-destructive border-t pt-3">
                    Erreur : {r.error_msg || 'Une erreur est survenue lors de la génération.'}
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}
