'use client'

import { useState, useEffect, useMemo } from'react'
import { Download, FileSpreadsheet, FolderArchive, File, FileText, FileImage, FilePieChart } from'lucide-react'
import { createClient } from'@/lib/supabase/client'
import type { Document } from'@/lib/repository-types'
import { formatFileSize } from'@/lib/repository-types'
import { avgCycleTimeSec } from'@/lib/reporting/aggregations'
import CopilotExportButton from'@/components/copilot-export/copilot-export-button'
import { exportProjectCopilotDocx, exportProjectCopilotMd, exportProjectCopilotXlsx } from'@/app/project/[id]/export/actions'

interface Project {
 id: string
 supplier_name: string
 product_name: string | null
 plant_location: string | null
 visit_date: string
 customer_takt_time_sec: number | null
 planned_oee: number | null
 target_cycle_time_sec: number | null
}

interface Step {
 id: string
 station_name: string
 step_number: number
 planned_cycle_time_sec: number | null
 is_manual: boolean
 cycle_measurements: { cycle_number: number; cycle_time_sec: number; is_outlier: boolean; notes: string | null }[]
}

interface Action {
 action_number: number
 area: string
 description: string
 effort: string
 benefit: string
 status: string
 responsible: string | null
 target_date: string | null
 time_saving_sec: number | null
}

interface ShiftOutput {
 shift_date: string
 shift_type: string
 hour_start: number
 target_output: number
 actual_output: number
 remarks: string | null
}

interface Props {
 project: Project
 steps: Step[]
 actions: Action[]
 shifts: ShiftOutput[]
 /** copilotExports feature flag (config/profiles) — resolved server-side by
  * page.tsx and passed down (getProfile() reads process.env, must not be
  * called from this client component). */
 copilotExportsEnabled: boolean
}

function getMimeIcon(mimeType: string | null) {
 if (!mimeType) return <File size={14} className="text-muted-foreground shrink-0"/>
 if (mimeType.startsWith('image/')) return <FileImage size={14} className="text-primary shrink-0"/>
 if (mimeType.includes('spreadsheet') || mimeType.includes('excel') || mimeType ==='text/csv')
 return <FileSpreadsheet size={14} className="text-success shrink-0"/>
 if (mimeType ==='application/pdf') return <FilePieChart size={14} className="text-destructive shrink-0"/>
 return <FileText size={14} className="text-muted-foreground shrink-0"/>
}

