'use client'

import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { mapControlTypeToDisplay, mapStatusToDisplay, DisplayControl } from './_types'
import { ControlCard } from './_components/ControlCard'
import { AddControlForm } from './_components/AddControlForm'
import { LoadingSkeleton } from './_components/LoadingSkeleton'
import { StatsCards } from './_components/StatsCards'
import { FilterBar } from './_components/FilterBar'
import { RAGPanel } from './_components/RAGPanel'
import { useControlsData } from './_hooks/useControlsData'
import { useRAGSuggestions } from './_hooks/useRAGSuggestions'

// ---------------------------------------------------------------------------
// Transition Error Banner
// ---------------------------------------------------------------------------

function TransitionErrorBanner({
  controlId,
  violations,
  onDismiss,
}: {
  controlId: string
  violations: string[]
  onDismiss: () => void
}) {
  return (
    <div className="p-4 bg-orange-50 border border-orange-200 rounded-lg">
      <div className="flex items-start justify-between">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-orange-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
          <div>
            <h4 className="font-medium text-orange-800">Status-Transition blockiert ({controlId})</h4>
            <ul className="mt-2 space-y-1">
              {violations.map((v, i) => (
                <li key={i} className="text-sm text-orange-700 flex items-start gap-2">
                  <span className="text-orange-400 mt-0.5">•</span>
                  <span>{v}</span>
                </li>
              ))}
            </ul>
            <a href="/sdk/evidence" className="mt-2 inline-block text-sm text-purple-600 hover:text-purple-700 font-medium">
              Evidence hinzufuegen →
            </a>
          </div>
        </div>
        <button onClick={onDismiss} className="text-orange-400 hover:text-orange-600 ml-4">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
    </div>
  )
}

// ---------------------------------------------------------------------------
// Main Page
// ---------------------------------------------------------------------------

