// tdd-guard:skip — React component; pure import logic tested via lib/lsc/__tests__/workshop-import.test.ts
'use client'

import { useState } from 'react'
import ExcelJS from 'exceljs'
import {
  parseWorkshopImportRows,
  type ParsedWorkshopRow,
  type WorkshopImportRow,
} from '@/lib/lsc/workshop-import'

interface ProcessStepInfo {
  id: string
  station_name: string
}

interface Props {
  steps: ProcessStepInfo[]
  existingStepIds: Set<string>
  onClose: () => void
  onApply: (rows: ParsedWorkshopRow[]) => Promise<void>
}

/** Download an empty import template. */
async function downloadTemplate(): Promise<void> {
  const ExcelJSDyn = (await import('exceljs')).default
  const wb = new ExcelJSDyn.Workbook()
  const ws = wb.addWorksheet('Workshop-Import')
  ws.columns = [
    { header: 'Station', key: 'station', width: 30 },
    { header: 'Beobachtete CT (s)', key: 'observed_ct', width: 20 },
    { header: 'Mögliche CT (s)', key: 'possible_ct', width: 20 },
    { header: 'Bemerkung', key: 'comment', width: 40 },
  ]
  const headerRow = ws.getRow(1)
  headerRow.eachCell((cell) => {
    cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF037493' } }
    cell.font = { color: { argb: 'FFFFFFFF' }, bold: true }
    cell.alignment = { vertical: 'middle' }
  })
  ws.views = [{ state: 'frozen', ySplit: 1 }]
  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 = 'workshop-import-vorlage.xlsx'
  a.click()
  URL.revokeObjectURL(url)
}

const ACTION_LABELS: Record<'create' | 'update' | 'skip', string> = {
  create: 'Neu',
  update: 'Aktualisieren',
  skip: 'Überspringen',
}

const ACTION_CLASSES: Record<'create' | 'update' | 'skip', string> = {
  create: 'text-success',
  update: 'text-primary',
  skip: 'text-muted-foreground',
}

