'use client'

/**
 * Template Rule Editor — Editorial-UI fuer Anwaelte/DSBs.
 *
 * Architektur:
 * - Links: RuleList mit Filter
 * - Rechts: RuleEditor mit Klassifikation, Condition-Builder, Source-Citation,
 *   Approval-Workflow (draft → review → approved → published)
 *
 * Backend: /api/sdk/v1/compliance/template-rules + /template-rule-versions/*
 */

import { useEffect, useState, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
import StepHeader from '@/components/sdk/StepHeader/StepHeader'
import { useRuleEditorActions } from './_hooks/useRuleEditorActions'
import type {
  ApprovalHistoryEntry, Classification, Rule, RuleCondition, RuleVersion,
  TenantRuleOverride,
} from './_types'
import RuleList from './_components/RuleList'
import RuleEditor from './_components/RuleEditor'
import TenantOverrideList from './_components/TenantOverrideList'

type Tab = 'rules' | 'overrides'

export default function TemplateRuleEditorPage() {
  useSDK()

  const actions = useRuleEditorActions()

  const [tab, setTab] = useState<Tab>('rules')
  const [rules, setRules] = useState<Rule[]>([])
  const [liveVersionsByRule, setLiveVersionsByRule] = useState<Record<string, RuleVersion | undefined>>({})
  const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null)
  const [selectedVersions, setSelectedVersions] = useState<RuleVersion[]>([])
  const [selectedHistory, setSelectedHistory] = useState<ApprovalHistoryEntry[]>([])
  const [overrides, setOverrides] = useState<TenantRuleOverride[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Initial: Regeln laden + Live-Versions
  const loadRules = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const list = await actions.listRules()
      setRules(list)
      const byRule: Record<string, RuleVersion | undefined> = {}
      // Live-Versionen parallel
      await Promise.all(
        list.map(async (r) => {
          try {
            const versions = await actions.listVersions(r.id)
            const live = versions.find((v) => v.is_live)
            byRule[r.id] = live
          } catch {
            byRule[r.id] = undefined
          }
        }),
      )
      setLiveVersionsByRule(byRule)
      if (list.length > 0 && !selectedRuleId) {
        setSelectedRuleId(list[0].id)
      }
    } catch (e) {
      setError((e as Error).message)
    } finally {
      setLoading(false)
    }
  }, [actions, selectedRuleId])

  // Bei Selektions-Wechsel: Versions + History laden
  const loadSelected = useCallback(async () => {
    if (!selectedRuleId) {
      setSelectedVersions([])
      setSelectedHistory([])
      return
    }
    try {
      const versions = await actions.listVersions(selectedRuleId)
      setSelectedVersions(versions)
      const live = versions.find((v) => v.is_live)
      if (live) {
        const history = await actions.getApprovalHistory(live.id)
        setSelectedHistory(history)
      } else {
        setSelectedHistory([])
      }
    } catch (e) {
      setError((e as Error).message)
    }
  }, [actions, selectedRuleId])

  useEffect(() => { loadRules() }, [])
  useEffect(() => { loadSelected() }, [selectedRuleId])

  const handleCreateDraft = async (payload: {
    classification: Classification
    conditions: RuleCondition
    source_citation: string
    rationale?: string | null
  }) => {
    if (!selectedRuleId) return
    try {
      await actions.createDraftVersion(selectedRuleId, payload)
      await loadSelected()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  const handleUpdateDraft = async (versionId: string, patch: {
    classification?: Classification
    conditions?: RuleCondition
    source_citation?: string
    rationale?: string | null
  }) => {
    try {
      await actions.updateDraftVersion(versionId, patch)
      await loadSelected()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  const handleSubmitForReview = async (versionId: string, changeSummary: string) => {
    try {
      await actions.submitForReview(versionId, { change_summary: changeSummary })
      await loadSelected()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  const handleApprove = async (versionId: string) => {
    try {
      await actions.approveVersion(versionId)
      await loadSelected()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  const handlePublish = async (versionId: string) => {
    try {
      await actions.publishVersion(versionId)
      await loadRules()
      await loadSelected()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  const handleReject = async (versionId: string, reason: string) => {
    try {
      await actions.rejectVersion(versionId, { rejection_reason: reason })
      await loadSelected()
    } catch (e) {
      setError((e as Error).message)
    }
  }

  const loadOverrides = useCallback(async () => {
    try {
      const list = await actions.listOverrides()
      setOverrides(list)
    } catch (e) {
      setError((e as Error).message)
    }
  }, [actions])

  useEffect(() => { loadOverrides() }, [])

  const handleUpsertOverride = async (payload: {
    rule_id: string
    override_classification: Classification | null
    reason: string
  }) => {
    await actions.upsertOverride(payload)
    await loadOverrides()
  }

  const handleDeleteOverride = async (overrideId: string) => {
    await actions.deleteOverride(overrideId)
    await loadOverrides()
  }

  const selectedRule = rules.find((r) => r.id === selectedRuleId)

  return (
    <div className="h-full flex flex-col bg-white">
      <StepHeader
        stepId="template-rule-editor"
        title="Empfehlungs-Regeln"
        description="Editorial-UI für profilbasierte Dokument-Empfehlungen. Anwälte/DSBs editieren globale Regeln mit Approval-Workflow + Quellen-Attribution."
      />
      {error && (
        <div className="px-5 py-2 bg-rose-50 border-b border-rose-200 text-sm text-rose-800">
          {error}
        </div>
      )}
      {loading && (
        <div className="p-5 text-sm text-gray-500">Lade Regeln…</div>
      )}
      {!loading && (
        <>
          <nav className="px-5 border-b border-gray-200 bg-white flex gap-1">
            <TabButton active={tab === 'rules'} onClick={() => setTab('rules')}>
              Globale Regeln <span className="text-xs text-gray-500">({rules.length})</span>
            </TabButton>
            <TabButton active={tab === 'overrides'} onClick={() => setTab('overrides')}>
              Meine Overrides <span className="text-xs text-gray-500">({overrides.length})</span>
            </TabButton>
          </nav>
          {tab === 'rules' && (
            <div className="flex-1 grid grid-cols-[320px_1fr] overflow-hidden">
              <RuleList
                rules={rules}
                versionsByRule={liveVersionsByRule}
                selectedRuleId={selectedRuleId}
                onSelectRule={setSelectedRuleId}
              />
              {selectedRule ? (
                <RuleEditor
                  rule={selectedRule}
                  versions={selectedVersions}
                  history={selectedHistory}
                  onCreateDraft={handleCreateDraft}
                  onUpdateDraft={handleUpdateDraft}
                  onSubmitForReview={handleSubmitForReview}
                  onApprove={handleApprove}
                  onPublish={handlePublish}
                  onReject={handleReject}
                />
              ) : (
                <div className="h-full grid place-items-center text-sm text-gray-500">
                  Wähle links eine Regel zum Bearbeiten.
                </div>
              )}
            </div>
          )}
          {tab === 'overrides' && (
            <div className="flex-1 overflow-hidden">
              <TenantOverrideList
                rules={rules}
                liveVersionsByRule={liveVersionsByRule}
                overrides={overrides}
                onUpsert={handleUpsertOverride}
                onDelete={handleDeleteOverride}
              />
            </div>
          )}
        </>
      )}
    </div>
  )
}

function TabButton({
  active, onClick, children,
}: {
  active: boolean
  onClick: () => void
  children: React.ReactNode
}) {
  return (
    <button
      className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
        active
          ? 'border-amber-500 text-gray-900'
          : 'border-transparent text-gray-600 hover:text-gray-800 hover:border-gray-300'
      }`}
      onClick={onClick}
    >
      {children}
    </button>
  )
}