export default function ControlsPage() {
  const router = useRouter()
  const [filter, setFilter] = useState<string>('all')
  const [showAddForm, setShowAddForm] = useState(false)
  const [transitionError, setTransitionError] = useState<{ controlId: string; violations: string[] } | null>(null)

  const {
    state, dispatch, loading, error, setError,
    effectivenessMap, evidenceMap,
    handleStatusChange: _handleStatusChange,
    handleEffectivenessChange,
    handleAddControl,
  } = useControlsData()

  const {
    ragLoading, ragSuggestions, showRagPanel, setShowRagPanel,
    selectedRequirementId, setSelectedRequirementId,
    suggestControlsFromRAG, addSuggestedControl,
  } = useRAGSuggestions(setError)

  // Wrap status change to capture 409 transition errors
  const handleStatusChange = async (controlId: string, newStatus: import('@/lib/sdk').ImplementationStatus) => {
    const oldControl = state.controls.find(c => c.id === controlId)
    const oldStatus = oldControl?.implementationStatus

    dispatch({ type: 'UPDATE_CONTROL', payload: { id: controlId, data: { implementationStatus: newStatus } } })

    try {
      const res = await fetch(`/api/sdk/v1/compliance/controls/${controlId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ implementation_status: newStatus }),
      })

      if (!res.ok) {
        if (oldStatus) dispatch({ type: 'UPDATE_CONTROL', payload: { id: controlId, data: { implementationStatus: oldStatus } } })
        const err = await res.json().catch(() => ({ detail: 'Status-Aenderung fehlgeschlagen' }))
        if (res.status === 409 && err.detail?.violations) {
          setTransitionError({ controlId, violations: err.detail.violations })
        } else {
          const msg = typeof err.detail === 'string' ? err.detail : err.detail?.error || 'Status-Aenderung fehlgeschlagen'
          setError(msg)
        }
      } else if (transitionError?.controlId === controlId) {
        setTransitionError(null)
      }
    } catch {
      if (oldStatus) dispatch({ type: 'UPDATE_CONTROL', payload: { id: controlId, data: { implementationStatus: oldStatus } } })
      setError('Netzwerkfehler bei Status-Aenderung')
    }
  }

  // Build display controls
  const displayControls: DisplayControl[] = state.controls.map(ctrl => {
    const effectivenessPercent = effectivenessMap[ctrl.id] ??
      (ctrl.implementationStatus === 'IMPLEMENTED' ? 85 : ctrl.implementationStatus === 'PARTIAL' ? 50 : 0)
    return {
      id: ctrl.id,
      name: ctrl.name,
      description: ctrl.description,
      type: ctrl.type,
      category: ctrl.category,
      implementationStatus: ctrl.implementationStatus,
      evidence: ctrl.evidence,
      owner: ctrl.owner,
      dueDate: ctrl.dueDate,
      code: ctrl.id,
      displayType: 'preventive' as import('./_types').DisplayControlType,
      displayCategory: mapControlTypeToDisplay(ctrl.type),
      displayStatus: mapStatusToDisplay(ctrl.implementationStatus),
      effectivenessPercent,
      linkedRequirements: [],
      linkedEvidence: evidenceMap[ctrl.id] || [],
      lastReview: new Date(),
    }
  })

  const filteredControls = filter === 'all'
    ? displayControls
    : displayControls.filter(c => c.displayStatus === filter || c.displayType === filter || c.displayCategory === filter)

  const implementedCount = displayControls.filter(c => c.displayStatus === 'implemented').length
  const avgEffectiveness = displayControls.length > 0
    ? Math.round(displayControls.reduce((sum, c) => sum + c.effectivenessPercent, 0) / displayControls.length)
    : 0
  const partialCount = displayControls.filter(c => c.displayStatus === 'partial').length
  const stepInfo = STEP_EXPLANATIONS['controls']

  return (
    <div className="space-y-6">
      <StepHeader stepId="controls" title={stepInfo.title} description={stepInfo.description} explanation={stepInfo.explanation} tips={stepInfo.tips}>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowRagPanel(!showRagPanel)}
            className="flex items-center gap-2 px-4 py-2 bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors border border-purple-200"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
            KI-Controls aus RAG
          </button>
          <button
            onClick={() => setShowAddForm(true)}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Kontrolle hinzufuegen
          </button>
        </div>
      </StepHeader>

      {showAddForm && (
        <AddControlForm
          onSubmit={(data) => { handleAddControl(data); setShowAddForm(false) }}
          onCancel={() => setShowAddForm(false)}
        />
      )}

      {showRagPanel && (
        <RAGPanel
          selectedRequirementId={selectedRequirementId}
          onSelectedRequirementIdChange={setSelectedRequirementId}
          requirements={state.requirements}
          onSuggestControls={suggestControlsFromRAG}
          ragLoading={ragLoading}
          ragSuggestions={ragSuggestions}
          onAddSuggestion={addSuggestedControl}
          onClose={() => setShowRagPanel(false)}
        />
      )}

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="text-red-500 hover:text-red-700">&times;</button>
        </div>
      )}

      {transitionError && (
        <TransitionErrorBanner
          controlId={transitionError.controlId}
          violations={transitionError.violations}
          onDismiss={() => setTransitionError(null)}
        />
      )}

      {state.requirements.length === 0 && !loading && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-amber-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <div>
              <h4 className="font-medium text-amber-800">Keine Anforderungen definiert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Bitte definieren Sie zuerst Anforderungen, um die zugehoerigen Kontrollen zu laden.
              </p>
            </div>
          </div>
        </div>
      )}

      <StatsCards total={displayControls.length} implementedCount={implementedCount} avgEffectiveness={avgEffectiveness} partialCount={partialCount} />

      <FilterBar filter={filter} onFilterChange={setFilter} />

      {loading && <LoadingSkeleton />}

      {!loading && (
        <div className="space-y-4">
          {filteredControls.map(control => (
            <ControlCard
              key={control.id}
              control={control}
              onStatusChange={(status) => handleStatusChange(control.id, status)}
              onEffectivenessChange={(effectiveness) => handleEffectivenessChange(control.id, effectiveness)}
              onLinkEvidence={() => router.push(`/sdk/evidence?control_id=${control.id}`)}
            />
          ))}
        </div>
      )}

      {!loading && filteredControls.length === 0 && state.requirements.length > 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Kontrollen gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder fuegen Sie neue Kontrollen hinzu.</p>
        </div>
      )}
    </div>
  )
}
