'use client'

import { useState, useEffect, useMemo } from'react'
import { createClient } from'@/lib/supabase/client'
import type { Consultant, AppointmentType, PlanningProject, WorkMode, AssignmentStatus } from'@/lib/planning-types'

interface ProjectOption {
 id: string
 project_code: string | null
 supplier_name: string
 parent_project_id: string | null
 sub_project_suffix: string | null
}

interface Props {
 consultantId: string
 date: string
 endDate?: string
 consultants: Consultant[]
 appointmentTypes: AppointmentType[]
 planningProjects: PlanningProject[]
 existingAssignments: unknown[]
 onClose: () => void
 onCreated: () => void
 /** FB-36 (P0 compliance, composition profile): work_mode ("Arbeitsort") capture on/off. */
 workModeCapture: boolean
}

function localDateKey(d: Date): string {
 return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}

function getDatesInRange(start: string, end: string, workdaysOnly: boolean): string[] {
 if (!start) return []
 const [s, e] = start <= end ? [start, end] : [end, start]
 const dates: string[] = []
 const cur = new Date(s +'T00:00:00')
 const last = new Date(e +'T00:00:00')
 while (cur <= last) {
 const d = cur.getDay()
 // Use local date — NOT toISOString() which converts to UTC and shifts the date
 if (!workdaysOnly || (d !== 0 && d !== 6)) dates.push(localDateKey(cur))
 cur.setDate(cur.getDate() + 1)
 }
 return dates
}

function fmtShort(d: string) {
 return new Date(d +'T00:00:00').toLocaleDateString('de-DE', { weekday:'short', day:'2-digit', month:'2-digit'})
}

const cls ='w-full h-8 rounded border border-muted text-[13px] text-foreground px-2 bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary'
const clsErr ='w-full h-8 rounded border border-destructive text-[13px] text-foreground px-2 bg-card focus:outline-none focus:border-destructive focus:ring-1 focus:ring-destructive'
const lbl ='block text-[12px] font-medium text-foreground mb-1'

