'use client'

import { useState } from'react'
import { Download } from'lucide-react'

type ExportType ='calculator'|'trends'|'verlustanalyse'

interface TrendRow {
 kw: number
 year: number
 line_name: string
 oee_factor: number | null
 availability_factor: number | null
 performance_factor: number | null
 quality_factor: number | null
 good_output: number | null
 theoretical_output: number | null
 installed_capacity: number | null
 purchased_capacity: number | null
 unplanned_downtime_min: number | null
}

interface CalcData {
 lineName: string
 kw: number
 year: number
 allTimeMin: number
 plannedBreakMin: number
 plannedDowntimeMin: number
 unplannedDowntimeMin: number
 setupMin: number
 maintenanceMin: number
 otherLossMin: number
 actualProdMin: number
 theoreticalOutput: number
 producedOutput: number
 goodOutput: number
 availability: number
 performance: number
 quality: number
 oee: number
}

interface LossRow {
 category: string
 minutes: number
 pctOfTotal: number
 pctOfLoss: number
}

type ExportData =
 | { type:'calculator'; data: CalcData; fileName?: string }
 | { type:'trends'; data: TrendRow[]; fileName?: string }
 | { type:'verlustanalyse'; data: LossRow[]; lineName: string; kw: number; year: number; fileName?: string }

interface Props {
 exportData: ExportData
}

// brand primary fill
const BRAND_PRIMARY = { argb:'FF0066B1'}
const WHITE = { argb:'FFFFFFFF'}
const LIGHT_BLUE = { argb:'FFE6F0F8'}
const BORDER_COLOR = { argb:'FFE0E6ED'}

