'use client'

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

interface ProductionLineItem {
  id: string
  name: string
  description: string
  station_count: number
  created_at: string
  updated_at: string
}

interface ProjectItem {
  id: string
  machine_name: string
  machine_type: string
  status: string
}

const STATION_TYPES = [
  { value: 'press', label: 'Presse' },
  { value: 'cobot', label: 'Cobot/Roboter' },
  { value: 'motor', label: 'Motor/Antrieb' },
  { value: 'rotary_transfer', label: 'Rundtaktanlage' },
  { value: 'conveyor', label: 'Foerderer' },
  { value: 'assembly', label: 'Montage' },
  { value: 'milling', label: 'Fraese' },
  { value: 'turning', label: 'Drehmaschine' },
  { value: 'welding', label: 'Schweissen' },
  { value: 'inspection', label: 'Pruefung' },
  { value: 'packaging', label: 'Verpackung' },
]

export default function ProductionLinesListPage() {
  const [lines, setLines] = useState<ProductionLineItem[]>([])
  const [projects, setProjects] = useState<ProjectItem[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [creating, setCreating] = useState(false)
  const [lineName, setLineName] = useState('')
  const [lineDesc, setLineDesc] = useState('')
  const [selectedStations, setSelectedStations] = useState<Array<{ projectId: string; stationType: string }>>([])

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

  async function fetchLines() {
    try {
      const res = await fetch('/api/sdk/v1/iace/production-lines')
      if (res.ok) {
        const json = await res.json()
        setLines(json.lines || [])
      }
    } catch { /* ignore */ }
    finally { setLoading(false) }
  }

  async function fetchProjects() {
    try {
      const res = await fetch('/api/sdk/v1/iace/projects')
      if (res.ok) {
        const json = await res.json()
        setProjects((json.projects || []).map((p: Record<string, unknown>) => ({
          id: p.id, machine_name: p.machine_name, machine_type: p.machine_type, status: p.status,
        })))
      }
    } catch { /* ignore */ }
  }

  function addStation() {
    setSelectedStations((prev) => [...prev, { projectId: '', stationType: 'assembly' }])
  }

  function removeStation(idx: number) {
    setSelectedStations((prev) => prev.filter((_, i) => i !== idx))
  }

  function updateStation(idx: number, field: 'projectId' | 'stationType', value: string) {
    setSelectedStations((prev) => prev.map((s, i) => i === idx ? { ...s, [field]: value } : s))
  }

  async function handleCreate() {
    if (!lineName.trim()) return
    setCreating(true)
    try {
      // 1. Create the line
      const lineRes = await fetch('/api/sdk/v1/iace/production-lines', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: lineName.trim(), description: lineDesc.trim() }),
      })
      if (!lineRes.ok) return
      const lineJson = await lineRes.json()
      const lineId = lineJson.line?.id || lineJson.id

      // 2. Add stations
      for (let i = 0; i < selectedStations.length; i++) {
        const s = selectedStations[i]
        if (!s.projectId) continue
        const proj = projects.find((p) => p.id === s.projectId)
        await fetch(`/api/sdk/v1/iace/production-lines/${lineId}/stations`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            project_id: s.projectId,
            station_type: s.stationType,
            station_label: proj?.machine_name || '',
            sort_order: i + 1,
          }),
        })
      }

      setShowCreate(false)
      setLineName('')
      setLineDesc('')
      setSelectedStations([])
      await fetchLines()
    } catch (err) {
      console.error('Failed to create line:', err)
    } finally {
      setCreating(false)
    }
  }

  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">
      <div className="flex items-start justify-between">
        <div>
          <Link href="/sdk/iace" className="text-xs text-purple-600 hover:text-purple-700 font-medium flex items-center gap-1 mb-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>
            IACE
          </Link>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Produktionslinien</h1>
          <p className="mt-1 text-sm text-gray-500">Verkettete Fertigungsstrassen mit aggregierter Risikoansicht</p>
        </div>
        <button onClick={() => setShowCreate(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>
          Neue Produktionslinie
        </button>
      </div>

      {/* Create form */}
      {showCreate && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-purple-200 p-6 space-y-4">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Neue Produktionslinie erstellen</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name *</label>
              <input type="text" value={lineName} onChange={(e) => setLineName(e.target.value)}
                placeholder="z.B. Fertigungsstrasse Halle 3"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 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">Beschreibung</label>
              <input type="text" value={lineDesc} onChange={(e) => setLineDesc(e.target.value)}
                placeholder="Optionale Beschreibung"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white" />
            </div>
          </div>

          {/* Stations */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-medium text-gray-700 dark:text-gray-300">Stationen (Projekte zuordnen)</label>
              <button onClick={addStation} className="text-xs text-purple-600 hover:text-purple-700 font-medium">+ Station hinzufuegen</button>
            </div>
            {selectedStations.length === 0 && (
              <p className="text-xs text-gray-400 italic">Noch keine Stationen. Klicken Sie &quot;+ Station hinzufuegen&quot; um Projekte zuzuordnen.</p>
            )}
            <div className="space-y-2">
              {selectedStations.map((s, i) => (
                <div key={i} className="flex items-center gap-2 p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <span className="text-xs font-bold text-gray-400 w-6">{i + 1}.</span>
                  <select value={s.projectId} onChange={(e) => updateStation(i, 'projectId', e.target.value)}
                    className="flex-1 px-2 py-1.5 text-sm border border-gray-300 rounded-lg dark:bg-gray-600 dark:border-gray-500 dark:text-white">
                    <option value="">-- Projekt waehlen --</option>
                    {projects.map((p) => (
                      <option key={p.id} value={p.id}>{p.machine_name} ({p.machine_type})</option>
                    ))}
                  </select>
                  <select value={s.stationType} onChange={(e) => updateStation(i, 'stationType', e.target.value)}
                    className="w-40 px-2 py-1.5 text-sm border border-gray-300 rounded-lg dark:bg-gray-600 dark:border-gray-500 dark:text-white">
                    {STATION_TYPES.map((t) => (
                      <option key={t.value} value={t.value}>{t.label}</option>
                    ))}
                  </select>
                  <button onClick={() => removeStation(i)} className="p-1 text-red-400 hover:text-red-600">
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              ))}
            </div>
          </div>

          <div className="flex gap-3 pt-2">
            <button onClick={handleCreate} disabled={!lineName.trim() || creating}
              className={`px-6 py-2 rounded-lg font-medium transition-colors ${lineName.trim() && !creating ? 'bg-purple-600 text-white hover:bg-purple-700' : 'bg-gray-200 text-gray-400 cursor-not-allowed'}`}>
              {creating ? 'Wird erstellt...' : 'Produktionslinie erstellen'}
            </button>
            <button onClick={() => { setShowCreate(false); setSelectedStations([]) }}
              className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
              Abbrechen
            </button>
          </div>
        </div>
      )}

      {/* Lines list */}
      {lines.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {lines.map((line) => (
            <Link key={line.id} href={`/sdk/iace/lines/${line.id}`}
              className="block bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 hover:shadow-md hover:border-purple-300 transition-all">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">{line.name}</h3>
              {line.description && <p className="text-sm text-gray-500 mb-3 line-clamp-2">{line.description}</p>}
              <div className="flex items-center gap-4 text-xs text-gray-500">
                <span>{line.station_count || 0} Stationen</span>
                <span>Aktualisiert: {new Date(line.updated_at || line.created_at).toLocaleDateString('de-DE')}</span>
              </div>
            </Link>
          ))}
        </div>
      )}

      {lines.length === 0 && !showCreate && (
        <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 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="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>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Noch keine Produktionslinien</h3>
          <p className="mt-2 text-gray-500 max-w-lg mx-auto">
            Produktionslinien verketten mehrere CE-Projekte zu einer Fertigungsstrasse.
          </p>
          <button onClick={() => { setShowCreate(true); addStation() }}
            className="mt-6 px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-medium">
            Erste Produktionslinie erstellen
          </button>
        </div>
      )}
    </div>
  )
}
