'use client'

import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import { ProcessFlow } from './_components/ProcessFlow'

interface IACEProject {
  id: string
  machine_name: string
  machine_type: string
  manufacturer: string
  status: string
  completeness_pct: number
  risk_summary?: {
    critical: number
    high: number
    medium: number
    low: number
  }
  created_at: string
  updated_at: string
}

function StatusBadge({ status }: { status: string }) {
  const colors: Record<string, string> = {
    draft: 'bg-gray-100 text-gray-700',
    in_progress: 'bg-blue-100 text-blue-700',
    review: 'bg-yellow-100 text-yellow-700',
    approved: 'bg-green-100 text-green-700',
    archived: 'bg-gray-100 text-gray-500',
  }
  const labels: Record<string, string> = {
    draft: 'Entwurf',
    in_progress: 'In Bearbeitung',
    review: 'In Pruefung',
    approved: 'Freigegeben',
    archived: 'Archiviert',
  }
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colors[status] || colors.draft}`}>
      {labels[status] || status}
    </span>
  )
}

function CompletenessBar({ pct }: { pct: number }) {
  const color = pct >= 80 ? 'bg-green-500' : pct >= 50 ? 'bg-yellow-500' : pct >= 25 ? 'bg-orange-500' : 'bg-red-500'
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 bg-gray-200 rounded-full h-2">
        <div className={`${color} h-2 rounded-full transition-all`} style={{ width: `${pct}%` }} />
      </div>
      <span className="text-xs font-medium text-gray-600 w-8 text-right">{pct}%</span>
    </div>
  )
}

function RiskDots({ summary }: { summary?: IACEProject['risk_summary'] }) {
  const s = summary || { critical: 0, high: 0, medium: 0, low: 0 }
  return (
    <div className="flex items-center gap-3 text-xs">
      {s.critical > 0 && (
        <span className="flex items-center gap-1">
          <span className="w-2.5 h-2.5 rounded-full bg-red-500" />
          <span className="text-gray-600">{s.critical}</span>
        </span>
      )}
      {s.high > 0 && (
        <span className="flex items-center gap-1">
          <span className="w-2.5 h-2.5 rounded-full bg-orange-500" />
          <span className="text-gray-600">{s.high}</span>
        </span>
      )}
      {s.medium > 0 && (
        <span className="flex items-center gap-1">
          <span className="w-2.5 h-2.5 rounded-full bg-yellow-500" />
          <span className="text-gray-600">{s.medium}</span>
        </span>
      )}
      {s.low > 0 && (
        <span className="flex items-center gap-1">
          <span className="w-2.5 h-2.5 rounded-full bg-green-500" />
          <span className="text-gray-600">{s.low}</span>
        </span>
      )}
      {s.critical === 0 && s.high === 0 && s.medium === 0 && s.low === 0 && (
        <span className="text-gray-400">Keine Risiken</span>
      )}
    </div>
  )
}

function ProjectCard({ project }: { project: IACEProject }) {
  return (
    <Link
      href={`/sdk/iace/${project.id}`}
      className="block bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 hover:shadow-md transition-shadow"
    >
      <div className="flex items-start justify-between mb-3">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">{project.machine_name}</h3>
          <p className="text-sm text-gray-500 dark:text-gray-400">{project.machine_type}</p>
        </div>
        <StatusBadge status={project.status} />
      </div>

      <div className="space-y-3">
        <div>
          <div className="text-xs text-gray-500 mb-1">Vollstaendigkeit</div>
          <CompletenessBar pct={project.completeness_pct} />
        </div>

        <div>
          <div className="text-xs text-gray-500 mb-1">Risiken</div>
          <RiskDots summary={project.risk_summary} />
        </div>

        <div className="flex items-center justify-between text-xs text-gray-400 pt-2 border-t border-gray-100 dark:border-gray-700">
          <span>Erstellt: {new Date(project.created_at).toLocaleDateString('de-DE')}</span>
          <span>Aktualisiert: {new Date(project.updated_at).toLocaleDateString('de-DE')}</span>
        </div>
      </div>
    </Link>
  )
}

export default function IACEDashboardPage() {
  const [projects, setProjects] = useState<IACEProject[]>([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(false)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [formData, setFormData] = useState({
    machine_name: '',
    machine_type: '',
    manufacturer: '',
  })
  const [machineTypes, setMachineTypes] = useState<{ key: string; label_de: string; group: string }[]>([])

  useEffect(() => {
    fetchProjects()
    fetch('/api/sdk/v1/iace/machine-types')
      .then((r) => (r.ok ? r.json() : null))
      .then((j) => j && setMachineTypes(j.machine_types || []))
      .catch((err) => console.error('Failed to fetch machine types:', err))
  }, [])

  async function fetchProjects() {
    try {
      const res = await fetch('/api/sdk/v1/iace/projects')
      if (res.ok) {
        const json = await res.json()
        const raw = json.projects || json || []
        // Map API fields to frontend expectations
        setProjects(raw.map((p: Record<string, unknown>) => ({
          ...p,
          completeness_pct: p.completeness_pct ?? p.completeness_score ?? 0,
          risk_summary: p.risk_summary || { critical: 0, high: 0, medium: 0, low: 0 },
        })))
      }
    } catch (err) {
      console.error('Failed to fetch IACE projects:', err)
    } finally {
      setLoading(false)
    }
  }

  async function handleCreateProject() {
    if (!formData.machine_name) return
    setCreating(true)
    try {
      const res = await fetch('/api/sdk/v1/iace/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      })
      if (res.ok) {
        setShowCreateForm(false)
        setFormData({ machine_name: '', machine_type: '', manufacturer: '' })
        await fetchProjects()
      }
    } catch (err) {
      console.error('Failed to create project:', err)
    } finally {
      setCreating(false)
    }
  }

  async function handleInitFromProfile(projectId: string) {
    try {
      const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/init-from-profile`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })
      if (res.ok) {
        await fetchProjects()
      }
    } catch (err) {
      console.error('Failed to init from profile:', err)
    }
  }

  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-6xl mx-auto">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            CE-Compliance (IACE)
          </h1>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            Industrial AI Compliance Engine -- Durchgaengige CE-Konformitaet fuer Maschinen und Anlagen
            mit KI-Komponenten. Verwalten Sie Risikobeurteilungen, Hazard Logs und technische
            Dokumentation gemaess Maschinenverordnung, AI Act, CRA und NIS2.
          </p>
        </div>
        <button
          onClick={() => setShowCreateForm(true)}
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex-shrink-0"
        >
          <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>
          Neues Projekt erstellen
        </button>
      </div>

      {/* Quick Access Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Link
          href="/sdk/iace/lines"
          className="block bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/20 dark:to-indigo-900/20 rounded-xl border border-purple-200 dark:border-purple-800 p-6 hover:shadow-md hover:border-purple-300 transition-all group"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-purple-100 dark:bg-purple-900/40 rounded-xl flex items-center justify-center flex-shrink-0">
                <svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <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>
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                  Produktionslinien
                </h2>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Verkettete Fertigungsstrassen mit aggregierter Risikoansicht und animiertem Stationsfluss
                </p>
              </div>
            </div>
            <svg className="w-5 h-5 text-purple-400 group-hover:text-purple-600 transition-colors flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </div>
        </Link>

        <Link
          href="/sdk/iace/library"
          className="block bg-gradient-to-r from-indigo-50 to-blue-50 dark:from-indigo-900/20 dark:to-blue-900/20 rounded-xl border border-indigo-200 dark:border-indigo-800 p-6 hover:shadow-md hover:border-indigo-300 transition-all group"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-indigo-100 dark:bg-indigo-900/40 rounded-xl flex items-center justify-center flex-shrink-0">
                <svg className="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <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>
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                  Bibliothek
                </h2>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Normen, Hazard Patterns und Schutzmassnahmen durchsuchen und filtern
                </p>
              </div>
            </div>
            <svg className="w-5 h-5 text-indigo-400 group-hover:text-indigo-600 transition-colors flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </div>
        </Link>
      </div>

      {/* Process Flow */}
      <ProcessFlow />

      {/* Create Form */}
      {showCreateForm && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Neues CE-Projekt anlegen
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Maschinenname *
              </label>
              <input
                type="text"
                value={formData.machine_name}
                onChange={(e) => setFormData({ ...formData, machine_name: e.target.value })}
                placeholder="z.B. Schweissroboter SR-500"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Maschinentyp
              </label>
              <select
                value={formData.machine_type}
                onChange={(e) => setFormData({ ...formData, machine_type: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              >
                <option value="">— Maschinentyp wählen —</option>
                {Array.from(new Set(machineTypes.map((m) => m.group))).map((group) => (
                  <optgroup key={group} label={group}>
                    {machineTypes.filter((m) => m.group === group).map((m) => (
                      <option key={m.key} value={m.key}>{m.label_de}</option>
                    ))}
                  </optgroup>
                ))}
              </select>
              <p className="mt-1 text-xs text-gray-400">
                Steuert, welche maschinenspezifischen Gefährdungs-Patterns greifen — bitte aus der Liste wählen.
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Hersteller
              </label>
              <input
                type="text"
                value={formData.manufacturer}
                onChange={(e) => setFormData({ ...formData, manufacturer: e.target.value })}
                placeholder="z.B. Acme Robotics GmbH"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              />
            </div>
          </div>
          <div className="mt-4 flex items-center gap-3">
            <button
              onClick={handleCreateProject}
              disabled={!formData.machine_name || creating}
              className={`px-6 py-2 rounded-lg font-medium transition-colors ${
                formData.machine_name && !creating
                  ? 'bg-purple-600 text-white hover:bg-purple-700'
                  : 'bg-gray-200 text-gray-400 cursor-not-allowed'
              }`}
            >
              {creating ? 'Wird erstellt...' : 'Projekt erstellen'}
            </button>
            <button
              onClick={() => setShowCreateForm(false)}
              className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
            >
              Abbrechen
            </button>
          </div>
        </div>
      )}

      {/* Project List */}
      {projects.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Projekte ({projects.length})
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {projects.map((project) => (
              <ProjectCard key={project.id} project={project} />
            ))}
          </div>
        </div>
      )}

      {/* Empty State */}
      {projects.length === 0 && !showCreateForm && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-purple-100 dark:bg-purple-900/30 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-purple-600" 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 dark:text-white">
            Noch keine CE-Projekte vorhanden
          </h3>
          <p className="mt-2 text-gray-500 dark:text-gray-400 max-w-lg mx-auto">
            Die IACE (Industrial AI Compliance Engine) begleitet Sie Schritt fuer Schritt durch den
            gesamten CE-Konformitaetsprozess. Von der Komponentenerfassung ueber die Risikobeurteilung
            bis hin zur fertigen CE-Akte -- alles in einem Werkzeug. Unterstuetzt werden Maschinenverordnung
            (2023/1230), AI Act, Cyber Resilience Act und NIS2.
          </p>
          <div className="mt-6 flex items-center justify-center gap-3">
            <button
              onClick={() => setShowCreateForm(true)}
              className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-medium"
            >
              Erstes Projekt erstellen
            </button>
            <button
              onClick={() => handleInitFromProfile('new')}
              className="px-6 py-3 border border-purple-300 text-purple-700 rounded-lg hover:bg-purple-50 transition-colors font-medium"
            >
              Aus Unternehmensprofil initialisieren
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
