'use client'

/**
 * Rechte Spalte: Detail-Editor fuer die ausgewaehlte Regel.
 *
 * - Zeigt Live-Version + offenen Draft (falls vorhanden)
 * - Erlaubt Draft-Edit (classification, conditions, source_citation, rationale)
 * - Buttons: "Neuen Draft starten" (kopiert von Live), "Einreichen" (mit Pflicht
 *   change_summary-Modal), "Intern freigeben" (DSB), "Publish" (= Mandanten-Freigabe)
 * - Versionshistorie + Approval-Trail unten als Akkordeon
 */

import { useEffect, useMemo, useState } from 'react'
import type {
  ApprovalHistoryEntry, Classification, Rule, RuleCondition, RuleVersion,
} from '../_types'
import { CLASSIFICATION_LABELS, STATUS_LABELS } from '../_types'
import ConditionBuilder from './ConditionBuilder'

interface Props {
  rule: Rule
  versions: RuleVersion[]
  history: ApprovalHistoryEntry[]
  onCreateDraft: (payload: {
    classification: Classification
    conditions: RuleCondition
    source_citation: string
    rationale?: string | null
  }) => Promise<void>
  onUpdateDraft: (versionId: string, patch: {
    classification?: Classification
    conditions?: RuleCondition
    source_citation?: string
    rationale?: string | null
  }) => Promise<void>
  onSubmitForReview: (versionId: string, changeSummary: string) => Promise<void>
  onApprove: (versionId: string) => Promise<void>
  onPublish: (versionId: string) => Promise<void>
  onReject: (versionId: string, reason: string) => Promise<void>
}

