'use client'

/**
 * Pro-Tenant Override-Liste: zeigt alle Overrides der eigenen Kanzlei
 * + Add/Edit/Delete.
 *
 * Reuse: Backend /tenant-rule-overrides (upsert via POST, delete via DELETE).
 * Read-only Klassifikation wird aus der live_version der Regel gezogen.
 */

import { useMemo, useState } from 'react'
import type {
  Classification, Rule, RuleVersion, TenantRuleOverride,
} from '../_types'
import { CLASSIFICATION_LABELS } from '../_types'

interface Props {
  rules: Rule[]
  liveVersionsByRule: Record<string, RuleVersion | undefined>
  overrides: TenantRuleOverride[]
  onUpsert: (payload: {
    rule_id: string
    override_classification: Classification | null
    reason: string
  }) => Promise<void>
  onDelete: (overrideId: string) => Promise<void>
}

export default function TenantOverrideList({
  rules, liveVersionsByRule, overrides, onUpsert, onDelete,
}: Props) {
  const [filter, setFilter] = useState('')
  const [showAdd, setShowAdd] = useState(false)
  const [editing, setEditing] = useState<TenantRuleOverride | null>(null)
  const [confirmDelete, setConfirmDelete] = useState<TenantRuleOverride | null>(null)

  const rulesById = useMemo(
    () => Object.fromEntries(rules.map((r) => [r.id, r])),
    [rules],
  )

  const rows = useMemo(() => {
    return overrides
      .map((o) => {
        const rule = rulesById[o.rule_id]
        const live = liveVersionsByRule[o.rule_id]
        return { override: o, rule, live }
      })
      .filter(({ rule }) => {
        if (!filter.trim()) return true
        const q = filter.toLowerCase()
        return (
          (rule?.title || '').toLowerCase().includes(q) ||
          (rule?.document_type || '').toLowerCase().includes(q) ||
          (rule?.rule_key || '').toLowerCase().includes(q)
        )
      })
  }, [overrides, rulesById, liveVersionsByRule, filter])

  return (
    <div className="h-full flex flex-col overflow-hidden bg-white">
      <header className="px-5 py-3 border-b border-gray-200 flex items-center justify-between gap-3">
        <div className="min-w-0">
          <h2 className="text-base font-semibold text-gray-800">Meine Overrides</h2>
          <p className="text-xs text-gray-500">
            Globale Regeln, die für meine Mandanten abweichend gelten.
            {overrides.length > 0 && ` ${overrides.length} aktiv.`}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <input
            type="text"
            placeholder="Suchen…"
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            className="text-sm px-2 py-1.5 border border-gray-300 rounded"
          />
          <button
            className="px-3 py-1.5 text-sm bg-amber-600 text-white rounded hover:bg-amber-700"
            onClick={() => setShowAdd(true)}
          >
            + Override hinzufügen
          </button>
        </div>
      </header>

      <div className="flex-1 overflow-auto">
        {rows.length === 0 ? (
          <div className="p-8 text-center text-sm text-gray-500">
            {overrides.length === 0
              ? 'Noch keine Overrides angelegt. Klicke oben rechts „+ Override hinzufügen“, um die globale Klassifikation einer Regel für deine Kanzlei abweichend zu setzen.'
              : 'Keine Treffer für den Filter.'}
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-gray-50 text-xs uppercase text-gray-600 sticky top-0">
              <tr>
                <th className="px-5 py-2 text-left">Regel</th>
                <th className="px-3 py-2 text-left">Original</th>
                <th className="px-3 py-2 text-left">Mein Override</th>
                <th className="px-3 py-2 text-left">Grund</th>
                <th className="px-3 py-2 text-left">Erstellt</th>
                <th className="px-3 py-2 text-left">Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(({ override, rule, live }) => (
                <tr key={override.id} className="border-t border-gray-100 hover:bg-gray-50">
                  <td className="px-5 py-2">
                    <div className="font-medium text-gray-800">{rule?.title ?? '(unbekannt)'}</div>
                    <div className="text-xs text-gray-500">
                      <code>{rule?.document_type ?? '?'}</code> · {rule?.rule_key ?? '?'}
                    </div>
                  </td>
                  <td className="px-3 py-2">
                    {live ? (
                      <ClassChip classification={live.classification} />
                    ) : (
                      <span className="text-xs text-gray-400">—</span>
                    )}
                  </td>
                  <td className="px-3 py-2">
                    {override.override_classification ? (
                      <ClassChip classification={override.override_classification} />
                    ) : (
                      <span className="px-1.5 py-0.5 text-xs rounded bg-gray-200 text-gray-700">
                        deaktiviert
                      </span>
                    )}
                  </td>
                  <td className="px-3 py-2 text-xs text-gray-700 max-w-xs">
                    <span className="line-clamp-2">{override.reason}</span>
                  </td>
                  <td className="px-3 py-2 text-xs text-gray-500 whitespace-nowrap">
                    {new Date(override.created_at).toLocaleDateString('de-DE')}
                    {override.created_by && (
                      <div className="text-[10px]">{override.created_by}</div>
                    )}
                  </td>
                  <td className="px-3 py-2">
                    <div className="flex items-center gap-1">
                      <button
                        className="text-xs px-2 py-1 border border-gray-300 rounded hover:bg-gray-100"
                        onClick={() => setEditing(override)}
                      >
                        Bearbeiten
                      </button>
                      <button
                        className="text-xs px-2 py-1 border border-rose-300 text-rose-700 rounded hover:bg-rose-50"
                        onClick={() => setConfirmDelete(override)}
                      >
                        Löschen
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {showAdd && (
        <OverrideDialog
          title="Neuen Override anlegen"
          rules={rules}
          liveVersionsByRule={liveVersionsByRule}
          existingOverrideRuleIds={new Set(overrides.map((o) => o.rule_id))}
          onCancel={() => setShowAdd(false)}
          onSubmit={async (payload) => {
            await onUpsert(payload)
            setShowAdd(false)
          }}
        />
      )}

      {editing && (
        <OverrideDialog
          title="Override bearbeiten"
          rules={rules}
          liveVersionsByRule={liveVersionsByRule}
          existingOverrideRuleIds={new Set()}
          initial={editing}
          fixedRuleId={editing.rule_id}
          onCancel={() => setEditing(null)}
          onSubmit={async (payload) => {
            await onUpsert(payload)
            setEditing(null)
          }}
        />
      )}

      {confirmDelete && (
        <ConfirmDialog
          message={`Override für „${rulesById[confirmDelete.rule_id]?.title || 'Regel'}" wirklich löschen?`}
          onCancel={() => setConfirmDelete(null)}
          onConfirm={async () => {
            await onDelete(confirmDelete.id)
            setConfirmDelete(null)
          }}
        />
      )}
    </div>
  )
}

function ClassChip({ classification }: { classification: Classification }) {
  const colorMap = {
    required: 'bg-rose-100 text-rose-800 border-rose-300',
    recommended: 'bg-amber-100 text-amber-800 border-amber-300',
    optional: 'bg-slate-100 text-slate-700 border-slate-300',
  } as const
  return (
    <span className={`px-1.5 py-0.5 text-xs rounded border ${colorMap[classification]}`}>
      {CLASSIFICATION_LABELS[classification]}
    </span>
  )
}

interface OverrideDialogProps {
  title: string
  rules: Rule[]
  liveVersionsByRule: Record<string, RuleVersion | undefined>
  existingOverrideRuleIds: Set<string>
  initial?: TenantRuleOverride
  fixedRuleId?: string
  onCancel: () => void
  onSubmit: (payload: {
    rule_id: string
    override_classification: Classification | null
    reason: string
  }) => Promise<void>
}

function OverrideDialog({
  title, rules, liveVersionsByRule, existingOverrideRuleIds,
  initial, fixedRuleId, onCancel, onSubmit,
}: OverrideDialogProps) {
  const [ruleId, setRuleId] = useState<string>(
    fixedRuleId ?? initial?.rule_id ?? '',
  )
  const [classification, setClassification] = useState<Classification | 'disabled'>(
    initial?.override_classification ?? 'optional',
  )
  const [reason, setReason] = useState<string>(initial?.reason ?? '')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const availableRules = useMemo(() => {
    if (fixedRuleId) {
      // Edit-Mode: nur die eine Regel zeigen
      return rules.filter((r) => r.id === fixedRuleId)
    }
    return rules.filter((r) => !existingOverrideRuleIds.has(r.id))
  }, [rules, existingOverrideRuleIds, fixedRuleId])

  const selectedRule = rules.find((r) => r.id === ruleId)
  const selectedLive = ruleId ? liveVersionsByRule[ruleId] : undefined

  const canSubmit = !!ruleId && reason.trim().length > 0 && !submitting

  const handleSubmit = async () => {
    setSubmitting(true)
    setError(null)
    try {
      await onSubmit({
        rule_id: ruleId,
        override_classification: classification === 'disabled' ? null : classification,
        reason: reason.trim(),
      })
    } catch (e) {
      setError((e as Error).message)
    } finally {
      setSubmitting(false)
    }
  }

  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-[560px] max-h-[90vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="px-5 py-3 border-b border-gray-200">
          <h3 className="font-semibold">{title}</h3>
        </header>
        <div className="p-5 space-y-4 overflow-y-auto">
          <section>
            <label className="text-xs font-medium text-gray-700 block mb-1">
              Regel <span className="text-rose-600">*</span>
            </label>
            <select
              className="w-full text-sm px-2 py-1.5 border border-gray-300 rounded bg-white"
              value={ruleId}
              disabled={!!fixedRuleId}
              onChange={(e) => setRuleId(e.target.value)}
            >
              <option value="">— Regel wählen —</option>
              {availableRules.map((r) => (
                <option key={r.id} value={r.id}>{r.title} ({r.document_type})</option>
              ))}
            </select>
            {selectedRule && selectedLive && (
              <div className="text-xs text-gray-600 mt-1">
                Original-Klassifikation: <ClassChip classification={selectedLive.classification} />{' '}
                · Quelle: {selectedLive.source_citation}
              </div>
            )}
          </section>

          <section>
            <label className="text-xs font-medium text-gray-700 block mb-1">
              Meine abweichende Klassifikation
            </label>
            <div className="space-y-1">
              {(['required', 'recommended', 'optional', 'disabled'] as const).map((c) => (
                <label key={c} className="flex items-center gap-2 text-sm">
                  <input
                    type="radio"
                    name="classification"
                    value={c}
                    checked={classification === c}
                    onChange={() => setClassification(c)}
                  />
                  {c === 'disabled' ? (
                    <span className="text-gray-700">
                      Deaktivieren (Regel gilt für meine Mandanten gar nicht)
                    </span>
                  ) : (
                    <ClassChip classification={c} />
                  )}
                </label>
              ))}
            </div>
          </section>

          <section>
            <label className="text-xs font-medium text-gray-700 block mb-1">
              Grund <span className="text-rose-600">*</span>
            </label>
            <textarea
              rows={4}
              className="w-full text-sm px-2 py-1.5 border border-gray-300 rounded"
              placeholder="Warum gilt diese Regel bei meinen Mandanten abweichend? (z.B. Bei Maschinenbauern haben wir CRA-Doku statt isolierter ISMS-Manuale.)"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
            />
          </section>

          {error && (
            <div className="bg-rose-50 border border-rose-200 text-rose-800 text-sm px-3 py-2 rounded">
              {error}
            </div>
          )}
        </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 hover:bg-amber-700 disabled:opacity-50"
            disabled={!canSubmit}
            onClick={handleSubmit}
          >
            {submitting ? 'Speichere…' : 'Speichern'}
          </button>
        </footer>
      </div>
    </div>
  )
}

function ConfirmDialog({
  message, onCancel, onConfirm,
}: {
  message: string
  onCancel: () => void
  onConfirm: () => Promise<void>
}) {
  const [busy, setBusy] = useState(false)
  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-[420px]" onClick={(e) => e.stopPropagation()}>
        <div className="p-5 text-sm text-gray-800">{message}</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={busy}
            onClick={async () => { setBusy(true); await onConfirm(); setBusy(false) }}
          >
            {busy ? 'Lösche…' : 'Löschen'}
          </button>
        </footer>
      </div>
    </div>
  )
}
