'use client'

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

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'] }) {
  return (
    <div className="flex items-center gap-3 text-xs">
      {summary.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">{summary.critical}</span>
        </span>
      )}
      {summary.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">{summary.high}</span>
        </span>
      )}
      {summary.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">{summary.medium}</span>
        </span>
      )}
      {summary.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">{summary.low}</span>
        </span>
      )}
      {summary.critical === 0 && summary.high === 0 && summary.medium === 0 && summary.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: '',
  })

  useEffect(() => {
    fetchProjects()
  }, [])

  async function fetchProjects() {
    try {
      const res = await fetch('/api/sdk/v1/iace/projects')
      if (res.ok) {
        const json = await res.json()
        setProjects(json.projects || json || [])
      }
    } 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>

      {/* 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>
              <input
                type="text"
                value={formData.machine_type}
                onChange={(e) => setFormData({ ...formData, machine_type: e.target.value })}
                placeholder="z.B. Industrieroboter"
                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">
                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>
  )
}