export default function RuleEditor({
  rule, versions, history,
  onCreateDraft, onUpdateDraft,
  onSubmitForReview, onApprove, onPublish, onReject,
}: Props) {
  const liveVersion = useMemo(
    () => versions.find((v) => v.is_live) || null,
    [versions],
  )
  const draftVersion = useMemo(
    () => versions.find((v) => ['draft', 'review'].includes(v.status)) || null,
    [versions],
  )

  // Edit-State
  const [classification, setClassification] = useState<Classification>('required')
  const [conditions, setConditions] = useState<RuleCondition>({ kind: 'all', clauses: [] })
  const [sourceCitation, setSourceCitation] = useState('')
  const [rationale, setRationale] = useState('')

  // Modal-State
  const [showSubmit, setShowSubmit] = useState(false)
  const [changeSummary, setChangeSummary] = useState('')
  const [showHistory, setShowHistory] = useState(false)
  const [rejectReason, setRejectReason] = useState('')
  const [showReject, setShowReject] = useState(false)

  // Sync Edit-State mit ausgewaehltem Version (Draft hat Vorrang)
  const sourceVersion = draftVersion || liveVersion
  useEffect(() => {
    if (sourceVersion) {
      setClassification(sourceVersion.classification)
      setConditions(sourceVersion.conditions)
      setSourceCitation(sourceVersion.source_citation)
      setRationale(sourceVersion.rationale || '')
    }
  }, [sourceVersion?.id])

  const isDraftMode = !!draftVersion && draftVersion.status === 'draft'
  const isReviewMode = !!draftVersion && draftVersion.status === 'review'
  const readOnly = !isDraftMode

  const handleCreateDraft = () => {
    onCreateDraft({
      classification: liveVersion?.classification || 'recommended',
      conditions: liveVersion?.conditions || { kind: 'all', clauses: [] },
      source_citation: liveVersion?.source_citation || '',
      rationale: liveVersion?.rationale,
    })
  }

  const handleSaveDraft = () => {
    if (!draftVersion) return
    onUpdateDraft(draftVersion.id, {
      classification, conditions, source_citation: sourceCitation, rationale,
    })
  }

  const handleSubmit = () => {
    if (!draftVersion || !changeSummary.trim()) return
    onSubmitForReview(draftVersion.id, changeSummary.trim())
    setShowSubmit(false)
    setChangeSummary('')
  }

  return (
    <div className="h-full flex flex-col overflow-hidden bg-white">
      <header className="px-5 py-3 border-b border-gray-200">
        <div className="flex items-baseline justify-between gap-3">
          <div className="min-w-0">
            <h2 className="text-base font-semibold text-gray-800 truncate">{rule.title}</h2>
            <div className="text-xs text-gray-500">
              <code>{rule.document_type}</code> · {rule.rule_key}
            </div>
          </div>
          <div className="flex items-center gap-2 text-xs text-gray-600">
            {liveVersion && (
              <span>
                Live: v{liveVersion.version_number} (
                <code>{liveVersion.classification}</code>)
              </span>
            )}
            {draftVersion && (
              <span className="px-1.5 py-0.5 bg-amber-100 text-amber-800 rounded border border-amber-300">
                Draft v{draftVersion.version_number} · {STATUS_LABELS[draftVersion.status]}
              </span>
            )}
          </div>
        </div>
      </header>

      <div className="flex-1 overflow-y-auto p-5 space-y-4">
        {!draftVersion && (
          <div className="bg-amber-50 border border-amber-200 rounded p-3 flex items-center justify-between">
            <span className="text-sm text-amber-800">
              Kein offener Draft. Starte einen neuen Draft, um die Regel zu ändern.
            </span>
            <button
              className="px-3 py-1.5 text-sm bg-amber-600 text-white rounded hover:bg-amber-700"
              onClick={handleCreateDraft}
            >
              + Neuen Draft starten
            </button>
          </div>
        )}

        {/* Klassifikation */}
        <section>
          <label className="text-xs font-medium text-gray-700 block mb-1">
            Klassifikation
          </label>
          <select
            className="text-sm px-2 py-1 border border-gray-300 rounded"
            value={classification}
            disabled={readOnly}
            onChange={(e) => setClassification(e.target.value as Classification)}
          >
            {(['required', 'recommended', 'optional'] as const).map((c) => (
              <option key={c} value={c}>{CLASSIFICATION_LABELS[c]}</option>
            ))}
          </select>
        </section>

        {/* Bedingung */}
        <section>
          <label className="text-xs font-medium text-gray-700 block mb-1">
            Bedingung
          </label>
          <ConditionBuilder
            value={conditions}
            onChange={setConditions}
            readOnly={readOnly}
          />
        </section>

        {/* Source Citation (Pflicht) */}
        <section>
          <label className="text-xs font-medium text-gray-700 block mb-1">
            Quelle / Norm-Citation <span className="text-rose-600">*</span>
          </label>
          <input
            type="text"
            className="w-full text-sm px-2 py-1.5 border border-gray-300 rounded"
            placeholder="z.B. § 12 HinSchG, Art. 28 DSGVO, EuGH C-311/18"
            value={sourceCitation}
            disabled={readOnly}
            onChange={(e) => setSourceCitation(e.target.value)}
          />
        </section>

        {/* Rationale */}
        <section>
          <label className="text-xs font-medium text-gray-700 block mb-1">
            Begründung / Rationale (optional)
          </label>
          <textarea
            className="w-full text-sm px-2 py-1.5 border border-gray-300 rounded"
            rows={3}
            placeholder="Anwalts-Kommentar, warum die Regel so klassifiziert ist…"
            value={rationale}
            disabled={readOnly}
            onChange={(e) => setRationale(e.target.value)}
          />
        </section>

        {/* Versionshistorie */}
        <section>
          <button
            className="text-xs text-gray-600 hover:text-gray-800"
            onClick={() => setShowHistory((v) => !v)}
          >
            {showHistory ? '▾' : '▸'} Versionshistorie + Approval-Trail ({versions.length} Versionen)
          </button>
          {showHistory && (
            <HistoryList versions={versions} history={history} />
          )}
        </section>
      </div>

      {/* Footer-Aktionen */}
      <footer className="px-5 py-3 border-t border-gray-200 bg-gray-50 flex items-center gap-2 flex-wrap">
        {isDraftMode && (
          <>
            <button
              className="px-3 py-1.5 text-sm border border-gray-300 rounded text-gray-700 hover:bg-white"
              onClick={handleSaveDraft}
            >
              Draft speichern
            </button>
            <button
              className="px-3 py-1.5 text-sm bg-amber-600 text-white rounded hover:bg-amber-700 disabled:opacity-50"
              disabled={!sourceCitation.trim()}
              onClick={() => setShowSubmit(true)}
              title={!sourceCitation.trim() ? 'Source Citation ist Pflicht' : ''}
            >
              Zur internen Prüfung einreichen
            </button>
          </>
        )}
        {isReviewMode && (
          <>
            <button
              className="px-3 py-1.5 text-sm bg-emerald-600 text-white rounded hover:bg-emerald-700"
              onClick={() => draftVersion && onApprove(draftVersion.id)}
            >
              Intern freigeben → Mandant
            </button>
            <button
              className="px-3 py-1.5 text-sm bg-blue-600 text-white rounded hover:bg-blue-700"
              onClick={() => draftVersion && onPublish(draftVersion.id)}
              title="Wird sofort live (Test-Modus)"
            >
              Publish (sofort live)
            </button>
            <button
              className="px-3 py-1.5 text-sm border border-rose-300 text-rose-700 rounded hover:bg-rose-50"
              onClick={() => setShowReject(true)}
            >
              Ablehnen
            </button>
          </>
        )}
      </footer>

      {showSubmit && (
        <SubmitDialog
          value={changeSummary}
          onChange={setChangeSummary}
          onCancel={() => setShowSubmit(false)}
          onSubmit={handleSubmit}
        />
      )}

      {showReject && (
        <RejectDialog
          value={rejectReason}
          onChange={setRejectReason}
          onCancel={() => { setShowReject(false); setRejectReason('') }}
          onSubmit={() => {
            if (!draftVersion || !rejectReason.trim()) return
            onReject(draftVersion.id, rejectReason.trim())
            setShowReject(false); setRejectReason('')
          }}
        />
      )}
    </div>
  )
}

