'use client'
// tdd-guard:skip — export orchestration UI; avg-cycle-time logic lives in lib/reporting/aggregations.ts (tested).

import { useState } from'react'
import { FileDown, Printer, FileText } from'lucide-react'
import { formatTypeLabels, getTypeCodes } from'@/lib/project-types/labels'
import { avgCycleTimeSec } from '@/lib/reporting/aggregations'

// ─── Types ───────────────────────────────────────────────────────────────────

interface ProjectStatus { id: string; code: string; label: string }
interface ProjectTypeAssignment { project_type_code: string }
interface SupplierData { supplier_name: string; city: string | null; country: string | null }

interface Project {
 id: string
 project_code: string | null
 supplier_name: string
 product_name: string | null
 customer_takt_time_sec: number | null
 target_cycle_time_sec: number | null
 visit_date: string | null
 expected_end_date: string | null
 project_type_assignments: ProjectTypeAssignment[] | null
 project_statuses: ProjectStatus | ProjectStatus[] | null
 supplier_master_data: SupplierData | SupplierData[] | null
}

interface ConsultantData { id: string; display_name: string | null; first_name: string | null; last_name: string | null }
interface Member { consultant_id: string; role_in_project: string; consultants: ConsultantData | ConsultantData[] | null }
interface Step { id: string; station_name: string; step_number: number; sort_order: number; area_name: string | null; planned_cycle_time_sec: number | null }
interface Measurement { process_step_id: string; cycle_time_sec: number; is_outlier: boolean }
interface LscShift { id: string; area_name: string; shift_number: number; shift_start: string; shift_end: string; planned_breaks_min: number; planned_downtime_min: number; setup_min: number; other_losses_min: number }
interface LscMeasure { id: string; title: string; description: string | null; responsible: string | null; due_date: string | null; status: string; priority: string; effort_level: number | null; benefit_level: number | null }