export default function CreateAssignmentModal({
 consultantId, date, endDate, consultants, appointmentTypes, planningProjects, onClose, onCreated,
 workModeCapture,
}: Props) {
 const [startDate, setStartDate] = useState(date)
 const [selEndDate, setSelEndDate] = useState(endDate ?? date)
 const [workdaysOnly, setWorkdaysOnly] = useState(true)
 const [conId, setConId] = useState(consultantId)
 const [typeId, setTypeId] = useState(appointmentTypes[0]?.id ??'')
 const [projectId, setProjectId] = useState('')
 const [status, setStatus] = useState<AssignmentStatus>('fixed')
 const [workMode, setWorkMode] = useState<WorkMode>('onsite')
 const [desc, setDesc] = useState('')
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState<string | null>(null)
 const [showErrors, setShowErrors] = useState(false)
 const [mainProjects, setMainProjects] = useState<ProjectOption[]>([])

 const fieldErrors = {
 startDate: !startDate,
 typeId: !typeId,
 projectId: !projectId,
 }

 const targetDates = useMemo(
 () => getDatesInRange(startDate, selEndDate, workdaysOnly),
 [startDate, selEndDate, workdaysOnly],
 )
 const isRange = startDate !== selEndDate

 useEffect(() => {
 const fn = (e: KeyboardEvent) => { if (e.key ==='Escape') onClose() }
 document.addEventListener('keydown', fn)
 return () => document.removeEventListener('keydown', fn)
 }, [onClose])

 useEffect(() => {
 const supabase = createClient()
 supabase
 .from('projects')
 .select('id, project_code, supplier_name, parent_project_id, sub_project_suffix')
 .order('project_code', { ascending: false, nullsFirst: false })
 .then(({ data }) => setMainProjects((data ?? []) as ProjectOption[]))
 }, [])

 async function handleSubmit(e: React.FormEvent) {
 e.preventDefault()
 if (!startDate || !typeId || !projectId) {
 setShowErrors(true)
 return
 }
 if (targetDates.length === 0) return
 setSaving(true)
 setError(null)
 const supabase = createClient()
 const { data: { user } } = await supabase.auth.getUser()

 // Resolve planning_projects FK: upsert an entry keyed by the project code
 // so assignments.project_id always points to a valid planning_projects row
 const selectedProject = mainProjects.find(p => p.id === projectId)
 let planningProjectId: string | null = null
 if (selectedProject) {
 const { data: pp } = await supabase
 .from('planning_projects')
 .upsert(
 {
 code: selectedProject.project_code ?? selectedProject.id,
 name: selectedProject.supplier_name,
 is_active: true,
 },
 { onConflict:'code'}
 )
 .select('id')
 .single()
 planningProjectId = pp?.id ?? null
 }

 const rows = targetDates.map((d) => ({
 date: d,
 consultant_id: conId,
 appointment_type_id: typeId,
 project_id: planningProjectId,
 description: desc || null,
 // FB-36: capture disabled -> omit work_mode entirely so the DB default
 // ('onsite', NOT NULL) applies, instead of writing a value the user
 // never had a chance to set.
 ...(workModeCapture ? { work_mode: workMode } : {}),
 status,
 is_all_day: true,
 requires_travel: false,
 is_demo: false,
 source:'manual',
 created_by: user?.id ?? null,
 updated_by: user?.id ?? null,
 }))
 const { error: err } = await supabase.from('assignments').insert(rows)
 if (err) { setError(err.message); setSaving(false); return }
 onCreated()
 }

 return (
 <div
 className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4"
 onClick={(e) => e.target === e.currentTarget && onClose()}
 >
 <div className="bg-card text-foreground rounded-xl w-full max-w-md max-h-[90vh] flex flex-col">

 <div className="flex items-center justify-between px-5 py-3.5 border-b border-border shrink-0">
 <h2 className="font-semibold text-[15px] text-foreground">Einsatz anlegen</h2>
 <button onClick={onClose} type="button"className="w-7 h-7 flex items-center justify-center rounded hover:bg-muted text-[#666]">✕</button>
 </div>

 <form onSubmit={handleSubmit} className="px-5 py-4 space-y-3 overflow-y-auto flex-1">

 {/* Date range */}
 <div className="grid grid-cols-2 gap-3">
 <div>
 <label className={lbl}>Von <span className="text-destructive">*</span></label>
 <input type="date"value={startDate} onChange={(e) => { setStartDate(e.target.value); setShowErrors(false) }}
 autoFocus className={showErrors && fieldErrors.startDate ? clsErr : cls} />
 {showErrors && fieldErrors.startDate && (
 <p className="mt-0.5 text-[11px] text-destructive">Pflichtfeld</p>
 )}
 </div>
 <div>
 <label className={lbl}>Bis</label>
 <input type="date"value={selEndDate} min={startDate}
 onChange={(e) => setSelEndDate(e.target.value)} className={cls} />
 </div>
 </div>

 {/* Range preview */}
 {isRange && (
 <div className="flex items-center justify-between text-[12px]">
 <label className="flex items-center gap-2 text-[#555] cursor-pointer select-none">
 <input type="checkbox"checked={workdaysOnly} onChange={(e) => setWorkdaysOnly(e.target.checked)}
 className="w-3.5 h-3.5 accent-primary"/>
 Nur Werktage
 </label>
 {targetDates.length > 0 ? (
 <span className="text-primary font-medium">
 {targetDates.length} Einsatz{targetDates.length !== 1 ?'e':''}
 {''}· {fmtShort(targetDates[0])} – {fmtShort(targetDates[targetDates.length - 1])}
 </span>
 ) : (
 <span className="text-destructive">Kein gültiger Bereich</span>
 )}
 </div>
 )}

 {/* Consultant */}
 <div>
 <label className={lbl}>Mitarbeiter *</label>
 <select value={conId} onChange={(e) => setConId(e.target.value)} required className={cls}>
 {consultants.filter((c) => c.is_active).map((c) => (
 <option key={c.id} value={c.id}>{c.display_name}</option>
 ))}
 </select>
 </div>

 {/* Appointment type */}
 <div>
 <label className={lbl}>Auftragsart <span className="text-destructive">*</span></label>
 <select value={typeId} onChange={(e) => { setTypeId(e.target.value); setShowErrors(false) }}
 className={showErrors && fieldErrors.typeId ? clsErr : cls}>
 <option value="">— Bitte wählen —</option>
 {appointmentTypes.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
 </select>
 {showErrors && fieldErrors.typeId && (
 <p className="mt-0.5 text-[11px] text-destructive">Pflichtfeld</p>
 )}
 </div>

 {/* Project — required, grouped with sub-projects */}
 <div>
 <label className={lbl}>Projekt <span className="text-destructive">*</span></label>
 <select
 value={projectId}
 onChange={(e) => { setProjectId(e.target.value); setShowErrors(false) }}
 className={showErrors && fieldErrors.projectId ? clsErr : cls}
 >
 <option value="">— Projekt wählen —</option>
 {mainProjects.length > 0 ? (() => {
 const topLevel = mainProjects.filter(p => !p.parent_project_id)
 const subMap = new Map<string, ProjectOption[]>()
 for (const p of mainProjects) {
 if (p.parent_project_id) {
 const list = subMap.get(p.parent_project_id) ?? []
 list.push(p)
 subMap.set(p.parent_project_id, list)
 }
 }
 return topLevel.map(p => {
 const subs = subMap.get(p.id) ?? []
 const label = `${p.project_code ??'—'} — ${p.supplier_name}`
 if (subs.length === 0) {
 return <option key={p.id} value={p.id}>{label}</option>
 }
 return (
 <optgroup key={p.id} label={label}>
 <option value={p.id}>{label} (Gesamt)</option>
 {subs.map(s => (
 <option key={s.id} value={s.id}>
 {s.sub_project_suffix} · {s.project_code ??'—'} — {s.supplier_name}
 </option>
 ))}
 </optgroup>
 )
 })
 })() : planningProjects.map((p) => <option key={p.id} value={p.id}>{p.code} — {p.name}</option>)}
 </select>
 {showErrors && fieldErrors.projectId && (
 <p className="mt-0.5 text-[11px] text-destructive">Pflichtfeld</p>
 )}
 </div>

 {/* Status */}
 <div>
 <label className={lbl}>Status *</label>
 <select value={status} onChange={(e) => setStatus(e.target.value as AssignmentStatus)} required className={cls}>
 <option value="fixed">Fest</option>
 <option value="tentative">Vorläufig</option>
 <option value="critical">Kritisch</option>
 <option value="cancelled">Storniert</option>
 </select>
 </div>

 {/* Work mode — FB-36: hidden entirely when capture is disabled by profile */}
 {workModeCapture && (
 <div>
 <label className={lbl}>Arbeitsort *</label>
 <div className="flex gap-4">
 {(['onsite','homeoffice','remote'] as WorkMode[]).map((m) => (
 <label key={m} className="flex items-center gap-1.5 text-[13px] cursor-pointer select-none">
 <input type="radio"name="workMode"value={m} checked={workMode === m}
 onChange={() => setWorkMode(m)} className="accent-primary"/>
 {m ==='onsite'?'Vor Ort': m ==='homeoffice'?'Homeoffice':'Remote'}
 </label>
 ))}
 </div>
 </div>
 )}

 {/* Description */}
 <div>
 <label className={lbl}>Bemerkung</label>
 <textarea value={desc} onChange={(e) => setDesc(e.target.value)} rows={2}
 className="w-full rounded border border-muted text-[13px] text-foreground px-2 py-1.5 bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary resize-none"/>
 </div>

 {error && <p className="text-[12px] text-destructive bg-status-red-soft border border-status-red-strong rounded px-2.5 py-1.5">{error}</p>}
 </form>

 <div className="flex justify-end gap-2 px-5 py-3 border-t border-border shrink-0">
 <button type="button"onClick={onClose}
 className="h-8 px-4 text-[13px] font-medium rounded border border-muted text-foreground hover:bg-muted">
 Abbrechen
 </button>
 <button type="button"
 disabled={saving || targetDates.length === 0}
 onClick={handleSubmit as unknown as React.MouseEventHandler}
 className="h-8 px-4 text-[13px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50">
 {saving ?'Speichern…': targetDates.length > 1 ? `${targetDates.length} Einsätze anlegen` :'Einsatz speichern'}
 </button>
 </div>
 </div>
 </div>
 )
}