function HistoryList({ versions, history }: { versions: RuleVersion[]; history: ApprovalHistoryEntry[] }) {
  return (
    <div className="mt-2 space-y-2 text-xs">
      <div>
        <div className="font-medium text-gray-700 mb-1">Versionen:</div>
        <ul className="space-y-1">
          {versions.map((v) => (
            <li key={v.id} className="bg-white border border-gray-200 rounded p-2">
              <div className="flex items-center gap-2">
                <span className="font-medium">v{v.version_number}</span>
                <span className="px-1.5 py-0.5 bg-gray-100 rounded">{STATUS_LABELS[v.status]}</span>
                {v.is_live && <span className="text-emerald-700">● Live</span>}
                <span className="text-gray-500 ml-auto">
                  {new Date(v.created_at).toLocaleString('de-DE')}
                </span>
              </div>
              {v.change_summary && (
                <div className="mt-1 text-gray-600">Änderung: {v.change_summary}</div>
              )}
              {v.source_citation && (
                <div className="mt-0.5 text-gray-500">Quelle: {v.source_citation}</div>
              )}
            </li>
          ))}
        </ul>
      </div>
      <div>
        <div className="font-medium text-gray-700 mb-1">Approval-Trail:</div>
        <ul className="space-y-0.5">
          {history.map((h) => (
            <li key={h.id} className="text-gray-600">
              {new Date(h.created_at).toLocaleString('de-DE')} · {h.action}
              {h.approver && ` · ${h.approver}`}
              {h.comment && ` — ${h.comment}`}
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

function SubmitDialog({
  value, onChange, onCancel, onSubmit,
}: {
  value: string
  onChange: (s: string) => void
  onCancel: () => void
  onSubmit: () => void
}) {
  return (
    <div className="fixed inset-0 bg-black/30 z-50 flex items-center justify-center" onClick={onCancel}>
      <div className="bg-white rounded-lg shadow-xl w-[520px]" onClick={(e) => e.stopPropagation()}>
        <header className="px-5 py-3 border-b border-gray-200">
          <h3 className="font-semibold">Zur internen Prüfung einreichen</h3>
        </header>
        <div className="p-5">
          <label className="text-xs font-medium text-gray-700">
            Was wurde geändert? <span className="text-rose-600">*</span>
          </label>
          <textarea
            autoFocus
            rows={4}
            className="w-full mt-1 text-sm px-2 py-1.5 border border-gray-300 rounded"
            placeholder="z.B. Schwelle auf 50 MA angehoben (BAG-Urteil X)"
            value={value}
            onChange={(e) => onChange(e.target.value)}
          />
        </div>
        <footer className="px-5 py-3 border-t border-gray-200 flex justify-end gap-2">
          <button className="px-3 py-1.5 text-sm text-gray-600" onClick={onCancel}>Abbrechen</button>
          <button
            className="px-4 py-1.5 text-sm bg-amber-600 text-white rounded disabled:opacity-50"
            disabled={!value.trim()}
            onClick={onSubmit}
          >
            Einreichen
          </button>
        </footer>
      </div>
    </div>
  )
}

function RejectDialog({
  value, onChange, onCancel, onSubmit,
}: {
  value: string
  onChange: (s: string) => void
  onCancel: () => void
  onSubmit: () => void
}) {
  return (
    <div className="fixed inset-0 bg-black/30 z-50 flex items-center justify-center" onClick={onCancel}>
      <div className="bg-white rounded-lg shadow-xl w-[480px]" onClick={(e) => e.stopPropagation()}>
        <header className="px-5 py-3 border-b border-gray-200">
          <h3 className="font-semibold">Draft ablehnen</h3>
        </header>
        <div className="p-5">
          <label className="text-xs font-medium text-gray-700">
            Ablehnungsgrund <span className="text-rose-600">*</span>
          </label>
          <textarea
            autoFocus
            rows={3}
            className="w-full mt-1 text-sm px-2 py-1.5 border border-gray-300 rounded"
            value={value}
            onChange={(e) => onChange(e.target.value)}
          />
        </div>
        <footer className="px-5 py-3 border-t border-gray-200 flex justify-end gap-2">
          <button className="px-3 py-1.5 text-sm text-gray-600" onClick={onCancel}>Abbrechen</button>
          <button
            className="px-4 py-1.5 text-sm bg-rose-600 text-white rounded disabled:opacity-50"
            disabled={!value.trim()}
            onClick={onSubmit}
          >
            Ablehnen
          </button>
        </footer>
      </div>
    </div>
  )
}
