/**
 * Export utilities for the planning grid.
 *
 * exportGridToExcel  — produces an .xlsx file matching the visible grid
 * triggerPrintGrid   — opens browser print dialog targeting a DOM element id
 */

import type { Assignment, Consultant, AppointmentType, PlanningProject } from '@/lib/planning-types'
import { getMonthDays, formatDateKey, DAY_ABBREV, getISOWeek, groupDaysByWeek } from '@/lib/planning-config'

// ── Excel export ──────────────────────────────────────────────────────────────

export async function exportGridToExcel(opts: {
  year: number
  month: number
  consultants: Consultant[]
  assignments: Assignment[]
  appointmentTypes: AppointmentType[]
  planningProjects: PlanningProject[]
}) {
  const { year, month, consultants, assignments, appointmentTypes, planningProjects } = opts

  const ExcelJS = (await import('exceljs')).default
  const wb = new ExcelJS.Workbook()
  const ws = wb.addWorksheet(`Planung ${year}-${String(month).padStart(2, '0')}`)

  const days       = getMonthDays(year, month)
  const weekGroups = groupDaysByWeek(days)
  const typeMap    = new Map(appointmentTypes.map((t) => [t.id, t]))
  const projMap    = new Map(planningProjects.map((p) => [p.id, p]))

  // Build assignment map
  const aMap = new Map<string, Assignment[]>()
  for (const a of assignments) {
    const k = `${a.consultant_id}:${a.date}`
    aMap.set(k, [...(aMap.get(k) ?? []), a])
  }

  // ── Column widths ─────────────────────────────────────────────────────────
  ws.columns = [
    { width: 22 },                         // Name col
    ...days.map(() => ({ width: 9 })),     // Day cols
  ]

  // ── Row 1: KW headers ────────────────────────────────────────────────────
  const kwRow = ws.addRow([
    'Mitarbeiter',
    ...weekGroups.flatMap(({ kw, days: wd }) => [`KW ${kw}`, ...Array(wd.length - 1).fill('')]),
  ])
  kwRow.height = 16
  kwRow.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF00274D' } }
  kwRow.getCell(1).font = { bold: true, color: { argb: 'FFFFFFFF' }, size: 9 }

  let col = 2
  for (const { kw, days: wd } of weekGroups) {
    const cell = kwRow.getCell(col)
    cell.value = `KW ${kw}`
    cell.fill  = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF003D6B' } }
    cell.font  = { bold: true, color: { argb: 'FFFFFFFF' }, size: 9 }
    cell.alignment = { horizontal: 'center' }
    if (wd.length > 1) ws.mergeCells(1, col, 1, col + wd.length - 1)
    col += wd.length
  }

  // ── Row 2: Day headers ────────────────────────────────────────────────────
  const dayRow = ws.addRow([
    '',
    ...days.map((d) => `${DAY_ABBREV[d.getDay()]} ${d.getDate()}`),
  ])
  dayRow.height = 20
  dayRow.eachCell((cell, c) => {
    if (c === 1) return
    const d = days[c - 2]
    const isWeekend = d.getDay() === 0 || d.getDay() === 6
    cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: isWeekend ? 'FFEFEFEF' : 'FFF5F5F5' } }
    cell.font = { bold: true, size: 8, color: { argb: isWeekend ? 'FF999999' : 'FF333333' } }
    cell.alignment = { horizontal: 'center', vertical: 'middle' }
  })

  ws.views = [{ state: 'frozen', ySplit: 2, xSplit: 1 }]

  // ── Data rows ─────────────────────────────────────────────────────────────
  for (const [ci, consultant] of consultants.entries()) {
    const rowData: string[] = [consultant.display_name]

    for (const day of days) {
      const key  = `${consultant.id}:${formatDateKey(day)}`
      const list = aMap.get(key) ?? []

      if (list.length === 0) {
        rowData.push('')
      } else {
        const lines = list.map((a) => {
          const proj = a.project_id ? projMap.get(a.project_id) : null
          const type = typeMap.get(a.appointment_type_id)
          return proj ? proj.code : (type?.code ?? '?')
        })
        rowData.push(lines.join(' / '))
      }
    }

    const row = ws.addRow(rowData)
    row.height = 18

    // Name cell style
    const nameCell = row.getCell(1)
    nameCell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: ci % 2 === 0 ? 'FFFFFFFF' : 'FFFAFAFA' } }
    nameCell.font = { bold: true, size: 9 }

    // Day cells
    for (let i = 0; i < days.length; i++) {
      const cell = row.getCell(i + 2)
      const key  = `${consultant.id}:${formatDateKey(days[i])}`
      const list = aMap.get(key) ?? []
      const d    = days[i]
      const isWeekend = d.getDay() === 0 || d.getDay() === 6

      cell.font      = { size: 8 }
      cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: false }

      if (list.length > 0) {
        const firstType = typeMap.get(list[0].appointment_type_id)
        const hex = (firstType?.color ?? '#E5E5E5').replace('#', 'FF')
        cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: hex } }
        cell.font = { size: 8, color: { argb: 'FF333333' } }
      } else if (isWeekend) {
        cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFEBEBEB' } }
      } else {
        cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: ci % 2 === 0 ? 'FFE8E8E8' : 'FFE0E0E0' } }
      }
    }
  }

  // ── Add thin borders ──────────────────────────────────────────────────────
  const totalRows = ws.rowCount
  const totalCols = days.length + 1
  for (let r = 1; r <= totalRows; r++) {
    for (let c = 1; c <= totalCols; c++) {
      ws.getRow(r).getCell(c).border = {
        top:    { style: 'thin', color: { argb: 'FFD6D6D6' } },
        bottom: { style: 'thin', color: { argb: 'FFD6D6D6' } },
        left:   { style: 'thin', color: { argb: 'FFD6D6D6' } },
        right:  { style: 'thin', color: { argb: 'FFD6D6D6' } },
      }
    }
  }

  // ── Download ──────────────────────────────────────────────────────────────
  const buf  = await wb.xlsx.writeBuffer()
  const blob = new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const url  = URL.createObjectURL(blob)
  const a    = document.createElement('a')
  a.href     = url
  a.download = `Einsatzplanung_${year}-${String(month).padStart(2, '0')}.xlsx`
  a.click()
  URL.revokeObjectURL(url)
}

// ── Print / PDF export ────────────────────────────────────────────────────────

/**
 * Injects a temporary print stylesheet that hides everything except
 * the element with the given id, then opens the print dialog.
 */
export function triggerPrintGrid(elementId: string, title: string) {
  const styleId = '__print_override__'
  if (!document.getElementById(styleId)) {
    const style = document.createElement('style')
    style.id = styleId
    style.media = 'print'
    style.textContent = `
      body > * { display: none !important; }
      #${elementId} { display: block !important; }
      #${elementId} { position: fixed; inset: 0; overflow: visible; background: white; }
      @page { margin: 10mm; size: landscape; }
    `
    document.head.appendChild(style)
  }

  const old = document.title
  document.title = title
  window.print()
  document.title = old
}
