'use client'
// tdd-guard:skip — CRUD/UI component; avg-cycle-time logic lives in lib/reporting/aggregations.ts (tested).

import { useState, useMemo } from'react'
import { createClient } from'@/lib/supabase/client'
import { avgCycleTimeSec } from'@/lib/reporting/aggregations'
import { Plus, Trash2, Timer, Pencil, Check, X, GripVertical } from'lucide-react'
import Link from'next/link'
import { useRouter } from'next/navigation'

interface ProcessStep {
 id: string
 project_id: string
 step_number: number
 station_name: string
 description: string | null
 planned_cycle_time_sec: number | null
 is_manual: boolean
 operator_count: number
 sort_order: number
 cycle_measurements?: { cycle_time_sec: number; is_outlier: boolean }[]
}

interface Props {
 projectId: string
 initialSteps: ProcessStep[]
}

export default function ProcessStepsManager({ projectId, initialSteps }: Props) {
 const router = useRouter()
 const [steps, setSteps] = useState<ProcessStep[]>(initialSteps)
 const [adding, setAdding] = useState(false)
 const [editingId, setEditingId] = useState<string | null>(null)
 const [newStation, setNewStation] = useState('')
 const [newPlannedCt, setNewPlannedCt] = useState('')
 const [isManual, setIsManual] = useState(false)
 const [saving, setSaving] = useState(false)

 // Edit state
 const [editName, setEditName] = useState('')
 const [editPlannedCt, setEditPlannedCt] = useState('')
 const [editManual, setEditManual] = useState(false)
 const supabase = useMemo(() => createClient(), [])


 function startEdit(step: ProcessStep) {
 setEditingId(step.id)
 setEditName(step.station_name)
 setEditPlannedCt(step.planned_cycle_time_sec?.toString() ??'')
 setEditManual(step.is_manual)
 }

 async function saveEdit(stepId: string) {
 setSaving(true)
 const updates = {
 station_name: editName.trim(),
 planned_cycle_time_sec: editPlannedCt ? parseFloat(editPlannedCt) : null,
 is_manual: editManual,
 }
 const { error } = await supabase.from('process_steps').update(updates).eq('id', stepId)
 if (!error) {
 setSteps((prev) => prev.map((s) => (s.id === stepId ? { ...s, ...updates } : s)))
 setEditingId(null)
 router.refresh()
 }
 setSaving(false)
 }

 async function addStep() {
 if (!newStation.trim()) return
 setSaving(true)
 const nextNumber = steps.length + 1
 const { data, error } = await supabase
 .from('process_steps')
 .insert({
 project_id: projectId,
 step_number: nextNumber,
 station_name: newStation.trim(),
 planned_cycle_time_sec: newPlannedCt ? parseFloat(newPlannedCt) : null,
 is_manual: isManual,
 sort_order: steps.length,
 })
 .select()
 .single()
 if (!error && data) {
 setSteps([...steps, data])
 setNewStation('')
 setNewPlannedCt('')
 setIsManual(false)
 setAdding(false)
 router.refresh()
 }
 setSaving(false)
 }

 async function deleteStep(stepId: string) {
 if (!confirm('Delete this station and all its measurements?')) return
 await supabase.from('process_steps').delete().eq('id', stepId)
 setSteps(steps.filter((s) => s.id !== stepId))
 router.refresh()
 }

 async function moveStep(stepId: string, direction:'up'|'down') {
 const idx = steps.findIndex((s) => s.id === stepId)
 if (direction ==='up'&& idx === 0) return
 if (direction ==='down'&& idx === steps.length - 1) return

 const newSteps = [...steps]
 const swapIdx = direction ==='up'? idx - 1 : idx + 1
 ;[newSteps[idx], newSteps[swapIdx]] = [newSteps[swapIdx], newSteps[idx]]

 // Update sort_order
 const updated = newSteps.map((s, i) => ({ ...s, sort_order: i }))
 setSteps(updated)

 await Promise.all([
 supabase.from('process_steps').update({ sort_order: idx }).eq('id', updated[swapIdx].id),
 supabase.from('process_steps').update({ sort_order: swapIdx }).eq('id', updated[idx].id),
 ])
 router.refresh()
 }

 return (
 <div className="space-y-2">
 {steps.map((step, idx) => {
 const avg = avgCycleTimeSec(step.cycle_measurements ?? [])
 const count = step.cycle_measurements?.filter((m) => !m.is_outlier).length ?? 0
 const isEditing = editingId === step.id

 return (
 <div key={step.id} className={`bg-card border rounded-lg overflow-hidden transition-colors ${isEditing ?'border-primary/40':'border-border'}`}>
 {isEditing ? (
 <div className="p-3 space-y-2">
 <div className="flex gap-2">
 <input
 type="text"
 value={editName}
 onChange={(e) => setEditName(e.target.value)}
 className="flex-1 h-9 px-2 rounded-md border border-input text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 autoFocus
 />
 <input
 type="number"
 step="0.01"
 value={editPlannedCt}
 onChange={(e) => setEditPlannedCt(e.target.value)}
 placeholder="Plan CT (s)"
 className="w-24 h-9 px-2 rounded-md border border-input text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary"
 />
 </div>
 <div className="flex items-center justify-between">
 <label className="flex items-center gap-2 text-sm cursor-pointer">
 <input type="checkbox"checked={editManual} onChange={(e) => setEditManual(e.target.checked)} className="rounded"/>
 Manual station
 </label>
 <div className="flex gap-2">
 <button onClick={() => setEditingId(null)} className="p-1.5 text-muted-foreground hover:text-foreground rounded">
 <X size={16} />
 </button>
 <button onClick={() => saveEdit(step.id)} disabled={saving || !editName.trim()}
 className="p-1.5 text-success hover:bg-success/10 rounded disabled:opacity-50">
 <Check size={16} />
 </button>
 </div>
 </div>
 </div>
 ) : (
 <div className="px-3 py-3 flex items-center gap-2">
 {/* Reorder arrows */}
 <div className="flex flex-col gap-0.5 shrink-0">
 <button onClick={() => moveStep(step.id,'up')} disabled={idx === 0}
 className="text-muted-foreground hover:text-foreground disabled:opacity-20 leading-none">▲</button>
 <button onClick={() => moveStep(step.id,'down')} disabled={idx === steps.length - 1}
 className="text-muted-foreground hover:text-foreground disabled:opacity-20 leading-none text-xs">▼</button>
 </div>

 <div className="flex-1 min-w-0">
 <div className="flex items-center gap-2">
 <span className="text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded shrink-0">
 #{idx + 1}
 </span>
 <span className="font-medium text-sm truncate">{step.station_name}</span>
 {step.is_manual && (
 <span className="text-xs text-primary bg-primary/10 px-1.5 py-0.5 rounded shrink-0">manual</span>
 )}
 </div>
 <div className="flex items-center gap-3 mt-0.5 text-xs text-muted-foreground">
 {step.planned_cycle_time_sec && (
 <span className="font-mono">plan: {step.planned_cycle_time_sec}s</span>
 )}
 {avg !== null ? (
 <span className="font-mono font-medium text-foreground">avg: {avg.toFixed(2)}s ({count}×)</span>
 ) : (
 <span>no measurements</span>
 )}
 </div>
 </div>

 <div className="flex items-center gap-1 shrink-0">
 <button onClick={() => startEdit(step)} className="p-1.5 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded transition-colors"title="Edit">
 <Pencil size={14} />
 </button>
 <Link href={`/project/${projectId}/stopwatch?step=${step.id}`}
 className="p-1.5 text-primary hover:bg-primary/10 rounded transition-colors"title="Measure">
 <Timer size={15} />
 </Link>
 <button onClick={() => deleteStep(step.id)} className="p-1.5 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded transition-colors"title="Delete">
 <Trash2 size={14} />
 </button>
 </div>
 </div>
 )}
 </div>
 )
 })}

 {adding ? (
 <div className="bg-card border border-primary/30 rounded-lg p-3 space-y-3">
 <div className="flex gap-2">
 <input type="text"value={newStation} onChange={(e) => setNewStation(e.target.value)}
 placeholder="Station name (e.g. M0500, Endmontage)"
 className="flex-1 h-10 px-3 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 autoFocus onKeyDown={(e) => e.key ==='Enter'&& addStep()} />
 <input type="number"step="0.01"value={newPlannedCt} onChange={(e) => setNewPlannedCt(e.target.value)}
 placeholder="Plan CT (s)"
 className="w-28 h-10 px-3 rounded-md border border-input bg-background text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary"/>
 </div>
 <div className="flex items-center justify-between">
 <label className="flex items-center gap-2 text-sm cursor-pointer">
 <input type="checkbox"checked={isManual} onChange={(e) => setIsManual(e.target.checked)} className="rounded"/>
 Manual station
 </label>
 <div className="flex gap-2">
 <button onClick={() => { setAdding(false); setNewStation(''); setNewPlannedCt('') }}
 className="px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground">Cancel</button>
 <button onClick={addStep} disabled={saving || !newStation.trim()}
 className="px-3 py-1.5 bg-primary text-white rounded-md text-sm disabled:opacity-50">
 {saving ?'Adding…':'Add'}
 </button>
 </div>
 </div>
 </div>
 ) : (
 <button onClick={() => setAdding(true)}
 className="w-full flex items-center justify-center gap-2 h-10 border border-dashed border-border rounded-lg text-sm text-muted-foreground hover:text-primary hover:border-primary/50 transition-colors">
 <Plus size={16} />
 Add process step
 </button>
 )}
 </div>
 )
}
