'use client'

import React from 'react'
import Link from 'next/link'
import { usePathname, useParams } from 'next/navigation'
import IACEFlowFAB from './[projectId]/_components/IACEFlowFAB'

const IACE_NAV_ITEMS = [
  { id: 'overview', label: 'Uebersicht', href: '', icon: 'grid' },
  { id: 'architektur', label: 'Architektur & Datenfluss', href: '/architektur', icon: 'activity' },
  { id: 'order', label: 'Auftrag', href: '/order', icon: 'briefcase' },
  { id: 'interview', label: 'Grenzen & Verwendung', href: '/interview', icon: 'chat' },
  { id: 'operational-states', label: 'Betriebszustaende', href: '/operational-states', icon: 'activity' },
  { id: 'norms', label: 'Normenrecherche', href: '/norms', icon: 'book' },
  { id: 'components', label: 'Komponenten', href: '/components', icon: 'cube' },
  { id: 'hazards', label: 'Hazard Log', href: '/hazards', icon: 'warning' },
  { id: 'risikobewertung', label: 'Risikobewertung', href: '/risikobewertung', icon: 'activity' },
  { id: 'mitigations', label: 'Massnahmen', href: '/mitigations', icon: 'shield' },
  { id: 'clarifications', label: 'Klärungen', href: '/clarifications', icon: 'chat' },
  { id: 'verification', label: 'Verifikation', href: '/verification', icon: 'check' },
  { id: 'customer-standards', label: 'Kundenstandards', href: '/customer-standards', icon: 'building' },
  { id: 'evidence', label: 'Nachweise', href: '/evidence', icon: 'document' },
  { id: 'tech-file', label: 'CE-Akte', href: '/tech-file', icon: 'folder' },
]

const IACE_EXTRA_ITEMS = [
  { id: 'cra', label: 'CRA / Cyber', href: '/cra', icon: 'shield' },
  { id: 'fmea', label: 'FMEA', href: '/fmea', icon: 'grid' },
  { id: 'knowledge-graph', label: 'Knowledge Graph', href: '/knowledge-graph', icon: 'activity' },
  { id: 'classification', label: 'Klassifikation', href: '/classification', icon: 'tag' },
  { id: 'monitoring', label: 'Monitoring', href: '/monitoring', icon: 'activity' },
  { id: 'benchmark', label: 'Benchmark', href: '/benchmark', icon: 'check' },
]

function NavIcon({ icon, className }: { icon: string; className?: string }) {
  const cls = className || 'w-5 h-5'
  switch (icon) {
    case 'grid':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
        </svg>
      )
    case 'cube':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
        </svg>
      )
    case 'tag':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
        </svg>
      )
    case 'warning':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <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>
      )
    case 'shield':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <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>
      )
    case 'check':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      )
    case 'building':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0H5m14 0h2m-16 0H3m4-4h2m-2-4h2m-2-4h2m4 8h2m-2-4h2m-2-4h2" />
        </svg>
      )
    case 'document':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
      )
    case 'folder':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
        </svg>
      )
    case 'activity':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
        </svg>
      )
    case 'briefcase':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m10 0H6a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V8a2 2 0 00-2-2z" />
        </svg>
      )
    case 'chat':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
        </svg>
      )
    case 'book':
      return (
        <svg className={cls} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
        </svg>
      )
    default:
      return null
  }
}

