import { useState, useEffect, useCallback } from 'react'
import { FileText, Plus, Edit2, Archive, CheckCircle, Clock, Copy, Download, ChevronUp, ChevronDown, Eye } from 'lucide-react'
import api from '../utils/api'
import { generateLegalPdf, legalSectionNumber } from '../utils/legalPdfExport'
import LegalDocumentBody from '../components/LegalDocumentBody'
import { LegalPreviewModal } from '../components/LegalDocumentPreview'

const PDF_STATUS_META = { published: 'Gültig seit', draft: 'Entwurf — Stand', archived: 'Archiviert — Stand' }

// ─── Sub-components ──────────────────────────────────────────────────────────

const DOC_TYPES = [
  { key: 'impressum',      label: 'Impressum',           defaultTitle: 'Impressum' },
  { key: 'privacy_policy', label: 'Datenschutz',         defaultTitle: 'Datenschutzerklärung' },
  { key: 'terms_of_use',   label: 'Nutzungsbedingungen', defaultTitle: 'Nutzungsbedingungen' },
  { key: 'media_policy',   label: 'Medienrichtlinie',    defaultTitle: 'Medienrichtlinie' },
]

const STATUS_LABELS = {
  draft:     { label: 'Entwurf',        color: 'var(--text3)' },
  published: { label: 'Veröffentlicht', color: 'var(--accent)' },
  archived:  { label: 'Archiviert',     color: 'var(--danger)' },
}

function StatusBadge({ status }) {
  const s = STATUS_LABELS[status] || { label: status, color: 'var(--text3)' }
  return (
    <span style={{
      fontSize: '0.75rem', fontWeight: 600, color: s.color,
      border: `1px solid ${s.color}`, borderRadius: '4px', padding: '1px 6px',
    }}>
      {s.label}
    </span>
  )
}