interface Props {
 project: Project
 members: Member[]
 steps: Step[]
 measurements: Measurement[]
 shifts: LscShift[]
 measures: LscMeasure[]
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function resolveOne<T>(v: T | T[] | null): T | null {
 if (!v) return null
 return Array.isArray(v) ? (v[0] ?? null) : v
}

function consultantName(c: ConsultantData): string {
 return c.display_name ?? ([c.first_name, c.last_name].filter(Boolean).join('') ||'—')
}

function fmtDate(iso: string | null | undefined): string {
 if (!iso) return'—'
 return new Date(iso).toLocaleDateString('de-DE', { day:'2-digit', month:'2-digit', year:'numeric'})
}

function shiftDurationMin(s: LscShift): number {
 const [sh, sm] = s.shift_start.split(':').map(Number)
 const [eh, em] = s.shift_end.split(':').map(Number)
 let dur = (eh * 60 + em) - (sh * 60 + sm)
 if (dur <= 0) dur += 24 * 60
 return dur
}

function netProdMin(s: LscShift): number {
 return Math.max(0, shiftDurationMin(s) - s.planned_breaks_min - s.planned_downtime_min - s.setup_min - s.other_losses_min)
}

const ROLE_LABELS: Record<string, string> = {
 lead:'Projektleiter', collaborator:'Berater',
 einkauf:'Einkauf', qmt:'QMT', cost_engineering:'Cost Engineering',
}
const STATUS_DE: Record<string, string> = { offen:'Offen', in_arbeit:'In Arbeit', erledigt:'Erledigt'}
const PRIORITY_DE: Record<string, string> = { hoch:'Hoch', mittel:'Mittel', niedrig:'Niedrig'}

// ─── Component ───────────────────────────────────────────────────────────────

export default function LscExportClient({ project, members, steps, measurements, shifts, measures }: Props) {
 const [showReport, setShowReport] = useState(false)
 const [exportingPpt, setExportingPpt] = useState(false)

 const typeLabel = formatTypeLabels(getTypeCodes(project)) || '—'
 const status = resolveOne(project.project_statuses)
 const supplier = resolveOne(project.supplier_master_data)

 // CT statistics per step
 const ctByStep = steps.map(step => {
 const valid = measurements.filter(m => m.process_step_id === step.id && !m.is_outlier)
 const avg = avgCycleTimeSec(valid)
 return { step, avg, count: valid.length }
 })
 const bottleneck = ctByStep.reduce((best, cur) =>
 (cur.avg ?? 0) > (best.avg ?? 0) ? cur : best, ctByStep[0] ?? { step: null, avg: null, count: 0 }
 )

 // Shift summary
 const totalNetMin = shifts.reduce((s, sh) => s + netProdMin(sh), 0)

 // Measures summary
 const openMeasures = measures.filter(m => m.status ==='offen').length
 const doneMeasures = measures.filter(m => m.status ==='erledigt').length

 async function handleExportPpt() {
 setExportingPpt(true)
 try {
 const { exportToPptx, downloadBlob } = await import('@/lib/export/export-service')
 const teamNames = members.map(m => {
 const rawC = m.consultants
 const c = Array.isArray(rawC) ? (rawC[0] ?? null) : rawC
 return c ? `${consultantName(c)} (${ROLE_LABELS[m.role_in_project] ?? m.role_in_project})` : null
 }).filter(Boolean) as string[]

 const config = {
 title:'LSC Workshop Bericht',
 subtitle: `${supplier?.supplier_name ?? project.supplier_name} · ${fmtDate(project.visit_date)}`,
 date: new Date().toLocaleDateString('de-DE'),
 fileName: `lsc-workshop-${project.id.slice(0, 8)}.pptx`,
 sections: [
 {
 title:'Stammdaten',
 items: [
 { label:'Lieferant', value: supplier?.supplier_name ?? project.supplier_name },
 { label:'Besuch', value: fmtDate(project.visit_date) },
 { label:'Kundentakt', value: project.customer_takt_time_sec != null ? `${project.customer_takt_time_sec}s` :'—'},
 { label:'Target CT', value: project.target_cycle_time_sec != null ? `${project.target_cycle_time_sec}s` :'—'},
 { label:'Typ', value: typeLabel },
 { label:'Status', value: status?.label ??'—'},
 ...(teamNames.length > 0 ? [{ label:'Team', value: teamNames.join(',') }] : []),
 ],
 },
 ...(ctByStep.some(c => c.avg != null) ? [{
 title:'Zykluszeiten',
 table: {
 headers: ['Station','Bereich','Ø CT (s)','Messungen','vs. Takt'],
 rows: ctByStep.filter(c => c.avg != null).map(({ step, avg, count }) => {
 const taktRatio = avg && project.customer_takt_time_sec ? avg / project.customer_takt_time_sec : null
 return [
 step.station_name,
 step.area_name ??'—',
 avg?.toFixed(2) ??'—',
 String(count),
 taktRatio != null ? `${(taktRatio * 100).toFixed(0)}%` :'—',
 ]
 }),
 },
 }] : []),
 ...(measures.length > 0 ? [{
 title: `Maßnahmen (${measures.length})`,
 table: {
 headers: ['Maßnahme','Priorität','Status','Verantwortlich','Fälligkeit'],
 rows: measures.map(m => [
 m.title,
 PRIORITY_DE[m.priority] ?? m.priority,
 STATUS_DE[m.status] ?? m.status,
 m.responsible ??'—',
 fmtDate(m.due_date),
 ]),
 },
 }] : []),
 ],
 }
 const blob = await exportToPptx(config)
 await downloadBlob(blob, config.fileName)
 } finally {
 setExportingPpt(false)
 }
 }

 return (
 <main className="max-w-3xl mx-auto px-4 py-6 pb-24 md:pb-8 space-y-6">
 {/* Export options */}
 <div className="bg-card rounded-xl border border-border overflow-hidden">
 <div className="px-5 py-4 border-b border-border">
 <h2 className="text-sm font-semibold text-foreground">Workshop exportieren</h2>
 <p className="text-xs text-muted-foreground mt-0.5">Bericht generieren und drucken oder herunterladen</p>
 </div>
 <div className="p-5 grid grid-cols-1 md:grid-cols-2 gap-4">
 {/* PDF */}
 <button
 onClick={() => { setShowReport(true); setTimeout(() => window.print(), 300) }}
 className="flex items-start gap-4 p-4 rounded-xl border-2 border-primary bg-secondary hover:bg-secondary transition-colors text-left"
 >
 <div className="w-10 h-10 rounded-lg bg-primary flex items-center justify-center shrink-0">
 <FileDown size={20} className="text-white"/>
 </div>
 <div>
 <p className="text-sm font-semibold text-primary-dark">PDF Bericht</p>
 <p className="text-xs text-muted-foreground mt-0.5">Vollständiger Workshop-Bericht als PDF</p>
 </div>
 </button>

 {/* PPT */}
 <button
 onClick={handleExportPpt}
 disabled={exportingPpt}
 className="flex items-start gap-4 p-4 rounded-xl border-2 border-border bg-background hover:bg-[#F0F4F8] transition-colors text-left disabled:opacity-50"
 >
 <div className="w-10 h-10 rounded-lg bg-muted-foreground flex items-center justify-center shrink-0">
 <FileText size={20} className="text-white"/>
 </div>
 <div>
 <p className="text-sm font-semibold text-foreground">PowerPoint</p>
 <p className="text-xs text-muted-foreground mt-0.5">
 {exportingPpt ?'Wird erstellt…':'Workshop-Bericht als Präsentation'}
 </p>
 </div>
 </button>
 </div>
 </div>

 {/* Live preview */}
 <div className="bg-card rounded-xl border border-border overflow-hidden">
 <div className="px-5 py-4 border-b border-border flex items-center justify-between">
 <h2 className="text-sm font-semibold text-foreground">Vorschau</h2>
 <button
 onClick={() => window.print()}
 className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-primary px-2.5 py-1.5 rounded-lg hover:bg-secondary transition-colors"
 >
 <Printer size={13} />
 Drucken
 </button>
 </div>

 {/* Printable content */}
 <div id="lsc-print-report"className="p-6 space-y-6 text-sm">
 {/* Header */}
 <div className="flex items-start justify-between border-b-2 border-primary pb-4">
 <div>
 <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">Supplier Development</p>
 <h1 className="text-xl font-bold text-primary-dark mt-1">LSC Workshop Bericht</h1>
 <p className="text-sm text-muted-foreground mt-0.5">{supplier?.supplier_name ?? project.supplier_name}</p>
 </div>
 <div className="text-right">
 {project.project_code && (
 <span className="font-mono text-xs bg-secondary text-primary px-2.5 py-1 rounded-lg font-semibold block mb-1">
 {project.project_code}
 </span>
 )}
 <p className="text-xs text-muted-foreground">Erstellt: {fmtDate(new Date().toISOString())}</p>
 {status && <p className="text-xs text-muted-foreground">Status: {status.label}</p>}
 </div>
 </div>

 {/* Section 1: Stammdaten */}
 <section>
 <h2 className="text-xs font-semibold text-muted-foreground uppercase tracking-widest mb-3">Stammdaten</h2>
 <div className="grid grid-cols-3 gap-4">
 <div>
 <p className="text-[10px] text-muted-foreground">Lieferant</p>
 <p className="font-medium">{supplier?.supplier_name ?? project.supplier_name}</p>
 {(supplier?.city || supplier?.country) && (
 <p className="text-xs text-muted-foreground">{[supplier?.city, supplier?.country].filter(Boolean).join(',')}</p>
 )}
 </div>
 <div>
 <p className="text-[10px] text-muted-foreground">Kundentakt / Target CT</p>
 <p className="font-mono font-bold text-primary-dark">
 {project.customer_takt_time_sec != null ? `${project.customer_takt_time_sec}s` :'—'}
 {project.target_cycle_time_sec != null ? ` / ${project.target_cycle_time_sec}s` :''}
 </p>
 </div>
 <div>
 <p className="text-[10px] text-muted-foreground">Auftragstyp</p>
 <p className="font-medium">{typeLabel}</p>
 <p className="text-[10px] text-muted-foreground">Besuch: {fmtDate(project.visit_date)}</p>
 </div>
 </div>
 </section>

 {/* Section 2: Team */}
 {members.length > 0 && (
 <section>
 <h2 className="text-xs font-semibold text-muted-foreground uppercase tracking-widest mb-3">Team</h2>
 <div className="flex flex-wrap gap-2">
 {members.map(m => {
 const rawC = m.consultants
 const c = Array.isArray(rawC) ? (rawC[0] ?? null) : rawC
 if (!c) return null
 return (
 <span key={m.consultant_id} className="text-xs bg-secondary text-primary px-2.5 py-1 rounded-full">
 {consultantName(c)} · <span className="opacity-70">{ROLE_LABELS[m.role_in_project] ?? m.role_in_project}</span>
 </span>
 )
 })}
 </div>
 </section>
 )}

 {/* Section 3: Zykluszeiten */}
 {ctByStep.some(c => c.avg != null) && (
 <section>
 <h2 className="text-xs font-semibold text-muted-foreground uppercase tracking-widest mb-3">Zykluszeiten</h2>
 <table className="w-full text-xs border-collapse">
 <thead>
 <tr className="bg-background border border-border">
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Station</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Bereich</th>
 <th className="text-right px-3 py-2 font-semibold text-muted-foreground">Ø CT</th>
 <th className="text-right px-3 py-2 font-semibold text-muted-foreground">Messungen</th>
 <th className="text-right px-3 py-2 font-semibold text-muted-foreground">vs. Takt</th>
 </tr>
 </thead>
 <tbody>
 {ctByStep.filter(c => c.avg != null).map(({ step, avg, count }) => {
 const taktRatio = avg && project.customer_takt_time_sec ? avg / project.customer_takt_time_sec : null
 const isBottleneck = step.id === bottleneck?.step?.id
 return (
 <tr key={step.id} className={`border border-border ${isBottleneck ?'bg-red-50':''}`}>
 <td className="px-3 py-1.5 font-medium">
 {step.station_name}
 {isBottleneck && <span className="ml-1.5 text-[10px] text-destructive font-semibold">BOTTLENECK</span>}
 </td>
 <td className="px-3 py-1.5 text-muted-foreground">{step.area_name ??'—'}</td>
 <td className="px-3 py-1.5 text-right font-mono font-semibold">{avg?.toFixed(2)}s</td>
 <td className="px-3 py-1.5 text-right text-muted-foreground">{count}</td>
 <td className={`px-3 py-1.5 text-right font-mono font-semibold ${taktRatio && taktRatio > 1 ?'text-destructive':'text-success'}`}>
 {taktRatio != null ? `${(taktRatio * 100).toFixed(0)}%` :'—'}
 </td>
 </tr>
 )
 })}
 </tbody>
 </table>
 </section>
 )}

 {/* Section 4: Schichtmodell */}
 {shifts.length > 0 && (
 <section>
 <h2 className="text-xs font-semibold text-muted-foreground uppercase tracking-widest mb-3">Schichtmodell</h2>
 <div className="flex items-center gap-6 bg-background rounded-lg px-4 py-3 mb-3">
 <div>
 <p className="text-[10px] text-muted-foreground">Schichten</p>
 <p className="font-mono font-bold text-primary-dark">{shifts.length}</p>
 </div>
 <div>
 <p className="text-[10px] text-muted-foreground">Netto-Produktionszeit</p>
 <p className="font-mono font-bold text-primary-dark">{(totalNetMin / 60).toFixed(1)} h</p>
 </div>
 </div>
 </section>
 )}

 {/* Section 5: Maßnahmen */}
 {measures.length > 0 && (
 <section>
 <h2 className="text-xs font-semibold text-muted-foreground uppercase tracking-widest mb-3">
 Maßnahmen ({measures.length} gesamt — {openMeasures} offen, {doneMeasures} erledigt)
 </h2>
 <table className="w-full text-xs border-collapse">
 <thead>
 <tr className="bg-background border border-border">
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">#</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Maßnahme</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Priorität</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Status</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Verantwortlich</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Fälligkeit</th>
 </tr>
 </thead>
 <tbody>
 {measures.map((m, i) => (
 <tr key={m.id} className="border border-border">
 <td className="px-3 py-1.5 text-muted-foreground">{i + 1}</td>
 <td className="px-3 py-1.5 font-medium max-w-[200px]">
 <p className="truncate">{m.title}</p>
 {m.description && <p className="text-muted-foreground truncate">{m.description}</p>}
 </td>
 <td className={`px-3 py-1.5 font-medium ${m.priority ==='hoch'?'text-destructive': m.priority ==='mittel'?'text-status-yellow':'text-muted-foreground'}`}>
 {PRIORITY_DE[m.priority] ?? m.priority}
 </td>
 <td className="px-3 py-1.5">{STATUS_DE[m.status] ?? m.status}</td>
 <td className="px-3 py-1.5 text-muted-foreground">{m.responsible ??'—'}</td>
 <td className="px-3 py-1.5 text-muted-foreground">{fmtDate(m.due_date)}</td>
 </tr>
 ))}
 </tbody>
 </table>
 </section>
 )}

 {/* Footer */}
 <div className="border-t border-border pt-4 flex items-center justify-between text-[10px] text-muted-foreground">
 <span>Supplier Development</span>
 <span>SupplierPulse · {project.project_code}</span>
 </div>
 </div>
 </div>
 </main>
 )
}