export default function IACELayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const params = useParams()
  const projectId = params?.projectId as string | undefined
  const [projectName, setProjectName] = React.useState('')
  const [variantInfo, setVariantInfo] = React.useState<{
    parentProjectId?: string; parentName?: string; variantCount?: number
  }>({})
  const [openClarifications, setOpenClarifications] = React.useState<number | null>(null)

  // Poll the clarifications endpoint so the sidebar always shows the
  // current "offene Klaerungen" counter. Refresh whenever the user
  // navigates back to this layout (i.e. when pathname changes).
  React.useEffect(() => {
    if (!projectId) return
    let cancelled = false
    fetch(`/api/sdk/v1/iace/projects/${projectId}/clarifications`)
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (cancelled || !d || typeof d.open_count !== 'number') return
        setOpenClarifications(d.open_count)
      })
      .catch(() => {})
    return () => { cancelled = true }
  }, [projectId, pathname])

  React.useEffect(() => {
    if (!projectId) return
    fetch(`/api/sdk/v1/iace/projects/${projectId}`)
      .then(r => r.ok ? r.json() : null)
      .then(async (d) => {
        if (!d?.machine_name) return
        setProjectName(d.machine_name)
        // Resolve variant info
        if (d.parent_project_id) {
          try {
            const pRes = await fetch(`/api/sdk/v1/iace/projects/${d.parent_project_id}`)
            if (pRes.ok) {
              const pj = await pRes.json()
              setVariantInfo({ parentProjectId: d.parent_project_id, parentName: pj.machine_name })
            } else {
              setVariantInfo({ parentProjectId: d.parent_project_id })
            }
          } catch { setVariantInfo({ parentProjectId: d.parent_project_id }) }
        } else {
          // Check if this project has variants
          try {
            const vRes = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variants`)
            if (vRes.ok) {
              const vj = await vRes.json()
              const list = vj.variants || vj.projects || []
              if (list.length > 0) setVariantInfo({ variantCount: list.length })
            }
          } catch { /* no variants endpoint yet */ }
        }
      })
      .catch(() => {})
  }, [projectId])

  const basePath = projectId ? `/sdk/iace/${projectId}` : ''

  const isActive = (href: string) => {
    if (!projectId) return false
    const fullPath = `${basePath}${href}`
    if (href === '') {
      return pathname === fullPath
    }
    return pathname.startsWith(fullPath)
  }

  return (
    <div className="flex h-full min-h-screen">
      {/* Sidebar - only show when inside a project */}
      {projectId && (
        <aside className="w-[200px] bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex-shrink-0">
          <div className="p-4 border-b border-gray-200 dark:border-gray-700">
            <Link
              href="/sdk/iace"
              className="text-xs text-purple-600 hover:text-purple-700 font-medium flex items-center gap-1"
            >
              <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              Alle Projekte
            </Link>
            {projectName && (
              <p className="text-xs font-bold text-purple-700 dark:text-purple-400 mt-2 truncate" title={projectName}>
                {projectName}
              </p>
            )}
            {variantInfo.parentProjectId && (
              <Link
                href={`/sdk/iace/${variantInfo.parentProjectId}`}
                className="mt-1 flex items-center gap-1 text-[10px] text-orange-600 hover:text-orange-700 dark:text-orange-400 truncate"
                title={variantInfo.parentName ? `Variante von: ${variantInfo.parentName}` : 'Variante'}
              >
                <svg className="w-3 h-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16V4m0 0L3 8m4-4l4 4" />
                </svg>
                Variante von: {variantInfo.parentName || 'Basis'}
              </Link>
            )}
            {variantInfo.variantCount != null && variantInfo.variantCount > 0 && (
              <p className="mt-1 text-[10px] text-gray-400">({variantInfo.variantCount} Varianten)</p>
            )}
            <p className="text-[10px] text-gray-400 mt-0.5">CE-Compliance</p>
            <Link
              href="/sdk/iace/lines"
              className="mt-2 flex items-center gap-1.5 text-xs text-gray-500 hover:text-purple-600 dark:text-gray-400 dark:hover:text-purple-400 transition-colors"
            >
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
              </svg>
              Produktionslinien
            </Link>
          </div>
          <nav className="p-2 space-y-0.5">
            {IACE_NAV_ITEMS.map((item) => (
              <Link
                key={item.id}
                href={`${basePath}${item.href}`}
                className={`flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                  isActive(item.href)
                    ? 'bg-purple-50 text-purple-700 dark:bg-purple-900/50 dark:text-purple-300'
                    : 'text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700'
                }`}
              >
                <NavIcon icon={item.icon} className="w-4 h-4 flex-shrink-0" />
                <span className="truncate flex-1">{item.label}</span>
                {item.id === 'clarifications' && openClarifications !== null && openClarifications > 0 && (
                  <span
                    className="ml-auto inline-flex items-center justify-center min-w-[20px] px-1.5 py-0.5 text-[10px] font-semibold rounded-full bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300"
                    title={`${openClarifications} offene Klärung${openClarifications === 1 ? '' : 'en'}`}
                  >
                    {openClarifications}
                  </span>
                )}
              </Link>
            ))}
          </nav>
          {/* Extra modules (not part of standard CE flow) */}
          <div className="px-4 pt-3 mt-1 border-t border-gray-200 dark:border-gray-700">
            <p className="text-xs text-gray-400 uppercase tracking-wider mb-1">Zusatzmodule</p>
          </div>
          <nav className="px-2 pb-2 space-y-0.5">
            {IACE_EXTRA_ITEMS.map((item) => (
              <Link
                key={item.id}
                href={`${basePath}${item.href}`}
                className={`flex items-center gap-2.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${
                  isActive(item.href)
                    ? 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
                    : 'text-gray-400 hover:bg-gray-50 dark:text-gray-500 dark:hover:bg-gray-700'
                }`}
              >
                <NavIcon icon={item.icon} className="w-3.5 h-3.5 flex-shrink-0" />
                <span className="truncate">{item.label}</span>
              </Link>
            ))}
          </nav>
        </aside>
      )}

      {/* Main content */}
      <main className="flex-1 overflow-auto bg-gray-50 dark:bg-gray-900">
        <div className="p-6">{children}</div>
      </main>

      {/* CE Process Step Navigator FAB */}
      {projectId && <IACEFlowFAB />}
    </div>
  )
}
