'use client'

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

export default function ControlsPage() {
  const router = useRouter()
  const [filter, setFilter] = useState<string>('all')
  const [showAddForm, setShowAddForm] = useState(false)

  const {
    state,
    loading,
    error,
    setError,
    displayControls,
    transitionError,
    setTransitionError,
    handleStatusChange,
    handleEffectivenessChange,
    handleAddControl,
    addSuggestedControl,
  } = useControlsData()

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

  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={(s) => { addSuggestedControl(s); removeSuggestion(s.control_id) }}
          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>
  )
}