export default function ExportClient({ project, steps, actions, shifts, copilotExportsEnabled }: Props) {
 const [exporting, setExporting] = useState<string | null>(null)
 // tdd-guard:skip — export UI glue; export-model logic is covered separately (GAP-05).
 const [exportError, setExportError] = useState<string | null>(null)
 const [attachments, setAttachments] = useState<Document[]>([])
 const [loadingAttachments, setLoadingAttachments] = useState(true)
 const supabase = useMemo(() => createClient(), [])

 useEffect(() => {
 supabase
 .from('documents')
 .select('*')
 .eq('project_id', project.id)
 .eq('is_deleted', false)
 .order('created_at', { ascending: false })
 .then(({ data }) => {
 setAttachments((data as Document[]) ?? [])
 setLoadingAttachments(false)
 })
 }, [project.id])

 async function downloadAttachment(doc: Document) {
 const { data, error } = await supabase.storage
 .from('documents')
 .createSignedUrl(doc.storage_key, 60)
 if (error || !data?.signedUrl) return
 const a = document.createElement('a')
 a.href = data.signedUrl
 a.download = doc.original_filename
 a.click()
 }

 async function exportFullReport() {
 setExporting('full')
 setExportError(null)
 try {
 const ExcelJS = (await import('exceljs')).default
 const { saveAs } = await import('file-saver')

 const wb = new ExcelJS.Workbook()
 wb.creator ='SupplierPulse'
 wb.created = new Date()

 // Sheet 1: Summary
 const summary = wb.addWorksheet('Cycle Time Summary')
 summary.columns = [
 { header:'Station', key:'station', width: 20 },
 { header:'Planned CT (s)', key:'planned', width: 15 },
 { header:'Avg CT (s)', key:'avg', width: 12 },
 { header:'Min (s)', key:'min', width: 10 },
 { header:'Max (s)', key:'max', width: 10 },
 { header:'Cycles', key:'cycles', width: 8 },
 { header:'Bottleneck', key:'bottleneck', width: 12 },
 ]

 // Style header
 summary.getRow(1).font = { bold: true }
 summary.getRow(1).fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FF0D4F4F'} }
 summary.getRow(1).font = { bold: true, color: { argb:'FFFFFFFF'} }

 let maxAvg = 0
 steps.forEach((step) => {
 const valid = step.cycle_measurements.filter((m) => !m.is_outlier)
 const a = avgCycleTimeSec(step.cycle_measurements)
 if (a && a > maxAvg) maxAvg = a
 })

 steps.forEach((step) => {
 const valid = step.cycle_measurements.filter((m) => !m.is_outlier)
 const a = avgCycleTimeSec(step.cycle_measurements)
 const mn = valid.length ? Math.min(...valid.map((m) => m.cycle_time_sec)) : null
 const mx = valid.length ? Math.max(...valid.map((m) => m.cycle_time_sec)) : null
 const row = summary.addRow({
 station: step.station_name,
 planned: step.planned_cycle_time_sec,
 avg: a?.toFixed(2),
 min: mn?.toFixed(2),
 max: mx?.toFixed(2),
 cycles: valid.length,
 bottleneck: a && a === maxAvg ?'⚠ BOTTLENECK':'',
 })
 if (a && a === maxAvg) {
 row.getCell('avg').fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FFFDE8E8'} }
 row.getCell('bottleneck').font = { bold: true, color: { argb:'FFC0392B'} }
 }
 })

 // Sheet 2: Raw measurements
 const raw = wb.addWorksheet('Raw Measurements')
 raw.columns = [
 { header:'Station', key:'station', width: 20 },
 { header:'Cycle #', key:'cycle', width: 8 },
 { header:'CT (s)', key:'ct', width: 10 },
 { header:'Outlier', key:'outlier', width: 8 },
 { header:'Notes', key:'notes', width: 30 },
 ]
 raw.getRow(1).font = { bold: true }
 raw.getRow(1).fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FF0D4F4F'} }
 raw.getRow(1).font = { bold: true, color: { argb:'FFFFFFFF'} }

 steps.forEach((step) => {
 step.cycle_measurements
 .sort((a, b) => a.cycle_number - b.cycle_number)
 .forEach((m) => {
 raw.addRow({
 station: step.station_name,
 cycle: m.cycle_number,
 ct: m.cycle_time_sec,
 outlier: m.is_outlier ?'Yes':'No',
 notes: m.notes,
 })
 })
 })

 // Sheet 3: Workshop Actions
 if (actions.length > 0) {
 const ws = wb.addWorksheet('Workshop Actions')
 ws.columns = [
 { header:'#', key:'num', width: 5 },
 { header:'Area', key:'area', width: 18 },
 { header:'Description', key:'desc', width: 40 },
 { header:'Effort', key:'effort', width: 10 },
 { header:'Benefit', key:'benefit', width: 10 },
 { header:'Status', key:'status', width: 12 },
 { header:'Responsible', key:'resp', width: 15 },
 { header:'Target Date', key:'date', width: 12 },
 { header:'Time saving (s)', key:'time', width: 15 },
 ]
 ws.getRow(1).font = { bold: true, color: { argb:'FFFFFFFF'} }
 ws.getRow(1).fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FF0D4F4F'} }
 actions.forEach((a) => {
 ws.addRow({
 num: a.action_number,
 area: a.area,
 desc: a.description,
 effort: a.effort,
 benefit: a.benefit,
 status: a.status,
 resp: a.responsible,
 date: a.target_date,
 time: a.time_saving_sec,
 })
 })
 }

 // Sheet 4: Shift Output
 if (shifts.length > 0) {
 const ws = wb.addWorksheet('Shift Output')
 ws.columns = [
 { header:'Date', key:'date', width: 12 },
 { header:'Shift', key:'shift', width: 14 },
 { header:'Hour', key:'hour', width: 8 },
 { header:'Soll', key:'target', width: 8 },
 { header:'Ist', key:'actual', width: 8 },
 { header:'Delta', key:'delta', width: 8 },
 { header:'Remarks', key:'remarks', width: 30 },
 ]
 ws.getRow(1).font = { bold: true, color: { argb:'FFFFFFFF'} }
 ws.getRow(1).fill = { type:'pattern', pattern:'solid', fgColor: { argb:'FF0D4F4F'} }
 shifts.forEach((s) => {
 ws.addRow({
 date: s.shift_date,
 shift: s.shift_type,
 hour: `${String(s.hour_start).padStart(2,'0')}:00`,
 target: s.target_output,
 actual: s.actual_output,
 delta: s.actual_output - s.target_output,
 remarks: s.remarks,
 })
 })
 }

 const buf = await wb.xlsx.writeBuffer()
 saveAs(
 new Blob([buf], { type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
 `SupplierPulse_${project.supplier_name.replace(/\s+/g,'_')}_${project.visit_date}.xlsx`
 )
 } catch (err) {
 setExportError(err instanceof Error ? err.message :'Export fehlgeschlagen')
 } finally {
 setExporting(null)
 }
 }

 async function exportPdf() {
 setExporting('pdf')
 try {
 const { exportToPdf, downloadBlob } = await import('@/lib/export/export-service')
 const stepsWithAvg = steps.map(step => {
 const valid = step.cycle_measurements.filter(m => !m.is_outlier)
 const a = avgCycleTimeSec(valid)
 return { step, avg: a, count: valid.length }
 })
 const maxAvg = Math.max(...stepsWithAvg.map(s => s.avg ?? 0), 0)

 const config = {
 title:'Projektdatenblatt',
 subtitle: project.supplier_name,
 date: project.visit_date
 ? new Date(project.visit_date).toLocaleDateString('de-DE')
 : new Date().toLocaleDateString('de-DE'),
 fileName: `projekt-${project.id.slice(0, 8)}.pdf`,
 sections: [
 {
 title:'Stammdaten',
 items: [
 { label:'Lieferant', value: project.supplier_name },
 { label:'Produkt', value: project.product_name ??'—'},
 { label:'Standort', value: project.plant_location ??'—'},
 { label:'Besuchsdatum', value: project.visit_date ? new Date(project.visit_date).toLocaleDateString('de-DE') :'—'},
 { 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` :'—'},
 ],
 },
 ...(stepsWithAvg.some(s => s.avg != null) ? [{
 title:'Zykluszeiten',
 table: {
 headers: ['Station','Ø CT (s)','Messungen','Engpass'],
 rows: stepsWithAvg.filter(s => s.avg != null).map(({ step, avg, count }) => [
 step.station_name,
 avg?.toFixed(2) ??'—',
 String(count),
 avg === maxAvg && maxAvg > 0 ?'Engpass':'',
 ]),
 },
 }] : []),
 ...(actions.length > 0 ? [{
 title:'Maßnahmen',
 table: {
 headers: ['Bereich','Beschreibung','Status','Aufwand','Nutzen'],
 rows: actions.map(a => [
 a.area,
 a.description.slice(0, 40),
 a.status,
 a.effort,
 a.benefit,
 ]),
 },
 }] : []),
 ],
 }
 const blob = await exportToPdf(config)
 await downloadBlob(blob, config.fileName)
 } finally {
 setExporting(null)
 }
 }

 async function exportCsv() {
 setExporting('csv')
 const rows: string[] = [
'Station,Cycle #,CT (s),Outlier,Notes',
 ...steps.flatMap((step) =>
 step.cycle_measurements
 .sort((a, b) => a.cycle_number - b.cycle_number)
 .map(
 (m) =>
 `"${step.station_name}",${m.cycle_number},${m.cycle_time_sec},${m.is_outlier},"${m.notes ??''}"`
 )
 ),
 ]
 const blob = new Blob([rows.join('\n')], { type:'text/csv'})
 const { saveAs } = await import('file-saver')
 saveAs(blob, `SupplierPulse_${project.supplier_name}_cycles.csv`)
 setExporting(null)
 }

 const totalMeasurements = steps.reduce((s, step) => s + step.cycle_measurements.length, 0)

 return (
 <div className="max-w-lg mx-auto px-4 py-6 pb-24 md:pb-8 space-y-4">
 {/* Data summary */}
 <div className="grid grid-cols-3 gap-3">
 <div className="bg-card border border-border rounded-lg p-3 text-center">
 <div className="text-xs text-muted-foreground">Stations</div>
 <div className="font-mono font-bold text-xl mt-0.5">{steps.length}</div>
 </div>
 <div className="bg-card border border-border rounded-lg p-3 text-center">
 <div className="text-xs text-muted-foreground">Measurements</div>
 <div className="font-mono font-bold text-xl mt-0.5">{totalMeasurements}</div>
 </div>
 <div className="bg-card border border-border rounded-lg p-3 text-center">
 <div className="text-xs text-muted-foreground">Actions</div>
 <div className="font-mono font-bold text-xl mt-0.5">{actions.length}</div>
 </div>
 </div>

 {/* Export buttons */}
 <div className="space-y-3">
 {exportError && (
 <p className="text-sm text-destructive">Export fehlgeschlagen: {exportError}</p>
 )}
 <button
 onClick={exportFullReport}
 disabled={!!exporting}
 className="w-full flex items-center gap-3 p-4 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50 transition-colors"
 >
 <FileSpreadsheet size={22} />
 <div className="text-left">
 <div className="font-semibold">Full Report (.xlsx)</div>
 <div className="text-xs text-white/70">
 Cycle times, raw data, workshop actions, shift output — all in one workbook
 </div>
 </div>
 {exporting ==='full'&& (
 <div className="ml-auto text-xs text-white/70">Generating…</div>
 )}
 </button>

 <button
 onClick={exportCsv}
 disabled={!!exporting}
 className="w-full flex items-center gap-3 p-4 bg-card border border-border rounded-lg hover:border-primary/40 hover:bg-secondary/50 disabled:opacity-50 transition-colors"
 >
 <Download size={22} className="text-primary"/>
 <div className="text-left">
 <div className="font-semibold">Cycle Times (.csv)</div>
 <div className="text-xs text-muted-foreground">
 Raw measurements — all cycles, all stations
 </div>
 </div>
 {exporting ==='csv'&& (
 <div className="ml-auto text-xs text-muted-foreground">Generating…</div>
 )}
 </button>

 <button
 onClick={exportPdf}
 disabled={!!exporting}
 className="w-full flex items-center gap-3 p-4 bg-card border border-border rounded-lg hover:border-primary/40 hover:bg-secondary/50 disabled:opacity-50 transition-colors"
 >
 <FilePieChart size={22} className="text-destructive"/>
 <div className="text-left">
 <div className="font-semibold">PDF Projektdatenblatt</div>
 <div className="text-xs text-muted-foreground">
 Projektstammdaten, Zykluszeiten und Maßnahmen als PDF
 </div>
 </div>
 {exporting ==='pdf'&& (
 <div className="ml-auto text-xs text-muted-foreground">Generating…</div>
 )}
 </button>

 {copilotExportsEnabled && (
 <>
 <CopilotExportButton
 id={project.id}
 formats={[
   { format: 'docx', action: exportProjectCopilotDocx, label: 'Word (DOCX)' },
   { format: 'md', action: exportProjectCopilotMd, label: 'Markdown (KI-Chat)' },
 ]}
 label="Gesamtprojekt-Export (Copilot)"
 busyLabel="Erzeuge…"
 className="w-full flex items-center gap-3 p-4 bg-card border border-border rounded-lg hover:border-primary/40 hover:bg-secondary/50 disabled:opacity-50 transition-colors"
 />
 <CopilotExportButton
 id={project.id}
 formats={[{ format: 'xlsx', action: exportProjectCopilotXlsx, label: 'Gesamtprojekt-Export (Copilot, XLSX)' }]}
 label="Gesamtprojekt-Export (Copilot, XLSX)"
 busyLabel="Erzeuge…"
 className="w-full flex items-center gap-3 p-4 bg-card border border-border rounded-lg hover:border-primary/40 hover:bg-secondary/50 disabled:opacity-50 transition-colors"
 />
 </>
 )}
 </div>

 {/* Anlagen (project documents) */}
 <div className="bg-card border border-border rounded-lg overflow-hidden">
 <div className="flex items-center gap-2 px-4 py-3 border-b border-border">
 <FolderArchive size={15} className="text-primary"/>
 <h2 className="font-semibold text-sm">Anlagen (Datenablage)</h2>
 {!loadingAttachments && attachments.length > 0 && (
 <span className="text-xs font-semibold text-primary bg-secondary rounded-full px-2 py-0.5">
 {attachments.length}
 </span>
 )}
 </div>

 {loadingAttachments ? (
 <div className="py-6 text-center text-xs text-muted-foreground">Lade…</div>
 ) : attachments.length === 0 ? (
 <div className="py-8 text-center text-muted-foreground">
 <File size={24} className="mx-auto mb-2 opacity-30"/>
 <p className="text-xs">Keine Dokumente für dieses Projekt</p>
 </div>
 ) : (
 <ul className="divide-y divide-border">
 {attachments.map((doc) => (
 <li
 key={doc.id}
 className="flex items-center gap-3 px-4 py-3 hover:bg-background transition-colors"
 >
 {getMimeIcon(doc.mime_type)}
 <div className="flex-1 min-w-0">
 <p className="text-xs font-medium text-foreground truncate">{doc.title}</p>
 <p className="text-[10px] text-muted-foreground font-mono">
 {formatFileSize(doc.file_size)}
 {doc.document_type && (
 <span className="ml-1.5 bg-secondary text-primary rounded-full px-1.5 py-0.5 font-medium not-italic">
 {doc.document_type}
 </span>
 )}
 </p>
 </div>
 <button
 onClick={() => downloadAttachment(doc)}
 title="Herunterladen"
 className="p-1.5 rounded hover:bg-secondary text-muted-foreground hover:text-primary transition-colors shrink-0"
 >
 <Download size={13} />
 </button>
 </li>
 ))}
 </ul>
 )}
 </div>
 </div>
 )
}
