'use client'

import { useState, useEffect } from 'react'
import { X, Sparkles, Globe, Check, Loader2, ExternalLink, Trash2, RefreshCw } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useLanguage } from '@/lib/i18n'
import { toast } from 'sonner'
import { motion, AnimatePresence } from 'motion/react'
import { useAiConsent } from '@/components/legal/ai-consent-provider'

type Step = 'loading' | 'published' | 'idle' | 'analyzing' | 'selection' | 'publishing' | 'done' | 'unpublishing'

interface NoteItem {
  id: string
  title: string
  include: boolean
  reason: string
}

interface NotebookSiteDialogProps {
  notebookId: string
  notebookName: string
  onClose: () => void
}

const TEMPLATES = [
  { id: 'magazine', label: 'Magazine', desc: 'Sombre, Playfair Display' },
  { id: 'brief', label: 'Brief', desc: 'Professionnel, sobre' },
  { id: 'essay', label: 'Essai', desc: 'Élégant, ivoire' },
] as const

export function NotebookSiteDialog({ notebookId, notebookName, onClose }: NotebookSiteDialogProps) {
  const { t, language } = useLanguage()
  const { requestAiConsent } = useAiConsent()

  const [step, setStep] = useState<Step>('loading')
  const [existingSlug, setExistingSlug] = useState<string | null>(null)
  const [notes, setNotes] = useState<NoteItem[]>([])
  const [description, setDescription] = useState('')
  const [template, setTemplate] = useState<'magazine' | 'brief' | 'essay'>('magazine')
  const [siteUrl, setSiteUrl] = useState('')

  // Charger l'état existant au montage
  useEffect(() => {
    fetch(`/api/notebooks/${notebookId}/publish`)
      .then(r => r.json())
      .then(data => {
        if (data.site?.slug) {
          setExistingSlug(data.site.slug)
          setSiteUrl(`/c/${data.site.slug}`)
          setTemplate(data.site.template || 'magazine')
          setStep('published')
        } else {
          setStep('idle')
        }
      })
      .catch(() => setStep('idle'))
  }, [notebookId])

  const handleAnalyze = async () => {
    const consented = await requestAiConsent()
    if (!consented) return
    setStep('analyzing')
    try {
      const res = await fetch('/api/ai/notebook-publish', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ notebookId, language }),
      })
      const data = await res.json()
      if (!res.ok) {
        toast.error(data.errorKey === 'ai.featureLocked' ? (t('ai.featureLocked') || 'Plan requis') : (data.error || 'Erreur'))
        setStep(existingSlug ? 'published' : 'idle')
        return
      }
      const items: NoteItem[] = (data.notes || []).map((n: any) => ({
        id: n.noteId,
        title: data.noteTitles?.[n.noteId] || n.noteId,
        include: n.include,
        reason: n.reason,
      }))
      setNotes(items)
      setDescription(data.description || '')
      setStep('selection')
      window.dispatchEvent(new Event('ai-usage-changed'))
    } catch (e: any) {
      toast.error(e.message || 'Erreur')
      setStep(existingSlug ? 'published' : 'idle')
    }
  }

  const handlePublish = async () => {
    const selected = notes.filter(n => n.include).map(n => n.id)
    if (selected.length === 0) { toast.error('Sélectionne au moins une note'); return }
    setStep('publishing')
    try {
      const res = await fetch(`/api/notebooks/${notebookId}/publish`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ selectedNoteIds: selected, template, description }),
      })
      const data = await res.json()
      if (!res.ok) { toast.error(data.errorKey ? t(data.errorKey) : (data.error || 'Erreur')); setStep('selection'); return }
      setExistingSlug(data.slug)
      setSiteUrl(data.url)
      setStep('done')
    } catch (e: any) {
      toast.error(e.message || 'Erreur')
      setStep('selection')
    }
  }

  const handleUnpublish = async () => {
    setStep('unpublishing')
    try {
      const res = await fetch(`/api/notebooks/${notebookId}/publish`, { method: 'DELETE' })
      if (!res.ok) { toast.error('Erreur'); setStep('published'); return }
      setExistingSlug(null)
      setSiteUrl('')
      toast.success('Site dépublié')
      setStep('idle')
    } catch {
      toast.error('Erreur')
      setStep('published')
    }
  }

  const selectedCount = notes.filter(n => n.include).length

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <motion.div
        initial={{ opacity: 0, scale: .96, y: 8 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: .96 }}
        className="relative bg-background border border-border rounded-2xl shadow-2xl w-full max-w-lg flex flex-col max-h-[90vh]"
      >
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-border">
          <div className="flex items-center gap-2.5">
            <Globe size={18} className="text-brand-accent" />
            <div>
              <p className="text-[13px] font-bold">{t('notebookSite.title') || 'Publier en site web'}</p>
              <p className="text-[11px] text-muted-foreground truncate max-w-[280px]">{notebookName}</p>
            </div>
          </div>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground transition-colors p-1">
            <X size={18} />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-5">
          <AnimatePresence mode="wait">

            {/* Chargement initial */}
            {step === 'loading' && (
              <motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex justify-center py-10">
                <Loader2 size={24} className="animate-spin text-muted-foreground" />
              </motion.div>
            )}

            {/* Déjà publié */}
            {step === 'published' && (
              <motion.div key="published" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="space-y-4">
                <div className="rounded-xl border border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-950/30 p-4 flex items-start gap-3">
                  <div className="w-8 h-8 rounded-full bg-green-100 dark:bg-green-900/50 flex items-center justify-center shrink-0">
                    <Check size={15} className="text-green-600 dark:text-green-400" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-[13px] font-bold text-green-800 dark:text-green-300 mb-1">Site en ligne</p>
                    <a
                      href={siteUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-[11px] font-mono text-green-700 dark:text-green-400 hover:underline flex items-center gap-1"
                    >
                      memento-note.com{siteUrl} <ExternalLink size={10} />
                    </a>
                  </div>
                </div>

                <div className="space-y-2">
                  <button
                    onClick={() => setStep('idle')}
                    className="w-full flex items-center gap-2 px-4 py-3 rounded-xl border border-border hover:bg-muted/50 transition-colors text-[13px] font-semibold text-left"
                  >
                    <RefreshCw size={15} className="text-brand-accent" />
                    <div>
                      <p>{t('notebookSite.updateSite') || 'Mettre à jour le site'}</p>
                      <p className="text-[11px] text-muted-foreground font-normal">Relancer l'analyse IA et modifier la sélection</p>
                    </div>
                  </button>

                  <button
                    onClick={handleUnpublish}
                    className="w-full flex items-center gap-2 px-4 py-3 rounded-xl border border-red-200 dark:border-red-900 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors text-[13px] font-semibold text-left text-red-600 dark:text-red-400"
                  >
                    <Trash2 size={15} />
                    <div>
                      <p>{t('notebookSite.unpublish') || 'Dépublier le site'}</p>
                      <p className="text-[11px] text-red-400 font-normal">Le lien public ne sera plus accessible</p>
                    </div>
                  </button>
                </div>
              </motion.div>
            )}

            {/* Dépublication en cours */}
            {step === 'unpublishing' && (
              <motion.div key="unpublishing" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col items-center gap-4 py-10">
                <Loader2 size={28} className="animate-spin text-red-500" />
                <p className="text-[13px] text-muted-foreground">Dépublication en cours...</p>
              </motion.div>
            )}

            {/* Étape 1 : explication */}
            {step === 'idle' && (
              <motion.div key="idle" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="space-y-4">
                <div className="rounded-xl border border-border/50 bg-muted/30 p-4 space-y-3">
                  <p className="text-[13px] font-semibold">{t('notebookSite.howItWorks') || 'Comment ça marche'}</p>
                  <ol className="space-y-2 text-[12px] text-muted-foreground">
                    {[
                      t('notebookSite.step1') || "L'IA analyse vos notes et recommande lesquelles publier",
                      t('notebookSite.step2') || "Vous validez ou modifiez la sélection",
                      t('notebookSite.step3') || "Votre site est généré avec navigation et table des matières",
                    ].map((s, i) => (
                      <li key={i} className="flex items-start gap-2.5">
                        <span className="shrink-0 w-4 h-4 rounded-full bg-brand-accent/20 text-brand-accent text-[10px] font-bold flex items-center justify-center mt-0.5">{i + 1}</span>
                        {s}
                      </li>
                    ))}
                  </ol>
                </div>
                <p className="text-[11px] text-muted-foreground">{t('notebookSite.quotaWarning') || "L'analyse consomme 1 crédit IA."}</p>
              </motion.div>
            )}

            {/* Analyse en cours */}
            {step === 'analyzing' && (
              <motion.div key="analyzing" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col items-center gap-4 py-10">
                <Loader2 size={30} className="animate-spin text-brand-accent" />
                <p className="text-[13px] text-muted-foreground">{t('notebookSite.analyzing') || "L'IA analyse vos notes..."}</p>
              </motion.div>
            )}

            {/* Sélection */}
            {step === 'selection' && (
              <motion.div key="selection" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                {description && (
                  <div className="rounded-xl bg-brand-accent/5 border border-brand-accent/20 p-3">
                    <p className="text-[11px] font-bold text-brand-accent uppercase tracking-widest mb-1">{t('notebookSite.siteDescription') || 'Description générée'}</p>
                    <p className="text-[12px] text-foreground leading-relaxed">{description}</p>
                  </div>
                )}

                <p className="text-[12px] text-muted-foreground">
                  <strong>{selectedCount}</strong> / {notes.length} {t('notebookSite.notesSelected') || 'notes sélectionnées'}
                </p>

                <div className="space-y-1.5 max-h-48 overflow-y-auto pr-1">
                  {notes.map(note => (
                    <button
                      key={note.id}
                      onClick={() => setNotes(prev => prev.map(n => n.id === note.id ? { ...n, include: !n.include } : n))}
                      className={cn(
                        'w-full text-left rounded-lg border p-2.5 transition-colors flex items-start gap-3',
                        note.include
                          ? 'border-brand-accent/40 bg-brand-accent/5'
                          : 'border-border/40 bg-muted/10 opacity-55',
                      )}
                    >
                      <div className={cn(
                        'shrink-0 w-4 h-4 rounded border flex items-center justify-center mt-0.5',
                        note.include ? 'bg-brand-accent border-brand-accent' : 'border-muted-foreground/30 bg-background',
                      )}>
                        {note.include && <Check size={9} className="text-white" strokeWidth={3} />}
                      </div>
                      <div className="min-w-0">
                        <p className="text-[12px] font-semibold text-foreground truncate">{note.title || 'Sans titre'}</p>
                        {note.reason && <p className="text-[10px] text-muted-foreground mt-0.5 leading-relaxed">{note.reason}</p>}
                      </div>
                    </button>
                  ))}
                </div>

                <div>
                  <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-widest mb-2">{t('notebookSite.template') || 'Style visuel'}</p>
                  <div className="grid grid-cols-3 gap-2">
                    {TEMPLATES.map(tpl => (
                      <button
                        key={tpl.id}
                        onClick={() => setTemplate(tpl.id)}
                        className={cn(
                          'rounded-lg border p-2.5 text-left transition-colors',
                          template === tpl.id
                            ? 'border-brand-accent bg-brand-accent/5'
                            : 'border-border/50 hover:border-border',
                        )}
                      >
                        <p className="text-[11px] font-bold">{tpl.label}</p>
                        <p className="text-[10px] text-muted-foreground">{tpl.desc}</p>
                      </button>
                    ))}
                  </div>
                </div>
              </motion.div>
            )}

            {/* Publication en cours */}
            {step === 'publishing' && (
              <motion.div key="publishing" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col items-center gap-4 py-10">
                <Loader2 size={30} className="animate-spin text-brand-accent" />
                <p className="text-[13px] text-muted-foreground">{t('notebookSite.publishing') || 'Génération du site...'}</p>
              </motion.div>
            )}

            {/* Succès */}
            {step === 'done' && (
              <motion.div key="done" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex flex-col items-center gap-5 py-6 text-center">
                <div className="w-14 h-14 rounded-full bg-green-100 dark:bg-green-950/40 flex items-center justify-center">
                  <Check size={26} className="text-green-600 dark:text-green-400" />
                </div>
                <div>
                  <p className="text-[16px] font-bold mb-1">{t('notebookSite.published') || 'Site publié !'}</p>
                  <p className="text-[12px] text-muted-foreground">{selectedCount} notes · accessible publiquement</p>
                </div>
                <a
                  href={siteUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-brand-accent text-white text-[12px] font-bold hover:opacity-90 transition-opacity"
                >
                  <ExternalLink size={13} />
                  {t('notebookSite.openSite') || 'Ouvrir le site'}
                </a>
                <p className="text-[10px] text-muted-foreground font-mono break-all">memento-note.com{siteUrl}</p>
              </motion.div>
            )}

          </AnimatePresence>
        </div>

        {/* Footer actions */}
        <div className="p-4 border-t border-border flex items-center justify-between gap-2">
          <div>
            {(step === 'selection' || step === 'idle') && existingSlug && (
              <button
                onClick={() => setStep('published')}
                className="text-[11px] text-muted-foreground hover:text-foreground transition-colors"
              >
                ← Retour au site actuel
              </button>
            )}
          </div>
          <div className="flex gap-2">
            {step === 'idle' && (
              <button
                onClick={handleAnalyze}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-accent text-white text-[12px] font-bold hover:opacity-90 transition-opacity"
              >
                <Sparkles size={13} />
                {t('notebookSite.analyzeBtn') || "Analyser avec l'IA"}
              </button>
            )}
            {step === 'selection' && (
              <>
                <button
                  onClick={() => setStep('idle')}
                  className="px-3 py-2 rounded-lg text-[12px] text-muted-foreground hover:text-foreground transition-colors"
                >
                  ← Retour
                </button>
                <button
                  onClick={handlePublish}
                  disabled={selectedCount === 0}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-accent text-white text-[12px] font-bold hover:opacity-90 disabled:opacity-40 transition-opacity"
                >
                  <Globe size={13} />
                  {t('notebookSite.publishBtn') || 'Publier'} ({selectedCount})
                </button>
              </>
            )}
            {(step === 'done' || step === 'published') && (
              <button
                onClick={onClose}
                className="px-4 py-2 rounded-lg bg-foreground text-background text-[12px] font-bold hover:opacity-90 transition-opacity"
              >
                Fermer
              </button>
            )}
          </div>
        </div>
      </motion.div>
    </div>
  )
}