export default function OeeExportButton({ exportData }: Props) {
 const [loading, setLoading] = useState(false)

 async function handleExport() {
 setLoading(true)
 try {
 const ExcelJS = (await import('exceljs')).default
 const wb = new ExcelJS.Workbook()
 wb.creator ='SupplierDev OEE'
 wb.created = new Date()

 if (exportData.type ==='calculator') {
 const d = exportData.data
 const ws = wb.addWorksheet('OEE Berechnung')

 // Header row
 ws.addRow(['OEE Berechnung', `KW ${d.kw}/${d.year}`, d.lineName])
 ws.mergeCells('A1:B1')
 const headerRow = ws.getRow(1)
 headerRow.eachCell(cell => {
 cell.fill = { type:'pattern', pattern:'solid', fgColor: BRAND_PRIMARY }
 cell.font = { color: WHITE, bold: true, size: 12, name:'Calibri'}
 cell.alignment = { vertical:'middle', horizontal:'left'}
 })
 headerRow.height = 24

 ws.addRow([]) // spacer

 const sections = [
 ['Zeitbasis',''],
 ['Gesamtverfügbare Zeit (min)', d.allTimeMin],
 ['Geplante Pausen (min)', d.plannedBreakMin],
 ['Geplante Stillstände (min)', d.plannedDowntimeMin],
 ['Ungeplante Stillstände (min)', d.unplannedDowntimeMin],
 ['Rüstzeit (min)', d.setupMin],
 ['Wartungszeit (min)', d.maintenanceMin],
 ['Sonstige Verluste (min)', d.otherLossMin],
 ['Produktionszeit (min)', d.actualProdMin],
 ['',''],
 ['Ausbringung',''],
 ['Theoretische Ausbringung', d.theoreticalOutput],
 ['Produzierte Menge', d.producedOutput],
 ['Gutmenge', d.goodOutput],
 ['',''],
 ['OEE Faktoren',''],
 ['Verfügbarkeit', `${(d.availability * 100).toFixed(2)} %`],
 ['Leistung', `${(d.performance * 100).toFixed(2)} %`],
 ['Qualität', `${(d.quality * 100).toFixed(2)} %`],
 ['OEE', `${(d.oee * 100).toFixed(2)} %`],
 ]

 for (const [label, value] of sections) {
 const row = ws.addRow([label, value])
 if (label && !value) {
 // section header
 row.getCell(1).fill = { type:'pattern', pattern:'solid', fgColor: LIGHT_BLUE }
 row.getCell(1).font = { bold: true, size: 10, name:'Calibri'}
 } else if (label) {
 row.getCell(1).font = { size: 10, name:'Calibri'}
 row.getCell(2).font = { size: 10, name:'Calibri'}
 }
 row.eachCell(cell => {
 cell.border = {
 bottom: { style:'thin', color: BORDER_COLOR },
 }
 })
 }

 ws.getColumn(1).width = 35
 ws.getColumn(2).width = 20
 ws.views = [{ state:'frozen', ySplit: 1 }]

 } else if (exportData.type ==='trends') {
 const ws = wb.addWorksheet('OEE Trenddaten')

 const headers = ['KW','Jahr','Linie','OEE %','Verfügbarkeit %','Leistung %','Qualität %','Gutmenge','Theor. Ausbringung','Install. Kapazität','Eingek. Kapazität','Ungeplante Stillst. (min)']
 const headerRow = ws.addRow(headers)
 headerRow.eachCell(cell => {
 cell.fill = { type:'pattern', pattern:'solid', fgColor: BRAND_PRIMARY }
 cell.font = { color: WHITE, bold: true, size: 10, name:'Calibri'}
 cell.alignment = { vertical:'middle', horizontal:'center'}
 })
 headerRow.height = 22

 for (const row of exportData.data) {
 const r = ws.addRow([
 row.kw, row.year, row.line_name,
 row.oee_factor != null ? +(row.oee_factor * 100).toFixed(2) : null,
 row.availability_factor != null ? +(row.availability_factor * 100).toFixed(2) : null,
 row.performance_factor != null ? +(row.performance_factor * 100).toFixed(2) : null,
 row.quality_factor != null ? +(row.quality_factor * 100).toFixed(2) : null,
 row.good_output, row.theoretical_output,
 row.installed_capacity, row.purchased_capacity,
 row.unplanned_downtime_min,
 ])
 r.eachCell({ includeEmpty: true }, (cell, col) => {
 cell.font = { size: 10, name:'Calibri'}
 if (col >= 4 && col <= 7) {
 cell.numFmt ='0.00"%"'
 }
 })
 }

 ws.columns.forEach(col => { col.width = 16 })
 ws.getColumn(3).width = 20
 ws.views = [{ state:'frozen', ySplit: 1 }]

 } else {
 // verlustanalyse
 const ws = wb.addWorksheet('Verlustanalyse')
 const title = `${exportData.lineName} · KW ${exportData.kw}/${exportData.year}`
 ws.addRow(['Verlustanalyse', title])
 const headerRow = ws.getRow(1)
 headerRow.eachCell(cell => {
 cell.fill = { type:'pattern', pattern:'solid', fgColor: BRAND_PRIMARY }
 cell.font = { color: WHITE, bold: true, size: 12, name:'Calibri'}
 })
 headerRow.height = 22

 ws.addRow([])
 const colHeader = ws.addRow(['Verlusttyp','Minuten','% Gesamtzeit','% Verluste'])
 colHeader.eachCell(cell => {
 cell.fill = { type:'pattern', pattern:'solid', fgColor: LIGHT_BLUE }
 cell.font = { bold: true, size: 10, name:'Calibri'}
 })

 for (const row of exportData.data) {
 const r = ws.addRow([row.category, Math.round(row.minutes), +row.pctOfTotal.toFixed(1), +row.pctOfLoss.toFixed(1)])
 r.eachCell(cell => { cell.font = { size: 10, name:'Calibri'} })
 r.getCell(3).numFmt ='0.0"%"'
 r.getCell(4).numFmt ='0.0"%"'
 }

 ws.getColumn(1).width = 30
 ws.getColumn(2).width = 16
 ws.getColumn(3).width = 18
 ws.getColumn(4).width = 16
 ws.views = [{ state:'frozen', ySplit: 3 }]
 }

 const buffer = await wb.xlsx.writeBuffer()
 const blob = new Blob([buffer], { type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
 const url = URL.createObjectURL(blob)
 const a = document.createElement('a')
 a.href = url
 a.download = exportData.fileName ?? `oee-export-${Date.now()}.xlsx`
 a.click()
 URL.revokeObjectURL(url)
 } finally {
 setLoading(false)
 }
 }

 return (
 <button
 type="button"
 onClick={() => void handleExport()}
 disabled={loading}
 className="flex items-center gap-2 h-9 px-4 rounded-lg border border-border bg-card text-sm text-muted-foreground hover:bg-background hover:border-secondary disabled:opacity-50 transition-colors"
 >
 <Download size={14} />
 {loading ?'Exportiert…':'Excel Export'}
 </button>
 )
}
