// tdd-guard:skip — interactive UI + supabase mutations; role list is static config.
'use client'

import { useState, useMemo } from'react'
import { X, Plus } from'lucide-react'
import { createClient } from'@/lib/supabase/client'

interface ConsultantData {
 id: string
 display_name: string | null
 first_name: string | null
 last_name: string | null
 team_code: string | null
}

interface Member {
 consultant_id: string
 role_in_project: string
 consultants: ConsultantData | ConsultantData[] | null
}

interface RoleOption {
 value: string
 label: string
}

interface Props {
 projectId: string
 initialMembers: Member[]
 allConsultants: ConsultantData[]
 canManage: boolean
}

function consultantName(c: ConsultantData): string {
 return c.display_name ?? ([c.first_name, c.last_name].filter(Boolean).join('') ||'—')
}

// KAR-704 C1: one consistent role set for every project. The workshop-only roles
// (Einkauf / QMT / Cost Engineering) are now available everywhere, so the project
// and LSC team routes no longer diverge.
const BASE_ROLES: RoleOption[] = [
 { value:'collaborator', label:'Berater'},
 { value:'lead', label:'Projektleiter'},
 { value:'einkauf', label:'Einkauf'},
 { value:'qmt', label:'QMT Qualität'},
 { value:'cost_engineering', label:'Cost Engineering'},
]

const ROLE_COLORS: Record<string, string> = {
 lead:'bg-secondary text-primary',
 collaborator:'bg-muted text-muted-foreground',
 einkauf:'bg-teal-100 text-teal-700',
 qmt:'bg-purple-100 text-purple-700',
 cost_engineering:'bg-amber-100 text-amber-700',
}

export default function TeamClient({ projectId, initialMembers, allConsultants, canManage }: Props) {
 const allRoles = BASE_ROLES
 const [members, setMembers] = useState<Member[]>(initialMembers)
 const [addId, setAddId] = useState('')
 const [addRole, setAddRole] = useState('collaborator')
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState<string | null>(null)
 const [confirmRemove, setConfirmRemove] = useState<string | null>(null)
 const supabase = useMemo(() => createClient(), [])

 const assignedIds = new Set(members.map((m) => m.consultant_id))
 const available = allConsultants.filter((c) => !assignedIds.has(c.id))

 async function handleAdd() {
 if (!addId) return
 setSaving(true)
 setError(null)
 const { error: err } = await supabase
 .from('project_consultants')
 .insert({ project_id: projectId, consultant_id: addId, role_in_project: addRole as string })
 if (err) {
 setError(err.message)
 setSaving(false)
 return
 }
 const consultant = allConsultants.find((c) => c.id === addId) ?? null
 setMembers((prev) => [...prev, { consultant_id: addId, role_in_project: addRole as string, consultants: consultant }])
 setAddId('')
 setAddRole('collaborator')
 setSaving(false)
 }

 async function handleRemove(consultantId: string) {
 setSaving(true)
 setError(null)
 const { error: err } = await supabase
 .from('project_consultants')
 .delete()
 .eq('project_id', projectId)
 .eq('consultant_id', consultantId)
 if (err) {
 setError(err.message)
 setSaving(false)
 setConfirmRemove(null)
 return
 }
 setMembers((prev) => prev.filter((m) => m.consultant_id !== consultantId))
 setConfirmRemove(null)
 setSaving(false)
 }

 return (
 <div className="space-y-4">
 {/* Member list */}
 <div className="bg-card rounded-xl border border-border divide-y divide-border">
 {members.map((m) => {
 const rawC = m.consultants
 const c: ConsultantData | null = Array.isArray(rawC) ? (rawC[0] ?? null) : rawC
 const roleLabel = allRoles.find(r => r.value === m.role_in_project)?.label ?? m.role_in_project
 const displayName = c ? consultantName(c) :'—'

 return (
 <div key={m.consultant_id} className="px-4 py-3 flex items-center justify-between gap-3">
 <div className="flex-1 min-w-0">
 <p className="text-sm font-medium text-foreground truncate">{displayName}</p>
 {c?.team_code && <p className="text-xs text-muted-foreground">{c.team_code}</p>}
 </div>
 <span
 className={`text-xs font-medium px-2 py-0.5 rounded-full shrink-0 ${ROLE_COLORS[m.role_in_project] ??'bg-muted text-muted-foreground'}`}
 >
 {roleLabel}
 </span>
 {canManage && (
 confirmRemove === m.consultant_id ? (
 <div className="flex items-center gap-1.5 shrink-0">
 <button
 onClick={() => void handleRemove(m.consultant_id)}
 disabled={saving}
 className="text-xs text-white bg-destructive px-2 py-1 rounded hover:bg-destructive/80 disabled:opacity-50"
 >
 Entfernen
 </button>
 <button
 onClick={() => setConfirmRemove(null)}
 className="text-xs text-muted-foreground px-2 py-1 rounded hover:bg-muted"
 >
 Abbrechen
 </button>
 </div>
 ) : (
 <button
 onClick={() => setConfirmRemove(m.consultant_id)}
 className="text-muted-foreground hover:text-destructive transition-colors shrink-0 p-1 rounded hover:bg-red-50"
 aria-label="Berater entfernen"
 >
 <X size={15} />
 </button>
 )
 )}
 </div>
 )
 })}
 {members.length === 0 && (
 <div className="px-4 py-8 text-center text-sm text-muted-foreground">
 Keine Teammitglieder zugewiesen.
 </div>
 )}
 </div>

 {/* Add consultant */}
 {canManage && (
 <div className="bg-card rounded-xl border border-border px-4 py-4">
 <p className="text-sm font-semibold text-foreground mb-3">Berater hinzufügen</p>
 <div className="flex gap-2 flex-wrap">
 <select
 value={addId}
 onChange={(e) => setAddId(e.target.value)}
 className="flex-1 min-w-[160px] h-10 px-3 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 >
 <option value="">Berater wählen…</option>
 {available.map((c) => (
 <option key={c.id} value={c.id}>{consultantName(c)}</option>
 ))}
 </select>
 <select
 value={addRole}
 onChange={(e) => setAddRole(e.target.value)}
 className="w-44 h-10 px-3 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 >
 {allRoles.map(r => (
 <option key={r.value} value={r.value}>{r.label}</option>
 ))}
 </select>
 <button
 onClick={() => void handleAdd()}
 disabled={!addId || saving}
 className="h-10 px-4 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-40 transition-colors flex items-center gap-1.5"
 >
 <Plus size={15} />
 Hinzufügen
 </button>
 </div>
 {error && <p className="mt-2 text-xs text-destructive">{error}</p>}
 </div>
 )}
 </div>
 )
}
