'use client'

import { useState, useMemo } from'react'
import { createClient } from'@/lib/supabase/client'
import { usePlaceholders } from'@/lib/master-data/use-placeholders'
import { Plus, X, ChevronDown, ChevronUp } from'lucide-react'

type Effort ='low'|'middle'|'high'
type Benefit ='low'|'middle'|'high'
type Status ='open'|'in_progress'|'done'|'rejected'

interface Action {
 id: string
 project_id: string
 action_number: number
 area: string
 description: string
 effort: Effort
 benefit: Benefit
 status: Status
 responsible: string | null
 target_date: string | null
 time_saving_sec: number | null
 cost_saving_eur: number | null
}

interface Props {
 projectId: string
 initialActions: Action[]
}

const statusColors: Record<Status, string> = {
 open:'bg-[#FFF3CD] text-status-yellow border-[#FDE68A]',
 in_progress:'bg-primary/10 text-primary border-primary/30',
 done:'bg-success/10 text-success border-success/30',
 rejected:'bg-muted text-muted-foreground border-border',
}

const effortBenefitColors: Record<string, string> = {
 high:'text-success',
 middle:'text-status-yellow',
 low:'text-destructive',
}

const matrixLabels = ['high','middle','low'] as const

export default function WorkshopClient({
 projectId, initialActions }: Props) {
 const ph = usePlaceholders()
 const [actions, setActions] = useState<Action[]>(initialActions)
 const [showForm, setShowForm] = useState(false)
 const [showMatrix, setShowMatrix] = useState(true)
 const [expandedId, setExpandedId] = useState<string | null>(null)

 const [form, setForm] = useState({
 area:'',
 description:'',
 effort:'middle'as Effort,
 benefit:'middle'as Benefit,
 responsible:'',
 target_date:'',
 time_saving_sec:'',
 })

 const supabase = useMemo(() => createClient(), [])

 function updateForm(field: string, value: string) {
 setForm((f) => ({ ...f, [field]: value }))
 }

 async function addAction() {
 if (!form.description.trim()) return
 const number = actions.length + 1

 const { data, error } = await supabase
 .from('workshop_actions')
 .insert({
 project_id: projectId,
 action_number: number,
 area: form.area ||'General',
 description: form.description,
 effort: form.effort,
 benefit: form.benefit,
 responsible: form.responsible || null,
 target_date: form.target_date || null,
 time_saving_sec: form.time_saving_sec ? parseFloat(form.time_saving_sec) : null,
 })
 .select()
 .single()

 if (!error && data) {
 setActions([...actions, data])
 setForm({ area:'', description:'', effort:'middle', benefit:'middle', responsible:'', target_date:'', time_saving_sec:''})
 setShowForm(false)
 }
 }

 async function updateStatus(id: string, status: Status) {
 setActions((prev) => prev.map((a) => (a.id === id ? { ...a, status } : a)))
 await supabase.from('workshop_actions').update({ status }).eq('id', id)
 }

 async function deleteAction(id: string) {
 if (!window.confirm('Maßnahme wirklich löschen?')) return
 setActions((prev) => prev.filter((a) => a.id !== id))
 await supabase.from('workshop_actions').delete().eq('id', id)
 }

 const totalTimeSaving = actions.reduce((s, a) => s + (a.time_saving_sec ?? 0), 0)

 return (
 <div className="max-w-2xl mx-auto px-4 py-4 pb-24 md:pb-8 space-y-4">
 {/* Summary */}
 {actions.length > 0 && (
 <div className="grid grid-cols-3 gap-2">
 <div className="bg-card border border-border rounded-lg p-3 text-center">
 <div className="text-xs text-muted-foreground">Total actions</div>
 <div className="font-mono font-bold text-xl mt-0.5">{actions.length}</div>
 </div>
 <div className="bg-card border border-border rounded-lg p-3 text-center">
 <div className="text-xs text-muted-foreground">Open</div>
 <div className="font-mono font-bold text-xl mt-0.5 text-status-yellow">
 {actions.filter((a) => a.status ==='open').length}
 </div>
 </div>
 <div className="bg-card border border-border rounded-lg p-3 text-center">
 <div className="text-xs text-muted-foreground">Time potential</div>
 <div className="font-mono font-bold text-xl mt-0.5 text-success">
 {totalTimeSaving > 0 ? `${totalTimeSaving.toFixed(0)}s` :'—'}
 </div>
 </div>
 </div>
 )}

 {/* Effort/Benefit Matrix */}
 <div className="bg-card border border-border rounded-lg overflow-hidden">
 <button
 onClick={() => setShowMatrix(!showMatrix)}
 className="w-full flex items-center justify-between px-4 py-3 font-medium text-sm hover:bg-muted/30"
 >
 Effort / Benefit Matrix
 {showMatrix ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
 </button>
 {showMatrix && (
 <div className="p-3 border-t border-border">
 <div className="grid grid-cols-4 gap-1 text-xs">
 {/* Header row */}
 <div className="text-muted-foreground text-center pt-4">Benefit →</div>
 {matrixLabels.map((b) => (
 <div key={b} className="text-center font-medium text-muted-foreground capitalize py-1">
 {b}
 </div>
 ))}
 {/* Matrix cells */}
 {matrixLabels.map((e) => (
 <>
 <div key={`label-${e}`} className="text-muted-foreground capitalize flex items-center justify-center text-center">
 {e}
 </div>
 {matrixLabels.map((b) => {
 const cell = actions.filter((a) => a.effort === e && a.benefit === b)
 const bg =
 e ==='low'&& b ==='high'?'bg-success/10 border-success/30':
 e ==='high'&& b ==='low'?'bg-destructive/10 border-destructive/30':
'bg-muted/30 border-border'
 return (
 <div
 key={`${e}-${b}`}
 className={`border rounded-md p-2 min-h-12 flex flex-wrap gap-1 ${bg}`}
 >
 {cell.map((a) => (
 <span
 key={a.id}
 className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-primary text-white text-xs font-bold"
 title={a.description}
 >
 {a.action_number}
 </span>
 ))}
 </div>
 )
 })}
 </>
 ))}
 </div>
 <p className="text-xs text-muted-foreground mt-2">
 Effort: low = easy to implement. Benefit: high = large CT reduction.
 </p>
 </div>
 )}
 </div>

 {/* Add action button */}
 <button
 onClick={() => setShowForm(!showForm)}
 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} />
 Maßnahme hinzufügen
 </button>

 {/* Add form */}
 {showForm && (
 <div className="bg-card border border-primary/30 rounded-lg p-4 space-y-3">
 <div className="grid grid-cols-2 gap-3">
 <div>
 <label className="text-xs font-medium text-muted-foreground mb-1 block">Bereich</label>
 <input
 type="text"
 value={form.area}
 onChange={(e) => updateForm('area', e.target.value)}
 className="w-full h-9 px-2 rounded-md border border-input text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 placeholder={ph('fabrikanalyse.finding')}
 />
 </div>
 <div>
 <label className="text-xs font-medium text-muted-foreground mb-1 block">Verantwortlich</label>
 <input
 type="text"
 value={form.responsible}
 onChange={(e) => updateForm('responsible', e.target.value)}
 className="w-full h-9 px-2 rounded-md border border-input text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 placeholder="Vor- und Nachname"
 />
 </div>
 </div>
 <div>
 <label className="text-xs font-medium text-muted-foreground mb-1 block">
 Beschreibung <span className="text-destructive">*</span>
 </label>
 <textarea
 value={form.description}
 onChange={(e) => updateForm('description', e.target.value)}
 rows={2}
 className="w-full px-2 py-1.5 rounded-md border border-input text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
 placeholder={ph('workshop.improvement_idea')}
 />
 </div>
 <div className="grid grid-cols-3 gap-3">
 <div>
 <label className="text-xs font-medium text-muted-foreground mb-1 block">Aufwand</label>
 <select
 value={form.effort}
 onChange={(e) => updateForm('effort', e.target.value)}
 className="w-full h-9 px-2 rounded-md border border-input text-sm focus:outline-none focus:ring-2 focus:ring-primary bg-background"
 >
 <option value="low">Niedrig</option>
 <option value="middle">Mittel</option>
 <option value="high">Hoch</option>
 </select>
 </div>
 <div>
 <label className="text-xs font-medium text-muted-foreground mb-1 block">Nutzen</label>
 <select
 value={form.benefit}
 onChange={(e) => updateForm('benefit', e.target.value)}
 className="w-full h-9 px-2 rounded-md border border-input text-sm focus:outline-none focus:ring-2 focus:ring-primary bg-background"
 >
 <option value="low">Niedrig</option>
 <option value="middle">Mittel</option>
 <option value="high">Hoch</option>
 </select>
 </div>
 <div>
 <label className="text-xs font-medium text-muted-foreground mb-1 block">Zeitersparnis (s)</label>
 <input
 type="number"
 step="0.1"
 value={form.time_saving_sec}
 onChange={(e) => updateForm('time_saving_sec', e.target.value)}
 className="w-full h-9 px-2 rounded-md border border-input text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary"
 placeholder="0"
 />
 </div>
 </div>
 <div className="flex gap-2 justify-end">
 <button onClick={() => setShowForm(false)} className="px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground">
 Abbrechen
 </button>
 <button
 onClick={addAction}
 disabled={!form.description.trim()}
 className="px-4 py-1.5 bg-primary text-white rounded-md text-sm disabled:opacity-50"
 >
 Maßnahme hinzufügen
 </button>
 </div>
 </div>
 )}

 {/* Action list */}
 <div className="space-y-2">
 {actions.map((action) => (
 <div key={action.id} className="bg-card border border-border rounded-lg overflow-hidden">
 <div
 className="flex items-start gap-3 p-3 cursor-pointer hover:bg-muted/20"
 onClick={() => setExpandedId(expandedId === action.id ? null : action.id)}
 >
 <span className="w-7 h-7 rounded-full bg-primary text-white text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">
 {action.action_number}
 </span>
 <div className="flex-1 min-w-0">
 <div className="flex items-center gap-2 flex-wrap">
 <span className="text-xs text-muted-foreground">{action.area}</span>
 <span className={`text-xs px-1.5 py-0.5 rounded-full border ${statusColors[action.status]} capitalize`}>
 {action.status.replace('_','')}
 </span>
 </div>
 <p className="text-sm mt-0.5 leading-snug">{action.description}</p>
 <div className="flex gap-3 mt-1 text-xs text-muted-foreground">
 <span>
 Effort: <span className={effortBenefitColors[action.effort]}>{action.effort}</span>
 </span>
 <span>
 Benefit: <span className={effortBenefitColors[action.benefit]}>{action.benefit}</span>
 </span>
 {action.time_saving_sec && (
 <span className="text-success font-mono">-{action.time_saving_sec}s</span>
 )}
 </div>
 </div>
 {expandedId === action.id ? <ChevronUp size={16} className="text-muted-foreground shrink-0"/> : <ChevronDown size={16} className="text-muted-foreground shrink-0"/>}
 </div>

 {expandedId === action.id && (
 <div className="border-t border-border px-3 pb-3 pt-3 space-y-2">
 {action.responsible && (
 <p className="text-xs text-muted-foreground">
 Responsible: <span className="text-foreground">{action.responsible}</span>
 </p>
 )}
 {action.target_date && (
 <p className="text-xs text-muted-foreground">
 Target: <span className="text-foreground font-mono">{new Date(action.target_date).toLocaleDateString('de-DE')}</span>
 </p>
 )}
 <div className="flex gap-2 flex-wrap">
 {(['open','in_progress','done','rejected'] as Status[]).map((s) => (
 <button
 key={s}
 onClick={() => updateStatus(action.id, s)}
 className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${
 action.status === s ? statusColors[s] :'border-border text-muted-foreground hover:bg-muted'
 }`}
 >
 {s.replace('_','')}
 </button>
 ))}
 <button
 onClick={() => deleteAction(action.id)}
 className="ml-auto px-2.5 py-1 text-xs rounded-full border border-destructive/30 text-destructive hover:bg-destructive/10"
 >
 Delete
 </button>
 </div>
 </div>
 )}
 </div>
 ))}
 </div>
 </div>
 )
}