export default function WorkshopImportModal({ steps, existingStepIds, onClose, onApply }: Props) {
  const [preview, setPreview] = useState<ParsedWorkshopRow[] | null>(null)
  const [errors, setErrors] = useState<string[]>([])
  const [applying, setApplying] = useState(false)
  const [downloadingTemplate, setDownloadingTemplate] = useState(false)

  // Build station lookup map (lower-cased name → step id)
  const stationMap = new Map<string, string>(
    steps.map((s) => [s.station_name.toLowerCase().trim(), s.id]),
  )

  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    const buf = await file.arrayBuffer()
    const wb = new ExcelJS.Workbook()
    await wb.xlsx.load(buf)
    const ws = wb.worksheets[0]
    const rawRows: WorkshopImportRow[] = []

    ws.eachRow((row, idx) => {
      if (idx === 1) return // skip header
      const cell = (col: number) => {
        const c = row.getCell(col)
        // Prefer cell.result for formula cells
        const val =
          c.type === ExcelJS.ValueType.Formula && c.result != null ? c.result : c.value
        return String(val ?? '').trim()
      }
      rawRows.push({
        stationName: cell(1),
        observedCtRaw: cell(2),
        possibleCtRaw: cell(3),
        comment: cell(4),
        rowIndex: idx,
      })
    })

    const result = parseWorkshopImportRows(rawRows, stationMap, existingStepIds)
    setPreview(result.rows)
    setErrors(result.errors)
  }

  async function handleApply() {
    if (!preview || preview.length === 0) return
    setApplying(true)
    try {
      await onApply(preview.filter((r) => r.action !== 'skip'))
    } finally {
      setApplying(false)
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose()
      }}
    >
      <div className="bg-card text-foreground rounded-md w-full max-w-3xl mx-4 p-5 space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-bold text-foreground">
            Workshop-Daten importieren
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="text-muted-foreground hover:text-foreground text-xs"
          >
            ✕
          </button>
        </div>

        {!preview ? (
          <div className="space-y-4">
            <p className="text-xs text-muted-foreground">
              Vorlage herunterladen, ausfüllen und hier hochladen.
              Spalten: <strong>Station | Beobachtete CT (s) | Mögliche CT (s) | Bemerkung</strong>.
              Die Station muss exakt einer Station im Projekt entsprechen (Groß-/Kleinschreibung egal).
            </p>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={() => {
                  setDownloadingTemplate(true)
                  void downloadTemplate().finally(() => setDownloadingTemplate(false))
                }}
                disabled={downloadingTemplate}
                className="h-8 px-3 rounded-sm border border-border text-xs text-foreground hover:bg-muted transition-colors disabled:opacity-50"
              >
                {downloadingTemplate ? 'Wird erstellt…' : 'Vorlage herunterladen'}
              </button>
            </div>
            <input
              type="file"
              accept=".xlsx,.xls"
              onChange={(e) => void handleFile(e)}
              className="block w-full text-xs text-muted-foreground file:mr-3 file:py-1.5 file:px-3 file:rounded-sm file:border file:border-border file:text-xs file:font-medium file:text-primary file:bg-card hover:file:bg-muted"
            />
            <div className="flex justify-end">
              <button
                type="button"
                onClick={onClose}
                className="h-8 px-4 rounded-sm border border-border text-xs text-muted-foreground hover:bg-muted transition-colors"
              >
                Abbrechen
              </button>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            {errors.length > 0 && (
              <div className="bg-destructive/10 border border-destructive rounded-sm p-3 space-y-1">
                <p className="text-xs font-semibold text-destructive">
                  {errors.length} Fehler / Warnungen:
                </p>
                <ul className="list-disc list-inside text-xs text-destructive space-y-0.5">
                  {errors.map((e, i) => (
                    <li key={i}>{e}</li>
                  ))}
                </ul>
              </div>
            )}

            {preview.length > 0 ? (
              <div className="overflow-x-auto max-h-72 border border-border rounded-sm">
                <table className="w-full text-xs">
                  <thead className="bg-background border-b border-border sticky top-0">
                    <tr>
                      <th className="text-left px-3 py-2 font-semibold text-muted-foreground">
                        Aktion
                      </th>
                      <th className="text-left px-3 py-2 font-semibold text-muted-foreground">
                        Station
                      </th>
                      <th className="text-right px-3 py-2 font-semibold text-muted-foreground">
                        Beobachtete CT (s)
                      </th>
                      <th className="text-right px-3 py-2 font-semibold text-muted-foreground">
                        Mögliche CT (s)
                      </th>
                      <th className="text-left px-3 py-2 font-semibold text-muted-foreground">
                        Bemerkung
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {preview.map((row) => (
                      <tr key={row.rowIndex} className="hover:bg-muted/50">
                        <td
                          className={`px-3 py-1.5 font-semibold ${ACTION_CLASSES[row.action]}`}
                        >
                          {ACTION_LABELS[row.action]}
                        </td>
                        <td className="px-3 py-1.5 text-foreground font-medium">
                          {row.stationName}
                        </td>
                        <td className="px-3 py-1.5 text-right font-condensed text-foreground">
                          {row.observed_ct_sec ?? '—'}
                        </td>
                        <td className="px-3 py-1.5 text-right font-condensed text-foreground">
                          {row.possible_ct_sec ?? '—'}
                        </td>
                        <td className="px-3 py-1.5 text-muted-foreground">
                          {row.comment ?? '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-xs text-muted-foreground text-center py-4">
                Keine gültigen Zeilen gefunden.
              </p>
            )}

            <p className="text-xs text-muted-foreground">
              {preview.length} gültige Zeile(n) · {errors.length} Fehler/Warnung(en)
            </p>

            <div className="flex gap-2 justify-end">
              <button
                type="button"
                onClick={() => {
                  setPreview(null)
                  setErrors([])
                }}
                className="h-8 px-4 rounded-sm border border-border text-xs text-muted-foreground hover:bg-muted transition-colors"
              >
                Andere Datei wählen
              </button>
              <button
                type="button"
                onClick={onClose}
                className="h-8 px-4 rounded-sm border border-border text-xs text-muted-foreground hover:bg-muted transition-colors"
              >
                Abbrechen
              </button>
              <button
                type="button"
                onClick={() => void handleApply()}
                disabled={applying || preview.length === 0}
                className="h-8 px-4 rounded-sm bg-primary text-white text-xs font-semibold hover:bg-primary-hover transition-colors disabled:opacity-50"
              >
                {applying ? 'Wird importiert…' : `${preview.length} Zeile(n) importieren`}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