function SectionEditor({ sections, onChange }) {
  const update = (i, field, val) =>
    onChange(sections.map((s, idx) => idx === i ? { ...s, [field]: val } : s))

  const remove = (i) => onChange(sections.filter((_, idx) => idx !== i))

  const move = (i, dir) => {
    const next = [...sections]
    const j = i + dir
    if (j < 0 || j >= next.length) return
    ;[next[i], next[j]] = [next[j], next[i]]
    onChange(next)
  }

  // Insert empty section after index i (-1 = prepend)
  const insertAfter = (i) => {
    const next = [...sections]
    next.splice(i + 1, 0, { heading: '', content: '' })
    onChange(next)
  }

  const InsertButton = ({ afterIndex }) => (
    <div style={{ display: 'flex', justifyContent: 'center', margin: '4px 0' }}>
      <button
        type="button"
        onClick={() => insertAfter(afterIndex)}
        title="Neuen Abschnitt hier einfügen"
        style={{
          background: 'none', border: '1px dashed var(--border)', borderRadius: '6px',
          color: 'var(--text3)', cursor: 'pointer', fontSize: '0.78rem',
          padding: '2px 16px', lineHeight: 1.8,
        }}
      >
        + Abschnitt hier einfügen
      </button>
    </div>
  )

  return (
    <div>
      <InsertButton afterIndex={-1} />
      {sections.map((sec, i) => (
        <div key={i}>
          <div className="card" style={{ padding: '12px', marginBottom: 0 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
              <span style={{ fontSize: '0.8rem', color: 'var(--text3)', fontWeight: 600 }}>Abschnitt {i + 1}</span>
              <div style={{ display: 'flex', gap: '4px' }}>
                <button
                  type="button" onClick={() => move(i, -1)} disabled={i === 0}
                  title="Nach oben" className="btn btn-secondary"
                  style={{ padding: '2px 6px', opacity: i === 0 ? 0.3 : 1 }}
                >
                  <ChevronUp size={13} />
                </button>
                <button
                  type="button" onClick={() => move(i, 1)} disabled={i === sections.length - 1}
                  title="Nach unten" className="btn btn-secondary"
                  style={{ padding: '2px 6px', opacity: i === sections.length - 1 ? 0.3 : 1 }}
                >
                  <ChevronDown size={13} />
                </button>
                <button
                  type="button" onClick={() => remove(i)}
                  className="btn btn-secondary" style={{ fontSize: '0.75rem', padding: '2px 8px' }}
                >
                  Entfernen
                </button>
              </div>
            </div>
            <div className="form-row">
              <label className="form-label">Überschrift</label>
              <input
                type="text" className="form-input" value={sec.heading}
                onChange={e => update(i, 'heading', e.target.value)}
                placeholder="Abschnittsüberschrift"
              />
            </div>
            <div className="legal-section-split">
              <div className="legal-section-split__editor">
                <label className="form-label">
                  Inhalt
                  <span className="form-sub">
                    Einfache Markdown-Formatierung: **fett**, *kursiv*, Listen (- oder 1.), [Link](https://…), Zeilenumbruch mit Leerzeile.
                  </span>
                </label>
                <textarea
                  className="form-input" rows={6} value={sec.content}
                  onChange={e => update(i, 'content', e.target.value)}
                  placeholder="Textinhalt des Abschnitts"
                />
              </div>
              <div className="legal-section-split__preview">
                <span className="form-label" style={{ fontSize: '0.8rem', display: 'block', marginBottom: '6px' }}>
                  Live-Vorschau
                </span>
                <div className="legal-section-preview-box" style={{ marginBottom: 0 }}>
                  <h4>
                    {sec.heading?.trim()
                      ? `${legalSectionNumber(i)} ${sec.heading}`
                      : legalSectionNumber(i)}
                  </h4>
                  {sec.content
                    ? <LegalDocumentBody content={sec.content} />
                    : <span style={{ color: 'var(--text3)', fontSize: '0.85rem' }}>(noch kein Text)</span>}
                </div>
              </div>
            </div>
          </div>
          <InsertButton afterIndex={i} />
        </div>
      ))}
      {sections.length === 0 && (
        <p style={{ color: 'var(--text3)', fontSize: '0.88rem', textAlign: 'center', margin: '0.5rem 0' }}>
          Noch keine Abschnitte. Klicke auf „+ Abschnitt hier einfügen".
        </p>
      )}
    </div>
  )
}

function DocumentRow({ doc, onPublish, onArchive, onEdit, onCopy, onDownload, onViewAudit, onRenderedPreview }) {
  const [downloading, setDownloading] = useState(false)

  const handleDownload = async () => {
    setDownloading(true)
    try { await onDownload(doc) } finally { setDownloading(false) }
  }

  return (
    <div className="card" style={{ display: 'flex', alignItems: 'center', gap: '1rem', padding: '12px 16px', marginBottom: '0.5rem' }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, marginBottom: '2px' }}>
          {doc.title}{' '}
          <span style={{ color: 'var(--text3)', fontWeight: 400, fontSize: '0.85rem' }}>v{doc.version}</span>
        </div>
        <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
          <StatusBadge status={doc.status} />
          {doc.published_at && (
            <span style={{ fontSize: '0.78rem', color: 'var(--text3)' }}>
              veröffentlicht {new Date(doc.published_at).toLocaleDateString('de-DE')}
            </span>
          )}
          {doc.change_note && (
            <span style={{ fontSize: '0.78rem', color: 'var(--text3)', fontStyle: 'italic' }}>
              {doc.change_note}
            </span>
          )}
        </div>
      </div>
      <div style={{ display: 'flex', gap: '0.4rem', flexShrink: 0 }}>
        {doc.status === 'draft' && (
          <>
            <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
              onClick={() => onEdit(doc)} title="Bearbeiten">
              <Edit2 size={13} />
            </button>
            <button className="btn btn-primary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
              onClick={() => onPublish(doc)} title="Veröffentlichen">
              <CheckCircle size={13} />
            </button>
          </>
        )}
        {doc.status === 'published' && (
          <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
            onClick={() => onArchive(doc)} title="Archivieren">
            <Archive size={13} />
          </button>
        )}
        <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
          onClick={() => onRenderedPreview(doc)} title="Gerenderte Vorschau">
          <Eye size={13} />
        </button>
        <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
          onClick={() => onCopy(doc)} title="Als neuen Entwurf kopieren">
          <Copy size={13} />
        </button>
        <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
          onClick={handleDownload} disabled={downloading} title="Als PDF herunterladen">
          {downloading ? '…' : <Download size={13} />}
        </button>
        <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.78rem' }}
          onClick={() => onViewAudit(doc)} title="Änderungslog">
          <Clock size={13} />
        </button>
      </div>
    </div>
  )
}

function EditForm({ docType, editDoc, onSaved, onCancel, onShowRenderedPreview }) {
  const [title, setTitle] = useState(editDoc ? editDoc.title : docType.defaultTitle)
  const [sections, setSections] = useState([])
  const [changeNote, setChangeNote] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState(null)
  const [loadingDoc, setLoadingDoc] = useState(!!editDoc)

  useEffect(() => {
    if (editDoc) {
      api.getLegalDocument(editDoc.id)
        .then(d => {
          setTitle(d.title)
          setSections(d.content_sections || [])
          setChangeNote(d.change_note || '')
        })
        .catch(e => setError(e.message))
        .finally(() => setLoadingDoc(false))
    }
  }, [editDoc])

  const handleSave = async () => {
    setSaving(true)
    setError(null)
    try {
      const payload = { title, content_sections: sections, change_note: changeNote || null }
      if (editDoc) {
        await api.updateLegalDocument(editDoc.id, payload)
      } else {
        await api.createLegalDocument({ document_type: docType.key, ...payload })
      }
      onSaved()
    } catch (e) {
      setError(e.message)
    } finally {
      setSaving(false)
    }
  }

  if (loadingDoc) return <div className="spinner" />

  return (
    <div className="card" style={{ marginTop: '1rem' }}>
      <h3 style={{ marginBottom: '1rem' }}>
        {editDoc ? 'Entwurf bearbeiten' : 'Neuen Entwurf erstellen'}
      </h3>
      {error && (
        <div className="card" style={{ borderLeft: '4px solid var(--danger)', marginBottom: '1rem' }}>
          <span style={{ color: 'var(--danger)' }}>{error}</span>
        </div>
      )}
      <div className="form-row">
        <label className="form-label">Titel *</label>
        <input type="text" className="form-input" value={title}
          onChange={e => setTitle(e.target.value)} required />
      </div>
      <div className="form-row">
        <label className="form-label">Abschnitte</label>
        <SectionEditor sections={sections} onChange={setSections} />
      </div>
      <div className="form-row">
        <label className="form-label">Änderungsnotiz (optional)</label>
        <input type="text" className="form-input" value={changeNote}
          onChange={e => setChangeNote(e.target.value)}
          placeholder="z. B. Erste Version nach juristischer Prüfung" />
      </div>
      <div style={{ display: 'flex', gap: '0.75rem', marginTop: '0.5rem', flexWrap: 'wrap' }}>
        <button className="btn btn-primary" onClick={handleSave} disabled={saving || !title.trim()}>
          {saving ? 'Speichern…' : 'Entwurf speichern'}
        </button>
        <button
          type="button"
          className="btn btn-secondary"
          onClick={() =>
            onShowRenderedPreview?.({
              title,
              sections,
              metaLine: 'Aktueller Editorstand (nicht automatisch gespeichert)',
            })}
          style={{ display: 'flex', alignItems: 'center', gap: '0.35rem' }}
        >
          <Eye size={15} /> Vollständige Vorschau
        </button>
        <button className="btn btn-secondary" onClick={onCancel}>Abbrechen</button>
      </div>
    </div>
  )
}

function AuditLog({ docId, onClose }) {
  const [entries, setEntries] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.getLegalDocumentAudit(docId)
      .then(setEntries)
      .catch(() => setEntries([]))
      .finally(() => setLoading(false))
  }, [docId])

  const ACTION_LABELS = { created: 'Erstellt', updated: 'Bearbeitet', published: 'Veröffentlicht', archived: 'Archiviert' }

  return (
    <div className="card" style={{ marginTop: '1rem' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
        <h3 style={{ margin: 0 }}>Änderungslog</h3>
        <button className="btn btn-secondary" style={{ padding: '4px 10px', fontSize: '0.8rem' }} onClick={onClose}>
          Schließen
        </button>
      </div>
      {loading ? <div className="spinner" /> : entries.length === 0 ? (
        <p style={{ color: 'var(--text3)' }}>Keine Einträge.</p>
      ) : entries.map(e => (
        <div key={e.id} style={{ padding: '8px 0', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
            <strong style={{ fontSize: '0.85rem' }}>{ACTION_LABELS[e.action] || e.action}</strong>
            {e.previous_status && <span style={{ fontSize: '0.78rem', color: 'var(--text3)' }}>von {e.previous_status}</span>}
            <span style={{ fontSize: '0.78rem', color: 'var(--text3)' }}>{new Date(e.created_at).toLocaleString('de-DE')}</span>
            {e.changed_by_name && <span style={{ fontSize: '0.78rem', color: 'var(--text3)' }}>von {e.changed_by_name}</span>}
          </div>
          {e.change_note && (
            <p style={{ margin: '2px 0 0', fontSize: '0.82rem', color: 'var(--text2)', fontStyle: 'italic' }}>
              {e.change_note}
            </p>
          )}
        </div>
      ))}
    </div>
  )
}

// ─── Main page ───────────────────────────────────────────────────────────────

export default function AdminLegalDocumentsPage() {
  const [activeType, setActiveType] = useState(DOC_TYPES[0].key)
  const [documents, setDocuments] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [showForm, setShowForm] = useState(false)
  const [editDoc, setEditDoc] = useState(null)
  const [auditDocId, setAuditDocId] = useState(null)
  const [confirmPublish, setConfirmPublish] = useState(null)
  const [legalPreview, setLegalPreview] = useState({
    open: false,
    loading: false,
    title: '',
    sections: [],
    metaLine: '',
  })

  const activeDocType = DOC_TYPES.find(d => d.key === activeType)

  const load = useCallback(() => {
    setLoading(true)
    setError(null)
    api.listLegalDocuments(activeType)
      .then(setDocuments)
      .catch(e => setError(e.message))
      .finally(() => setLoading(false))
  }, [activeType])

  useEffect(() => {
    load()
    setShowForm(false)
    setEditDoc(null)
    setAuditDocId(null)
    setConfirmPublish(null)
  }, [load])

  const handlePublish = (doc) => setConfirmPublish(doc)

  const confirmAndPublish = async () => {
    if (!confirmPublish) return
    try {
      await api.publishLegalDocument(confirmPublish.id, null)
      setConfirmPublish(null)
      load()
    } catch (e) { alert('Fehler: ' + e.message) }
  }

  const handleArchive = async (doc) => {
    if (!confirm(`"${doc.title}" archivieren?`)) return
    try { await api.archiveLegalDocument(doc.id); load() }
    catch (e) { alert('Fehler: ' + e.message) }
  }

  const handleEdit = (doc) => { setEditDoc(doc); setShowForm(true); setAuditDocId(null) }
  const handleViewAudit = (doc) => { setAuditDocId(doc.id); setShowForm(false); setEditDoc(null) }
  const handleNew = () => { setEditDoc(null); setShowForm(true); setAuditDocId(null) }
  const handleSaved = () => { setShowForm(false); setEditDoc(null); load() }

  const handleCopy = async (doc) => {
    try { await api.copyLegalDocumentAsDraft(doc.id); load() }
    catch (e) { alert('Fehler: ' + e.message) }
  }

  const closeLegalPreview = () =>
    setLegalPreview({ open: false, loading: false, title: '', sections: [], metaLine: '' })

  const openLegalPreviewFromEditor = (payload) => {
    setLegalPreview({
      open: true,
      loading: false,
      title: payload.title,
      sections: payload.sections,
      metaLine: payload.metaLine || '',
    })
  }

  const openLegalPreviewFromList = async (doc) => {
    setLegalPreview({
      open: true,
      loading: true,
      title: '',
      sections: [],
      metaLine: 'Laden…',
    })
    try {
      const full = await api.getLegalDocument(doc.id)
      setLegalPreview({
        open: true,
        loading: false,
        title: full.title,
        sections: full.content_sections || [],
        metaLine: `Version ${full.version} · ${STATUS_LABELS[full.status]?.label || full.status}`,
      })
    } catch (e) {
      closeLegalPreview()
      alert('Fehler: ' + e.message)
    }
  }

  const handleDownload = async (doc) => {
    const full = await api.getLegalDocument(doc.id)
    const dateStr = full.published_at
      ? new Date(full.published_at).toLocaleDateString('de-DE')
      : new Date(full.updated_at || full.created_at).toLocaleDateString('de-DE')
    const metaLine = `Version ${full.version}  |  ${PDF_STATUS_META[full.status] || full.status} ${dateStr}`
    generateLegalPdf(full, metaLine)
  }

  const publishedDoc = documents.find(d => d.status === 'published')

  return (
    <div className="app-main">
      <div style={{ maxWidth: '860px', margin: '0 auto' }}>

        <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.5rem' }}>
          <FileText size={22} color="var(--accent)" />
          <h1 style={{ margin: 0 }}>Rechtstexte verwalten</h1>
        </div>

        <div className="card" style={{ marginBottom: '1rem', padding: '12px', background: 'var(--surface)' }}>
          <p style={{ margin: 0, fontSize: '0.88rem', color: 'var(--text2)' }}>
            Versionierte Rechtstexte erstellen, bearbeiten und veröffentlichen.
            Pro Dokumententyp kann immer nur ein Text veröffentlicht sein.
          </p>
        </div>

        {/* Tab-Leiste */}
        <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginBottom: '1.25rem' }}>
          {DOC_TYPES.map(dt => (
            <button
              key={dt.key}
              className={`btn ${activeType === dt.key ? 'btn-primary' : 'btn-secondary'}`}
              onClick={() => setActiveType(dt.key)}
              style={{ minWidth: '130px' }}
            >
              {dt.label}
            </button>
          ))}
        </div>

        {/* Aktuell veröffentlicht */}
        {publishedDoc && (
          <div className="card" style={{ marginBottom: '1rem', borderLeft: '3px solid var(--accent)', display: 'flex', alignItems: 'center', gap: '0.75rem', padding: '10px 16px' }}>
            <CheckCircle size={16} color="var(--accent)" />
            <span style={{ fontSize: '0.88rem' }}>
              <strong>Aktuell live:</strong> {publishedDoc.title} (v{publishedDoc.version}
              {publishedDoc.published_at && `, ${new Date(publishedDoc.published_at).toLocaleDateString('de-DE')}`})
            </span>
          </div>
        )}

        {/* Aktionen */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '0.75rem' }}>
          <button className="btn btn-primary" onClick={handleNew} style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
            <Plus size={15} /> Neuer Entwurf
          </button>
        </div>

        {error && (
          <div className="card" style={{ borderLeft: '4px solid var(--danger)', marginBottom: '1rem' }}>
            <span style={{ color: 'var(--danger)' }}>{error}</span>
          </div>
        )}

        {/* Bestätigung Veröffentlichen */}
        {confirmPublish && (
          <div className="card" style={{ borderLeft: '4px solid var(--accent)', marginBottom: '1rem' }}>
            <p style={{ margin: '0 0 0.75rem' }}>
              <strong>„{confirmPublish.title}"</strong> veröffentlichen?
              {publishedDoc && publishedDoc.id !== confirmPublish.id && (
                <> Die aktuelle Version ({publishedDoc.title} v{publishedDoc.version}) wird dabei archiviert.</>
              )}
            </p>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <button className="btn btn-primary" onClick={confirmAndPublish}>Ja, veröffentlichen</button>
              <button className="btn btn-secondary" onClick={() => setConfirmPublish(null)}>Abbrechen</button>
            </div>
          </div>
        )}

        {/* Dokumentenliste */}
        {loading ? <div className="spinner" /> : documents.length === 0 ? (
          <div className="card" style={{ textAlign: 'center', padding: '2rem', color: 'var(--text3)' }}>
            Noch keine Versionen für {activeDocType?.label}. Erstelle einen neuen Entwurf.
          </div>
        ) : (
          documents.map(doc => (
            <DocumentRow
              key={doc.id}
              doc={doc}
              onPublish={handlePublish}
              onArchive={handleArchive}
              onEdit={handleEdit}
              onCopy={handleCopy}
              onDownload={handleDownload}
              onViewAudit={handleViewAudit}
              onRenderedPreview={openLegalPreviewFromList}
            />
          ))
        )}

        {showForm && (
          <EditForm
            docType={activeDocType}
            editDoc={editDoc}
            onSaved={handleSaved}
            onCancel={() => { setShowForm(false); setEditDoc(null) }}
            onShowRenderedPreview={openLegalPreviewFromEditor}
          />
        )}

        <LegalPreviewModal
          open={legalPreview.open}
          onClose={closeLegalPreview}
          title={legalPreview.title}
          sections={legalPreview.sections}
          metaLine={legalPreview.metaLine}
          loading={legalPreview.loading}
        />

        {auditDocId && (
          <AuditLog docId={auditDocId} onClose={() => setAuditDocId(null)} />
        )}
      </div>
    </div>
  )
}
