'use client'

import { useState } from 'react'
import { LegalTemplateResult } from '@/lib/sdk/types'
import { RuleEngineResult } from '../ruleEngine'
import ReviewAssignmentPanel from './ReviewAssignmentPanel'

interface GeneratorPreviewTabProps {
  template: LegalTemplateResult
  ruleResult: RuleEngineResult | null
  renderedContent: string
  missing: string[]
  onCopy: () => void
  onExportMarkdown: () => void
  onSaveToWorkflow?: () => void
  saveStatus?: string | null
}

// ============================================================================
// Lightweight Markdown → HTML (no dependency needed)
// ============================================================================

function markdownToHtml(md: string): string {
  let html = md
    // Escape HTML entities first
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')

  // Headings
  html = html.replace(/^#### (.+)$/gm, '<h4>$1</h4>')
  html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>')
  html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>')
  html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>')

  // Horizontal rules
  html = html.replace(/^---$/gm, '<hr/>')

  // Bold + Italic
  html = html.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>')
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>')

  // Links
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-purple-600 underline">$1</a>')

  // Tables (simple)
  html = html.replace(/^\|(.+)\|$/gm, (match) => {
    const cells = match.split('|').filter(c => c.trim())
    const isHeader = cells.every(c => /^[\s-:]+$/.test(c))
    if (isHeader) return '<!-- separator -->'
    const tag = 'td'
    return '<tr>' + cells.map(c => `<${tag}>${c.trim()}</${tag}>`).join('') + '</tr>'
  })

  // Wrap consecutive table rows
  html = html.replace(/((?:<tr>.*<\/tr>\n?<!-- separator -->\n?)?(?:<tr>.*<\/tr>\n?)+)/g, (block) => {
    const rows = block.split('\n').filter(r => r.startsWith('<tr>'))
    if (rows.length === 0) return block
    const headerRow = rows[0].replace(/<td>/g, '<th>').replace(/<\/td>/g, '</th>')
    const bodyRows = rows.slice(1).join('\n')
    return `<table><thead>${headerRow}</thead><tbody>${bodyRows}</tbody></table>`
  })

  // Remove separator comments
  html = html.replace(/<!-- separator -->\n?/g, '')

  // Unordered lists
  html = html.replace(/^- (.+)$/gm, '<li>$1</li>')
  html = html.replace(/((?:<li>.*<\/li>\n?)+)/g, '<ul>$1</ul>')

  // Paragraphs (lines that aren't already HTML)
  html = html.replace(/^(?!<[a-z/]|$)(.+)$/gm, '<p>$1</p>')

  // Clean up empty paragraphs
  html = html.replace(/<p>\s*<\/p>/g, '')

  return html
}

// ============================================================================
// Component
// ============================================================================

export default function GeneratorPreviewTab({
  template,
  ruleResult,
  renderedContent,
  missing,
  onCopy,
  onExportMarkdown,
  onSaveToWorkflow,
  saveStatus,
}: GeneratorPreviewTabProps) {
  const [viewMode, setViewMode] = useState<'preview' | 'markdown'>('preview')

  const htmlContent = markdownToHtml(renderedContent)

  return (
    <div className="space-y-4">
      {/* Violations */}
      {ruleResult && ruleResult.violations.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4">
          <p className="text-sm font-semibold text-red-700 mb-2">
            {ruleResult.violations.length} Fehler
          </p>
          <ul className="space-y-1">
            {ruleResult.violations.map((v) => (
              <li key={v.id} className="text-xs text-red-600">
                <span className="font-mono font-medium">[{v.id}]</span> {v.message}
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Warnings */}
      {ruleResult && ruleResult.warnings.filter((w) => w.id !== 'WARN_LEGAL_REVIEW').length > 0 && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
          <ul className="space-y-1">
            {ruleResult.warnings
              .filter((w) => w.id !== 'WARN_LEGAL_REVIEW')
              .map((w) => (
                <li key={w.id} className="text-xs text-yellow-700">
                  <span className="font-mono font-medium">[{w.id}]</span> {w.message}
                </li>
              ))}
          </ul>
        </div>
      )}

      {/* Legal notice */}
      {ruleResult && (
        <div className="bg-blue-50 border border-blue-200 rounded-xl p-3">
          <p className="text-xs text-blue-700">
            Rechtlicher Hinweis: Diese Vorlage ist MIT-lizenziert. Vor Produktionseinsatz
            wird eine rechtliche Ueberpruefung dringend empfohlen.
          </p>
        </div>
      )}

      {/* Toolbar */}
      <div className="flex items-center justify-between flex-wrap gap-2">
        <div className="flex gap-1 bg-gray-100 rounded-lg p-0.5">
          <button
            onClick={() => setViewMode('preview')}
            className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${
              viewMode === 'preview' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500'
            }`}
          >
            Vorschau
          </button>
          <button
            onClick={() => setViewMode('markdown')}
            className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${
              viewMode === 'markdown' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500'
            }`}
          >
            Markdown
          </button>
        </div>

        <div className="flex items-center gap-2">
          {missing.length > 0 && (
            <span className="text-xs text-orange-600">
              {missing.length} Platzhalter offen
            </span>
          )}
          <button onClick={onCopy} className="px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-600">
            Kopieren
          </button>
          <button onClick={onExportMarkdown} className="px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-600">
            Markdown
          </button>
          <button
            onClick={() => {
              const printWindow = window.open('', '_blank')
              if (!printWindow) return
              printWindow.document.write(`<!DOCTYPE html><html><head><title>${template.documentTitle || 'Dokument'}</title><style>
                @page { size: A4; margin: 25mm 20mm; }
                body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 11pt; line-height: 1.6; color: #1a202c; max-width: 170mm; margin: 0 auto; }
                h1 { font-size: 18pt; color: #5b21b6; margin: 24pt 0 8pt; border-bottom: 2px solid #7c3aed; padding-bottom: 4pt; }
                h2 { font-size: 14pt; color: #1f2937; margin: 18pt 0 6pt; }
                h3 { font-size: 12pt; color: #374151; margin: 12pt 0 4pt; }
                h4 { font-size: 11pt; color: #4b5563; margin: 10pt 0 4pt; }
                table { width: 100%; border-collapse: collapse; margin: 8pt 0; font-size: 10pt; }
                th { background: #f5f3ff; color: #5b21b6; font-weight: 600; text-align: left; padding: 6pt 8pt; border: 1px solid #e5e7eb; }
                td { padding: 5pt 8pt; border: 1px solid #e5e7eb; vertical-align: top; }
                ul { padding-left: 20pt; }
                li { margin: 2pt 0; }
                hr { border: none; border-top: 1px solid #e5e7eb; margin: 16pt 0; }
                a { color: #7c3aed; }
                p { margin: 4pt 0; }
                strong { font-weight: 600; }
              </style></head><body>${htmlContent}</body></html>`)
              printWindow.document.close()
              printWindow.print()
            }}
            className="px-4 py-1.5 text-xs bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            PDF drucken
          </button>
          {onSaveToWorkflow && (
            <button
              onClick={onSaveToWorkflow}
              disabled={saveStatus === 'saving'}
              className={`px-4 py-1.5 text-xs rounded-lg transition-colors ${
                saveStatus === 'saved' ? 'bg-green-600 text-white' :
                saveStatus === 'error' ? 'bg-red-600 text-white' :
                'bg-indigo-600 text-white hover:bg-indigo-700'
              } disabled:opacity-50`}
            >
              {saveStatus === 'saving' ? 'Speichern...' :
               saveStatus === 'saved' ? 'Gespeichert!' :
               saveStatus === 'error' ? 'Fehler' :
               'Als Version speichern'}
            </button>
          )}
        </div>
      </div>

      {/* Content */}
      {viewMode === 'markdown' ? (
        <div className="bg-gray-50 rounded-xl border border-gray-200 p-6 max-h-[800px] overflow-y-auto">
          <pre className="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed font-mono">
            {renderedContent}
          </pre>
        </div>
      ) : (
        <div className="bg-gray-100 rounded-xl p-8 flex justify-center overflow-y-auto max-h-[85vh]">
          {/* A4 Page */}
          <div
            className="bg-white shadow-lg border border-gray-300"
            style={{
              width: '210mm',
              minHeight: '297mm',
              padding: '25mm 20mm',
              fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
              fontSize: '11pt',
              lineHeight: '1.6',
              color: '#1a202c',
            }}
          >
            <style>{`
              .a4-content h1 { font-size: 18pt; color: #5b21b6; margin: 24pt 0 8pt; border-bottom: 2px solid #7c3aed; padding-bottom: 4pt; }
              .a4-content h2 { font-size: 14pt; color: #1f2937; margin: 18pt 0 6pt; }
              .a4-content h3 { font-size: 12pt; color: #374151; margin: 12pt 0 4pt; }
              .a4-content h4 { font-size: 11pt; color: #4b5563; margin: 10pt 0 4pt; }
              .a4-content table { width: 100%; border-collapse: collapse; margin: 8pt 0; font-size: 10pt; }
              .a4-content th { background: #f5f3ff; color: #5b21b6; font-weight: 600; text-align: left; padding: 6pt 8pt; border: 1px solid #e5e7eb; }
              .a4-content td { padding: 5pt 8pt; border: 1px solid #e5e7eb; vertical-align: top; }
              .a4-content ul { padding-left: 20pt; margin: 4pt 0; }
              .a4-content li { margin: 2pt 0; }
              .a4-content hr { border: none; border-top: 1px solid #e5e7eb; margin: 16pt 0; }
              .a4-content a { color: #7c3aed; text-decoration: underline; }
              .a4-content p { margin: 4pt 0; }
              .a4-content strong { font-weight: 600; }
            `}</style>
            <div
              className="a4-content"
              dangerouslySetInnerHTML={{ __html: htmlContent }}
            />
          </div>
        </div>
      )}

      {/* Review Assignment */}
      <ReviewAssignmentPanel
        documentType={template.templateType || ''}
        documentTitle={template.documentTitle || 'Dokument'}
        documentContent={renderedContent}
      />

      {/* Attribution */}
      {template.attributionRequired && template.attributionText && (
        <div className="text-xs text-orange-600 bg-orange-50 p-3 rounded-lg border border-orange-200">
          <strong>Attribution erforderlich:</strong> {template.attributionText}
        </div>
      )}
    </div>
  )
}
