'use client'

import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import NormenTab, { type Norm } from './_components/NormenTab'
import PatternsTab, { type HazardPattern } from './_components/PatternsTab'
import MeasuresTab, { type ProtectiveMeasure } from './_components/MeasuresTab'
import DokumenteTab, { type CEDocument } from './_components/DokumenteTab'

type TabId = 'normen' | 'patterns' | 'measures' | 'dokumente'

const TABS: { id: TabId; label: string }[] = [
  { id: 'normen', label: 'Normen' },
  { id: 'patterns', label: 'Patterns' },
  { id: 'measures', label: 'Massnahmen' },
  { id: 'dokumente', label: 'Dokumente' },
]

export default function IACELibraryPage() {
  const [activeTab, setActiveTab] = useState<TabId>('normen')
  const [norms, setNorms] = useState<Norm[]>([])
  const [patterns, setPatterns] = useState<HazardPattern[]>([])
  const [measures, setMeasures] = useState<ProtectiveMeasure[]>([])
  const [documents, setDocuments] = useState<CEDocument[]>([])
  const [docsLoading, setDocsLoading] = useState(false)
  const [docsFetched, setDocsFetched] = useState(false)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function load() {
      try {
        const [normsRes, patternsRes, measuresRes] = await Promise.all([
          fetch('/api/sdk/v1/iace/norms-library'),
          fetch('/api/sdk/v1/iace/hazard-patterns'),
          fetch('/api/sdk/v1/iace/protective-measures-library'),
        ])
        if (normsRes.ok) {
          const data = await normsRes.json()
          setNorms(data.norms || [])
        }
        if (patternsRes.ok) {
          const data = await patternsRes.json()
          setPatterns(data.patterns || [])
        }
        if (measuresRes.ok) {
          const data = await measuresRes.json()
          setMeasures(data.protective_measures || [])
        }
      } catch (err) {
        console.error('Failed to load IACE library data:', err)
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  // Lazy-load documents on tab switch
  useEffect(() => {
    if (activeTab !== 'dokumente' || docsFetched) return
    setDocsLoading(true)
    fetch('/api/sdk/v1/iace/ce-corpus-documents')
      .then((r) => r.ok ? r.json() : null)
      .then((data) => { if (data) setDocuments(data.documents || []) })
      .catch(() => {})
      .finally(() => { setDocsLoading(false); setDocsFetched(true) })
  }, [activeTab, docsFetched])

  const counts: Record<TabId, number> = {
    normen: norms.length,
    patterns: patterns.length,
    measures: measures.length,
    dokumente: documents.length,
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600" />
      </div>
    )
  }

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      {/* Back link + Header */}
      <div>
        <Link
          href="/sdk/iace"
          className="inline-flex items-center gap-1 text-sm text-purple-600 hover:text-purple-800 mb-3"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
          Zurueck zur IACE-Uebersicht
        </Link>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
          Bibliothek
        </h1>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
          Normen, Hazard Patterns und Schutzmassnahmen fuer die CE-Konformitaetsbewertung
        </p>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="flex gap-1" aria-label="Library tabs">
          {TABS.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`px-4 py-2.5 text-sm font-medium rounded-t-lg transition-colors ${
                activeTab === tab.id
                  ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 border-b-2 border-purple-600'
                  : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800'
              }`}
            >
              {tab.label}
              <span className={`ml-1.5 inline-flex items-center px-1.5 py-0.5 rounded-full text-xs ${
                activeTab === tab.id
                  ? 'bg-purple-200 dark:bg-purple-800 text-purple-800 dark:text-purple-200'
                  : 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
              }`}>
                {counts[tab.id]}
              </span>
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
        {activeTab === 'normen' && <NormenTab norms={norms} />}
        {activeTab === 'patterns' && <PatternsTab patterns={patterns} />}
        {activeTab === 'measures' && <MeasuresTab measures={measures} />}
        {activeTab === 'dokumente' && <DokumenteTab documents={documents} loading={docsLoading} />}
      </div>
    </div>
  )
}
