'use client'

import { useState, useEffect } from 'react'
import { Button } from './ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from './ui/dialog'
import { Loader2, FileText, RefreshCw, Download } from 'lucide-react'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'
import type { NotebookSummary } from '@/lib/ai/services'
import ReactMarkdown from 'react-markdown'

interface NotebookSummaryDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  notebookId: string | null
  notebookName?: string
}

export function NotebookSummaryDialog({
  open,
  onOpenChange,
  notebookId,
  notebookName,
}: NotebookSummaryDialogProps) {
  const { t } = useLanguage()
  const [summary, setSummary] = useState<NotebookSummary | null>(null)
  const [loading, setLoading] = useState(false)
  const [regenerating, setRegenerating] = useState(false)

  // Fetch summary when dialog opens with a notebook
  useEffect(() => {
    if (open && notebookId) {
      fetchSummary()
    } else {
      // Reset state when closing
      setSummary(null)
    }
  }, [open, notebookId])

  const fetchSummary = async () => {
    if (!notebookId) return

    setLoading(true)
    try {
      const response = await fetch('/api/ai/notebook-summary', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          notebookId,
          language: document.documentElement.lang || 'en',
        }),
      })

      const data = await response.json()

      if (data.success && data.data) {
        setSummary(data.data)
      } else {
        toast.error(data.error || t('notebook.summaryError'))
        onOpenChange(false)
      }
    } catch (error) {
      toast.error(t('notebook.summaryError'))
      onOpenChange(false)
    } finally {
      setLoading(false)
    }
  }

  const handleRegenerate = async () => {
    if (!notebookId) return
    setRegenerating(true)
    await fetchSummary()
    setRegenerating(false)
  }

  const handleExportPDF = () => {
    if (!summary) return

    const printWindow = window.open('', '_blank')
    if (!printWindow) return

    const date = new Date(summary.generatedAt).toLocaleString()
    const labels = summary.stats.labelsUsed.length > 0
      ? `<p><strong>${t('notebook.labels')}</strong> ${summary.stats.labelsUsed.join(', ')}</p>`
      : ''

    printWindow.document.write(`<!DOCTYPE html>
<html lang="${document.documentElement.lang || 'en'}">
<head>
  <meta charset="UTF-8" />
  <title>${t('notebook.pdfTitle', { name: summary.notebookName })}</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: Georgia, 'Times New Roman', serif; font-size: 13pt; line-height: 1.7; color: #111; padding: 2.5cm 3cm; max-width: 800px; margin: 0 auto; }
    h1 { font-size: 20pt; font-weight: bold; margin-bottom: 0.25em; }
    .meta { font-size: 10pt; color: #666; margin-bottom: 1.5em; border-bottom: 1px solid #ddd; padding-bottom: 0.75em; }
    .meta p { margin: 0.2em 0; }
    .content h1, .content h2, .content h3 { margin-top: 1.2em; margin-bottom: 0.4em; font-family: sans-serif; }
    .content h2 { font-size: 15pt; }
    .content h3 { font-size: 13pt; }
    .content p { margin-bottom: 0.8em; }
    .content ul, .content ol { margin-left: 1.5em; margin-bottom: 0.8em; }
    .content li { margin-bottom: 0.3em; }
    .content strong { font-weight: bold; }
    .content em { font-style: italic; }
    .content code { font-family: monospace; background: #f4f4f4; padding: 0.1em 0.3em; border-radius: 3px; }
    .content blockquote { border-left: 3px solid #ccc; padding-left: 1em; color: #555; margin: 0.8em 0; }
    @media print {
      body { padding: 1cm 1.5cm; }
      @page { margin: 1.5cm; }
    }
  </style>
</head>
<body>
  <h1>${t('notebook.pdfTitle', { name: summary.notebookName })}</h1>
  <div class="meta">
    <p><strong>${t('notebook.pdfNotesLabel')}</strong> ${summary.stats.totalNotes}</p>
    ${labels}
    <p><strong>${t('notebook.pdfGeneratedOn')}</strong> ${date}</p>
  </div>
  <div class="content">
    ${summary.summary
      .replace(/^### (.+)$/gm, '<h3>$1</h3>')
      .replace(/^## (.+)$/gm, '<h2>$1</h2>')
      .replace(/^# (.+)$/gm, '<h1>$1</h1>')
      .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.+?)\*/g, '<em>$1</em>')
      .replace(/`(.+?)`/g, '<code>$1</code>')
      .replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>')
      .replace(/^[-*] (.+)$/gm, '<li>$1</li>')
      .replace(/(<li>.*<\/li>\n?)+/g, '<ul>$&</ul>')
      .replace(/\n\n/g, '</p><p>')
      .replace(/^(?!<[hHuUoOblp])(.+)$/gm, '<p>$1</p>')}
  </div>
</body>
</html>`)

    printWindow.document.close()
    printWindow.focus()
    setTimeout(() => {
      printWindow.print()
    }, 300)
  }

  if (loading) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="overflow-y-auto" style={{ maxWidth: 'min(48rem, 95vw)', maxHeight: '90vh' }}>
          <DialogHeader className="sr-only">
            <DialogTitle>{t('notebook.generating')}</DialogTitle>
            <DialogDescription>{t('notebook.generatingDescription') || 'Please wait...'}</DialogDescription>
          </DialogHeader>
          <div className="flex flex-col items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <p className="mt-4 text-sm text-muted-foreground">
              {t('notebook.generating')}
            </p>
          </div>
        </DialogContent>
      </Dialog>
    )
  }

  if (!summary) {
    return null
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="flex flex-col overflow-hidden p-0"
        style={{ maxWidth: 'min(64rem, 95vw)', height: '90vh' }}
      >
        {/* En-tête fixe */}
        <div className="flex-shrink-0 px-6 pt-6 pb-4 border-b">
          <div className="flex items-center justify-between gap-4 flex-wrap">
            <div className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              <span className="text-lg font-semibold">{t('notebook.summary')}</span>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" onClick={handleExportPDF} className="gap-2">
                <Download className="h-4 w-4" />
                {t('ai.notebookSummary.exportPDF') || 'Exporter PDF'}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleRegenerate}
                disabled={regenerating}
                className="gap-2"
              >
                <RefreshCw className={`h-4 w-4 ${regenerating ? 'animate-spin' : ''}`} />
                {regenerating
                  ? (t('ai.notebookSummary.regenerating') || 'Regenerating...')
                  : (t('ai.notebookSummary.regenerate') || 'Regenerate')}
              </Button>
            </div>
          </div>
          <p className="text-sm text-muted-foreground mt-1">
            {t('notebook.summaryDescription', {
              notebook: summary.notebookName,
              count: summary.stats.totalNotes,
            })}
          </p>
        </div>

        {/* Zone scrollable */}
        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
          {/* Stats */}
          <div className="flex flex-wrap gap-4 p-4 bg-muted rounded-lg">
            <div className="flex items-center gap-2">
              <FileText className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm">
                {t('ai.autoLabels.notesCount', { count: summary.stats.totalNotes })}
              </span>
            </div>
            {summary.stats.labelsUsed.length > 0 && (
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">{t('notebook.labels')}</span>
                <span className="text-sm">{summary.stats.labelsUsed.join(', ')}</span>
              </div>
            )}
            <div className="ml-auto text-xs text-muted-foreground">
              {new Date(summary.generatedAt).toLocaleString()}
            </div>
          </div>

          {/* Contenu Markdown */}
          <div className="prose prose-sm dark:prose-invert max-w-none">
            <ReactMarkdown>{summary.summary}</ReactMarkdown>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
