import { buildPlanPayloadForSave, defaultSection } from './trainingUnitSectionsForm'
import { sessionAssignDefaults } from './trainingPlanningPageHelpers'

/** Leeres Formular für neue Einheit (ohne async Varianten-Anreicherung). */
export function createEmptyTrainingUnitFormData({
  groupId = '',
  plannedDate = '',
  timeStart = '',
  timeEnd = '',
} = {}) {
  return {
    group_id: groupId != null ? String(groupId) : '',
    planned_date: plannedDate || '',
    planned_time_start: timeStart || '',
    planned_time_end: timeEnd || '',
    planned_focus: '',
    actual_date: '',
    actual_time_start: '',
    actual_time_end: '',
    attendance_count: '',
    status: 'planned',
    notes: '',
    trainer_notes: '',
    debrief_completed: false,
    sections: [defaultSection('Hauptteil')],
    ...sessionAssignDefaults(),
  }
}

/**
 * API-Zeile → Formular (sync). `sections` müssen vorher via normalizeUnitToForm + enrich kommen.
 * @param {object} fullUnit
 * @param {object} sections — bereits angereicherte Editor-Sections
 */
export function trainingUnitToFormFields(fullUnit, sections) {
  const efLead =
    fullUnit.effective_lead_trainer_profile_id != null
      ? Number(fullUnit.effective_lead_trainer_profile_id)
      : null
  let assistantIds = []
  if (Array.isArray(fullUnit.assistant_trainer_profile_ids)) {
    assistantIds = fullUnit.assistant_trainer_profile_ids
      .map((x) => Number(x))
      .filter((n) => Number.isFinite(n) && n >= 1)
  }
  if (efLead != null && Number.isFinite(efLead)) {
    assistantIds = assistantIds.filter((id) => id !== efLead)
  }

  return {
    group_id: fullUnit.group_id,
    planned_date: fullUnit.planned_date || '',
    planned_time_start: fullUnit.planned_time_start?.slice?.(0, 5) || fullUnit.planned_time_start || '',
    planned_time_end: fullUnit.planned_time_end?.slice?.(0, 5) || fullUnit.planned_time_end || '',
    planned_focus: fullUnit.planned_focus || '',
    actual_date: fullUnit.actual_date || '',
    actual_time_start: fullUnit.actual_time_start?.slice?.(0, 5) || fullUnit.actual_time_start || '',
    actual_time_end: fullUnit.actual_time_end?.slice?.(0, 5) || fullUnit.actual_time_end || '',
    attendance_count: fullUnit.attendance_count ?? '',
    status: fullUnit.status || 'planned',
    notes: fullUnit.notes || '',
    trainer_notes: fullUnit.trainer_notes || '',
    debrief_completed: Boolean(fullUnit.debrief_completed_at),
    sections,
    lead_trainer_profile_id:
      fullUnit.lead_trainer_profile_id != null && fullUnit.lead_trainer_profile_id !== ''
        ? String(fullUnit.lead_trainer_profile_id)
        : '',
    session_assistants_inherit:
      fullUnit.assistant_trainer_profile_ids == null ||
      fullUnit.assistant_trainer_profile_ids === undefined,
    session_assistant_profile_ids: assistantIds,
  }
}

/**
 * Formular → API-Payload (identisch zur bisherigen Modal-Logik).
 * @param {object} formData
 * @param {{ editingUnit?: object|null, draftPlanTemplateId?: string }} opts
 */
export function buildTrainingUnitSavePayload(formData, { editingUnit = null, draftPlanTemplateId = '' } = {}) {
  const planPart = buildPlanPayloadForSave(formData.sections)
  const payload = {
    planned_date: formData.planned_date,
    planned_time_start: formData.planned_time_start || null,
    planned_time_end: formData.planned_time_end || null,
    planned_focus: formData.planned_focus || null,
    actual_date: formData.actual_date || null,
    actual_time_start: formData.actual_time_start || null,
    actual_time_end: formData.actual_time_end || null,
    attendance_count: formData.attendance_count ? parseInt(formData.attendance_count, 10) : null,
    status: formData.status || 'planned',
    notes: formData.notes || null,
    trainer_notes: formData.trainer_notes || null,
    ...planPart,
  }

  if (editingUnit) {
    payload.debrief_completed =
      (formData.status || '') === 'completed' ? !!formData.debrief_completed : false
  }

  const leadStr = String(formData.lead_trainer_profile_id || '').trim()
  if (leadStr) {
    payload.lead_trainer_profile_id = parseInt(leadStr, 10)
  } else if (editingUnit) {
    payload.lead_trainer_profile_id = null
  }

  if (formData.session_assistants_inherit) {
    if (editingUnit) payload.assistant_trainer_profile_ids = null
  } else {
    payload.assistant_trainer_profile_ids = [...(formData.session_assistant_profile_ids || [])].sort(
      (a, b) => a - b
    )
  }

  if (!editingUnit) {
    payload.group_id = parseInt(formData.group_id, 10)
    if (draftPlanTemplateId) {
      payload.plan_template_id = parseInt(draftPlanTemplateId, 10)
    }
  }

  return payload
}

export function validateTrainingUnitFormForSave(formData) {
  if (!formData?.group_id || !formData?.planned_date) {
    return { ok: false, message: 'Gruppe und Datum sind Pflichtfelder' }
  }
  return { ok: true }
}

/** Stabiler Fingerabdruck für Dirty-Check (identisch zum Save-Payload). */
export function trainingUnitFormSnapshot(
  formData,
  { editingUnit = null, draftPlanTemplateId = '' } = {}
) {
  return JSON.stringify(buildTrainingUnitSavePayload(formData, { editingUnit, draftPlanTemplateId }))
}
