// tdd-guard:skip — interactive UI + supabase mutations; no isolated logic to unit-test.
'use client'

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

interface ShiftOutput {
 id: string
 project_id: string
 shift_date: string
 shift_label:'Frühschicht'|'Spätschicht'|'Nachtschicht'
 hour_start: number
 plan_output: number
 ist_output: number
 remarks: string | null
}

interface Props {
 projectId: string
 initialOutputs: ShiftOutput[]
 defaultDate: string
}

const SHIFT_HOURS: Record<string, number[]> = {
 Frühschicht: [6, 7, 8, 9, 10, 11, 12, 13],
 Spätschicht: [14, 15, 16, 17, 18, 19, 20, 21],
 Nachtschicht: [22, 23, 0, 1, 2, 3, 4, 5],
}

export default function ShiftOutputClient({
 projectId, initialOutputs, defaultDate }: Props) {
 const ph = usePlaceholders()
 const [outputs, setOutputs] = useState<ShiftOutput[]>(initialOutputs)
 const [date, setDate] = useState(defaultDate)
 const [shiftType, setShiftType] = useState<'Frühschicht'|'Spätschicht'|'Nachtschicht'>('Frühschicht')
 const [editingId, setEditingId] = useState<string | null>(null)
 const [saving, setSaving] = useState(false)

 const currentOutputs = outputs.filter(
 (o) => o.shift_date === date && o.shift_label === shiftType
 )

 const hours = SHIFT_HOURS[shiftType]
 const totalTarget = currentOutputs.reduce((s, o) => s + o.plan_output, 0)
 const totalActual = currentOutputs.reduce((s, o) => s + o.ist_output, 0)

 function getOutput(hour: number) {
 return currentOutputs.find((o) => o.hour_start === hour)
 }

 async function upsertRow(hour: number, field:'plan_output'|'ist_output'|'remarks', value: string | number) {
 const existing = getOutput(hour)
 const supabase = createClient()

 if (existing) {
 const updated = { ...existing, [field]: value }
 setOutputs((prev) => prev.map((o) => (o.id === existing.id ? updated : o)))
 await supabase.from('lsc_shift_hours').update({ [field]: value }).eq('id', existing.id)
 } else {
 const row = {
 project_id: projectId,
 shift_date: date,
 shift_label: shiftType,
 hour_start: hour,
 plan_output: field ==='plan_output'? Number(value) : 0,
 ist_output: field ==='ist_output'? Number(value) : 0,
 remarks: field ==='remarks'? String(value) : null,
 }
 // Upsert on the project-scoped unique key so a repeat write for the same
 // hour updates instead of hitting the lsc_shift_hours unique constraint.
 const { data } = await supabase
 .from('lsc_shift_hours')
 .upsert(row, { onConflict:'project_id,shift_date,shift_label,hour_start'})
 .select()
 .single()
 if (data) setOutputs((prev) => [...prev, data])
 }
 }

 return (
 <div className="max-w-2xl mx-auto px-4 py-4 pb-24 md:pb-8 space-y-4">
 {/* Controls */}
 <div className="flex gap-3 flex-wrap">
 <input
 type="date"
 value={date}
 onChange={(e) => setDate(e.target.value)}
 className="h-10 px-3 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 />
 <div className="flex rounded-md border border-input overflow-hidden">
 {(['Frühschicht','Spätschicht','Nachtschicht'] as const).map((s) => (
 <button
 key={s}
 onClick={() => setShiftType(s)}
 className={`px-3 py-2 text-sm font-medium transition-colors ${
 shiftType === s
 ?'bg-primary text-white'
 :'bg-background text-foreground hover:bg-muted'
 }`}
 >
 {s.replace('schicht','')}
 </button>
 ))}
 </div>
 </div>

 {/* Table */}
 <div className="bg-card border border-border rounded-lg overflow-hidden">
 <table className="w-full text-sm">
 <thead>
 <tr className="bg-muted/50 border-b border-border">
 <th className="px-3 py-2.5 text-left font-medium text-muted-foreground">Uhrzeit</th>
 <th className="px-3 py-2.5 text-right font-medium text-muted-foreground">Soll</th>
 <th className="px-3 py-2.5 text-right font-medium text-muted-foreground">Ist</th>
 <th className="px-3 py-2.5 text-left font-medium text-muted-foreground">Bemerkung</th>
 </tr>
 </thead>
 <tbody>
 {hours.map((hour) => {
 const output = getOutput(hour)
 const isOver = output && output.ist_output >= output.plan_output && output.plan_output > 0
 const isUnder = output && output.ist_output < output.plan_output && output.plan_output > 0

 return (
 <tr key={hour} className="border-b border-border last:border-0 hover:bg-muted/30">
 <td className="px-3 py-2 font-mono text-sm">
 {String(hour).padStart(2,'0')}:00
 </td>
 <td className="px-3 py-2 text-right">
 <input
 type="number"
 min="0"
 defaultValue={output?.plan_output ??''}
 onBlur={(e) => upsertRow(hour,'plan_output', parseInt(e.target.value) || 0)}
 className="w-16 text-right font-mono h-8 px-2 rounded border border-transparent hover:border-input focus:border-primary focus:outline-none bg-transparent"
 placeholder="—"
 />
 </td>
 <td className="px-3 py-2 text-right">
 <input
 type="number"
 min="0"
 defaultValue={output?.ist_output ??''}
 onBlur={(e) => upsertRow(hour,'ist_output', parseInt(e.target.value) || 0)}
 className={`w-16 text-right font-mono font-semibold h-8 px-2 rounded border border-transparent hover:border-input focus:outline-none bg-transparent ${
 isOver ?'text-success focus:border-success':
 isUnder ?'text-destructive focus:border-destructive':
'focus:border-primary'
 }`}
 placeholder="—"
 />
 </td>
 <td className="px-3 py-2">
 <input
 type="text"
 defaultValue={output?.remarks ??''}
 onBlur={(e) => e.target.value && upsertRow(hour,'remarks', e.target.value)}
 className="w-full h-8 px-2 rounded border border-transparent hover:border-input focus:border-primary focus:outline-none bg-transparent text-xs"
 placeholder={ph('lsc.shift_comment')}
 />
 </td>
 </tr>
 )
 })}
 </tbody>
 <tfoot>
 <tr className="border-t-2 border-border bg-muted/50 font-semibold">
 <td className="px-3 py-2.5">Summe</td>
 <td className="px-3 py-2.5 text-right font-mono">{totalTarget ||'—'}</td>
 <td className={`px-3 py-2.5 text-right font-mono ${
 totalActual >= totalTarget && totalTarget > 0
 ?'text-success'
 : totalActual < totalTarget && totalTarget > 0
 ?'text-destructive'
 :''
 }`}>
 {totalActual ||'—'}
 </td>
 <td className="px-3 py-2.5">
 {totalTarget > 0 && (
 <span className={`text-xs font-mono ${totalActual >= totalTarget ?'text-success':'text-destructive'}`}>
 {totalActual >= totalTarget ?'+':''}{totalActual - totalTarget}
 </span>
 )}
 </td>
 </tr>
 </tfoot>
 </table>
 </div>

 {totalTarget > 0 && totalActual === totalTarget && (
 <div className="bg-status-yellow/10 border border-status-yellow/30 rounded-lg px-4 py-3 text-sm text-status-yellow">
 ⚠ Ist = Soll for every hour — check if target is too conservative (hidden losses possible)
 </div>
 )}
 </div>
 )
}
