'use client'

import { useState, useRef, useMemo } from'react'
import { Download, Upload, FileSpreadsheet, AlertCircle, CheckCircle, RefreshCw, X, FolderOpen, FileText, Monitor } from'lucide-react'
import { createClient } from'@/lib/supabase/client'
import type { QuestionWithCategories, AssessmentMainCategory, AssessmentSubCategory } from'@/lib/assessment-types'
import type { ImportRow } from'@/lib/assessment-catalog-import'
import DocumentPickerModal from'@/components/repository/document-picker-modal'
import type { Document } from'@/lib/repository-types'
import type { DuplicateMatch } from'@/lib/duplicates/detection'
import type { DuplicateResolution } from'@/components/duplicates/duplicate-review-step'
import DuplicateReviewStep from'@/components/duplicates/duplicate-review-step'

interface Props {
 questions: QuestionWithCategories[]
 mainCats: AssessmentMainCategory[]
 subCats: AssessmentSubCategory[]
 onRefresh: () => void
}

type ImportStep ='idle'|'parsing'|'preview'|'duplicates'|'importing'|'done'

const ASSESSMENT_FIELD_LABELS = [
 { key:'index_number', label:'Index'},
 { key:'question_text', label:'Frage'},
]

interface ImportSummary {
 created: number
 updated: number
 errors: number
}

export default function ImportExportTab({ questions, mainCats, subCats, onRefresh }: Props) {
 const fileInputRef = useRef<HTMLInputElement>(null)

 // Export state
 const [exportingCatalog, setExportingCatalog] = useState(false)
 const [exportingTemplate, setExportingTemplate] = useState(false)

 // Import state
 const [step, setStep] = useState<ImportStep>('idle')
 const [parseError, setParseError] = useState<string | null>(null)
 const [importRows, setImportRows] = useState<ImportRow[]>([])
 const [importOnly, setImportOnly] = useState(false)
 const [summary, setSummary] = useState<ImportSummary | null>(null)
 const [showPicker, setShowPicker] = useState(false)
 const [dupeCatalogMap, setDupeCatalogMap] = useState<Map<number, DuplicateMatch[]>>(new Map())
 const [dupeResolutions, setDupeResolutions] = useState<Map<number, DuplicateResolution>>(new Map())
 const supabase = useMemo(() => createClient(), [])

 const existingIndexes = new Set(questions.map((q) => q.index_number))

 // ── Export handlers ───────────────────────────────────────────────────────

 async function handleExportCatalog() {
 setExportingCatalog(true)
 try {
 const { exportCatalog } = await import('@/lib/assessment-catalog-export')
 await exportCatalog(questions)
 } finally {
 setExportingCatalog(false)
 }
 }

 async function handleDownloadTemplate() {
 setExportingTemplate(true)
 try {
 const { downloadImportTemplate } = await import('@/lib/assessment-catalog-export')
 await downloadImportTemplate()
 } finally {
 setExportingTemplate(false)
 }
 }

 // ── Import handlers ───────────────────────────────────────────────────────

 async function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
 const file = e.target.files?.[0]
 if (!file) return
 e.target.value =''
 setParseError(null)
 setImportRows([])
 setStep('parsing')

 try {
 const { parseCatalogFile } = await import('@/lib/assessment-catalog-import')
 const rows = await parseCatalogFile(file, mainCats, subCats, existingIndexes)
 setImportRows(rows)

 // Duplicate detection
 const { detectDuplicates } = await import('@/lib/duplicates/detection')
 const localConfig = {
 entityType:'assessment_question',
 exactMatchFields: ['index_number'],
 fuzzyMatchFields: ['question_text'],
 compositeKeys: [] as string[][],
 }
 const newRowsWithIdx: Array<{ row: ImportRow; origIdx: number }> = []
 rows.forEach((r, i) => { if (r.status ==='new') newRowsWithIdx.push({ row: r, origIdx: i }) })
 const incomingForDetect = newRowsWithIdx.map(({ row }) => row as unknown as Record<string, unknown>)
 const existingForDetect = questions.map((q) => q as unknown as Record<string, unknown>)
 const localDupeMap = detectDuplicates(localConfig, incomingForDetect, existingForDetect)
 const remappedDupeMap = new Map<number, DuplicateMatch[]>()
 for (const [li, matches] of localDupeMap) {
 const origIdx = newRowsWithIdx[li]?.origIdx
 if (origIdx !== undefined) remappedDupeMap.set(origIdx, matches)
 }
 setDupeCatalogMap(remappedDupeMap)
 setDupeResolutions(new Map())

 if (remappedDupeMap.size > 0) {
 setStep('duplicates')
 } else {
 setStep('preview')
 }
 } catch (err) {
 setParseError(err instanceof Error ? err.message :'Unbekannter Fehler beim Lesen der Datei.')
 setStep('idle')
 }
 }

 async function handleConfirmImport() {
 const rowsToImport = importRows.filter((r) => r.status !=='error')
 if (rowsToImport.length === 0) return

 setStep('importing')
 const supabase = createClient()

 const payloads = rowsToImport.map((r) => ({
 index_number: r.index_number!,
 main_category_id: r.main_category_id!,
 sub_category_id: r.sub_category_id!,
 question_text: r.question_text,
 answer_text_1: r.answer_text_1,
 answer_text_2: r.answer_text_2,
 answer_text_3: r.answer_text_3,
 answer_text_4: r.answer_text_4,
 is_active: r.is_active,
 sort_order: r.index_number!,
 updated_at: new Date().toISOString(),
 }))

 const { error } = await supabase
 .from('assessment_questions')
 .upsert(payloads, { onConflict:'index_number'})

 const errCount = importRows.filter((r) => r.status ==='error').length
 const newCount = rowsToImport.filter((r) => r.status ==='new').length
 const updCount = rowsToImport.filter((r) => r.status ==='update').length

 if (error) {
 setParseError(`Fehler beim Import: ${error.message}`)
 setStep('preview')
 } else {
 setSummary({ created: newCount, updated: updCount, errors: errCount })
 setStep('done')
 onRefresh()
 }
 }

 async function handlePickFromRepository(doc: Document) {
 setShowPicker(false)
 setParseError(null)
 setImportRows([])
 setStep('parsing')
 try {
 const { data: urlData, error: urlErr } = await supabase.storage
 .from('documents')
 .createSignedUrl(doc.storage_key, 60)
 if (urlErr || !urlData?.signedUrl) throw new Error('Datei konnte nicht geladen werden')
 const response = await fetch(urlData.signedUrl)
 if (!response.ok) throw new Error('Download fehlgeschlagen')
 const blob = await response.blob()
 const file = new File([blob], doc.original_filename, { type: blob.type })
 const { parseCatalogFile } = await import('@/lib/assessment-catalog-import')
 const rows = await parseCatalogFile(file, mainCats, subCats, existingIndexes)
 setImportRows(rows)

 // Duplicate detection
 const { detectDuplicates } = await import('@/lib/duplicates/detection')
 const localConfig = {
 entityType:'assessment_question',
 exactMatchFields: ['index_number'],
 fuzzyMatchFields: ['question_text'],
 compositeKeys: [] as string[][],
 }
 const newRowsWithIdx: Array<{ row: ImportRow; origIdx: number }> = []
 rows.forEach((r, i) => { if (r.status ==='new') newRowsWithIdx.push({ row: r, origIdx: i }) })
 const incomingForDetect = newRowsWithIdx.map(({ row }) => row as unknown as Record<string, unknown>)
 const existingForDetect = questions.map((q) => q as unknown as Record<string, unknown>)
 const localDupeMap = detectDuplicates(localConfig, incomingForDetect, existingForDetect)
 const remappedDupeMap = new Map<number, DuplicateMatch[]>()
 for (const [li, matches] of localDupeMap) {
 const origIdx = newRowsWithIdx[li]?.origIdx
 if (origIdx !== undefined) remappedDupeMap.set(origIdx, matches)
 }
 setDupeCatalogMap(remappedDupeMap)
 setDupeResolutions(new Map())

 if (remappedDupeMap.size > 0) {
 setStep('duplicates')
 } else {
 setStep('preview')
 }
 } catch (err) {
 setParseError(err instanceof Error ? err.message :'Fehler beim Laden aus Datenablage')
 setStep('idle')
 }
 }

 function reset() {
 setStep('idle')
 setImportRows([])
 setParseError(null)
 setSummary(null)
 setImportOnly(false)
 setDupeCatalogMap(new Map())
 setDupeResolutions(new Map())
 }

 // ── Derived counts ────────────────────────────────────────────────────────
 const newRows = importRows.filter((r) => r.status ==='new')
 const updateRows = importRows.filter((r) => r.status ==='update')
 const errorRows = importRows.filter((r) => r.status ==='error')
 const validRows = importRows.filter((r) => r.status !=='error')
 const hasErrors = errorRows.length > 0

 return (
 <div className="space-y-6 max-w-5xl">

 {/* ── Export section ──────────────────────────────────────────────── */}
 <div className="bg-card rounded-xl border border-border p-6">
 <h2 className="text-[13px] font-semibold text-foreground mb-1">Katalog exportieren</h2>
 <p className="text-[12px] text-muted-foreground mb-4">
 Exportiert alle {questions.length} Fragen als xlsx-Datei. Das Format entspricht dem Import-Template.
 </p>
 <div className="flex gap-3 flex-wrap">
 <button
 onClick={handleExportCatalog}
 disabled={exportingCatalog}
 className="flex items-center gap-2 h-9 px-4 rounded-lg bg-primary-dark text-white text-[13px] font-medium hover:bg-primary-dark transition-colors disabled:opacity-50"
 >
 <FileSpreadsheet size={15} />
 {exportingCatalog ?'Exportiere…':'Katalog als Excel'}
 </button>
 <button
 onClick={handleDownloadTemplate}
 disabled={exportingTemplate}
 className="flex items-center gap-2 h-9 px-4 rounded-lg border border-border text-foreground text-[13px] font-medium hover:bg-background transition-colors disabled:opacity-50"
 >
 <Download size={15} />
 {exportingTemplate ?'Exportiere…':'Import-Vorlage herunterladen'}
 </button>
 <button
 disabled
 className="flex items-center gap-2 h-9 px-4 rounded-lg border border-border text-muted-foreground text-[13px] font-medium cursor-not-allowed opacity-50"
 title="Wird in einer späteren Version verfügbar"
 >
 <Monitor size={15} />
 Ergebnisse als PowerPoint
 </button>
 <button
 onClick={() => window.print()}
 className="flex items-center gap-2 h-9 px-4 rounded-lg border border-border text-foreground text-[13px] font-medium hover:bg-background transition-colors"
 >
 <FileText size={15} />
 Ergebnisse als PDF
 </button>
 </div>
 </div>

 {/* ── Import section ──────────────────────────────────────────────── */}
 <div className="bg-card rounded-xl border border-border p-6">
 <div className="flex items-center justify-between mb-1">
 <h2 className="text-[13px] font-semibold text-foreground">Katalog importieren</h2>
 {step !=='idle'&& (
 <button onClick={reset} className="flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground">
 <X size={13} /> Zurücksetzen
 </button>
 )}
 </div>
 <p className="text-[12px] text-muted-foreground mb-4">
 Importiert Fragen aus einer xlsx-Datei. Bestehende Fragen werden anhand des Index-Nummern aktualisiert, neue werden angelegt.
 </p>

 {/* Step indicator */}
 <div className="flex items-center gap-1 mb-5">
 {(['1. Datei auswählen','2. Duplikate','3. Vorschau & Validierung','4. Import'].map((label, i) => {
 const stepIndex = i + 1
 const curStep = step ==='idle'? 0 : step ==='parsing'? 1 : step ==='duplicates'? 2 : step ==='preview'? 3 : step ==='importing'? 4 : 4
 const active = curStep === stepIndex
 const done = curStep > stepIndex
 return (
 <span key={i} className={`text-[11px] font-medium px-3 py-1 rounded-full ${
 done ?'bg-[#D1FAE5] text-[#065F46]':
 active ?'bg-primary-dark text-white':
'bg-background text-[#B3C5D5]'
 }`}>{label}</span>
 )
 }))}
 </div>

 {/* Step 1: Upload */}
 {(step ==='idle'|| step ==='parsing') && (
 <div>
 <input ref={fileInputRef} type="file"accept=".xlsx,.xls"onChange={handleFileSelect} className="hidden"/>
 {parseError && (
 <div className="mb-4 flex items-start gap-2 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5">
 <AlertCircle size={14} className="text-red-500 shrink-0 mt-0.5"/>
 <p className="text-[12px] text-red-700">{parseError}</p>
 </div>
 )}
 <div className="flex flex-wrap items-center gap-3">
 <button
 onClick={() => fileInputRef.current?.click()}
 disabled={step ==='parsing'}
 className="flex items-center gap-2 h-10 px-5 rounded-lg border-2 border-dashed border-secondary bg-background text-primary text-[13px] font-medium hover:border-primary hover:bg-secondary transition-colors disabled:opacity-50"
 >
 {step ==='parsing'? <RefreshCw size={15} className="animate-spin"/> : <Upload size={15} />}
 {step ==='parsing'?'Lese Datei…':'xlsx-Datei auswählen'}
 </button>
 <button
 onClick={() => setShowPicker(true)}
 disabled={step ==='parsing'}
 className="flex items-center gap-2 h-10 px-4 rounded-lg border border-primary/40 text-primary text-[13px] font-medium hover:bg-secondary transition-colors disabled:opacity-50"
 >
 <FolderOpen size={14} />
 Aus Datenablage
 </button>
 </div>
 </div>
 )}

 {/* Step 2: Duplicates */}
 {step ==='duplicates'&& (
 <div className="space-y-4">
 <DuplicateReviewStep
 duplicates={dupeCatalogMap}
 incomingRows={importRows as unknown as Record<string, unknown>[]}
 fieldLabels={ASSESSMENT_FIELD_LABELS}
 entityLabel="Frage"
 resolutions={dupeResolutions}
 onResolutionChange={(rowIndex, res) => {
 setDupeResolutions((prev) => { const next = new Map(prev); next.set(rowIndex, res); return next })
 }}
 onResolveAllExact={() => {
 setDupeResolutions((prev) => {
 const next = new Map(prev)
 for (const [rowIdx, matches] of dupeCatalogMap) {
 const best = matches.reduce((b, m) => m.confidence > b.confidence ? m : b, matches[0])
 if (best.confidence >= 95) next.set(rowIdx, { action:'merge', targetMatch: best, fieldResolutions: Object.fromEntries(ASSESSMENT_FIELD_LABELS.map(({ key }) => [key,'keep_existing'as const])) })
 }
 return next
 })
 }}
 />
 <div className="flex gap-3">
 <button
 onClick={() => setStep('preview')}
 className="flex items-center gap-2 h-9 px-4 rounded-lg bg-primary text-white text-[13px] font-medium hover:bg-primary-dark transition-colors"
 >
 Weiter zur Vorschau
 </button>
 </div>
 </div>
 )}

 {/* Step 3: Preview */}
 {step ==='preview'&& (
 <div className="space-y-4">
 {/* Summary bar */}
 <div className="flex flex-wrap gap-3">
 <span className="flex items-center gap-1.5 text-[12px] font-medium px-3 py-1.5 rounded-lg bg-[#D1FAE5] text-[#065F46]">
 <CheckCircle size={13} /> {newRows.length} Neu
 </span>
 <span className="flex items-center gap-1.5 text-[12px] font-medium px-3 py-1.5 rounded-lg bg-[#FEF3C7] text-status-yellow">
 <RefreshCw size={13} /> {updateRows.length} Aktualisierung
 </span>
 {hasErrors && (
 <span className="flex items-center gap-1.5 text-[12px] font-medium px-3 py-1.5 rounded-lg bg-[#FEE2E2] text-[#991B1B]">
 <AlertCircle size={13} /> {errorRows.length} Fehler
 </span>
 )}
 <span className="text-[12px] text-muted-foreground self-center">{importRows.length} Zeilen gesamt</span>
 </div>

 {/* Preview table */}
 <div className="border border-border rounded-xl overflow-hidden">
 <div className="max-h-[420px] overflow-y-auto">
 <table className="w-full text-[11px]">
 <thead className="sticky top-0 bg-background border-b border-border">
 <tr>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground w-10">Zeile</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground w-12">Index</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground w-16">Hauptkat.</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground w-20">Unterkat.</th>
 <th className="text-left px-3 py-2 font-semibold text-muted-foreground">Frage</th>
 <th className="text-center px-3 py-2 font-semibold text-muted-foreground w-24">Status</th>
 </tr>
 </thead>
 <tbody>
 {importRows.map((row, i) => (
 <tr
 key={i}
 className="border-b border-[#F0F4F8]"
 style={{
 backgroundColor:
 row.status ==='error'?'#FEF2F2':
 row.status ==='update'?'#FFFBEB':
'#F0FDF4',
 }}
 >
 <td className="px-3 py-2 text-muted-foreground">{row.rowNum}</td>
 <td className="px-3 py-2 font-mono font-bold">{row.index_number ??'?'}</td>
 <td className="px-3 py-2 font-mono text-muted-foreground">{row.main_category_code ||'—'}</td>
 <td className="px-3 py-2 font-mono text-muted-foreground">{row.sub_category_code ||'—'}</td>
 <td className="px-3 py-2">
 <p className="truncate max-w-[320px] text-foreground">
 {row.question_text || <span className="text-[#B3C5D5]">—</span>}
 </p>
 {row.errors.length > 0 && (
 <ul className="mt-0.5 space-y-0.5">
 {row.errors.map((e, j) => (
 <li key={j} className="flex items-start gap-1 text-red-600">
 <AlertCircle size={10} className="shrink-0 mt-0.5"/>
 <span>{e}</span>
 </li>
 ))}
 </ul>
 )}
 </td>
 <td className="px-3 py-2 text-center">
 <span
 className="inline-block text-[10px] font-medium px-2 py-0.5 rounded-full"
 style={{
 backgroundColor:
 row.status ==='error'?'#FEE2E2':
 row.status ==='update'?'#FEF3C7':'#D1FAE5',
 color:
 row.status ==='error'?'#991B1B':
 row.status ==='update'?'#92400E':'#065F46',
 }}
 >
 {row.status ==='error'?'Fehler': row.status ==='update'?'Update':'Neu'}
 </span>
 </td>
 </tr>
 ))}
 </tbody>
 </table>
 </div>
 </div>

 {/* Import options */}
 {hasErrors && validRows.length > 0 && (
 <label className="flex items-center gap-2 text-[12px] text-muted-foreground cursor-pointer select-none">
 <input
 type="checkbox"
 checked={importOnly}
 onChange={(e) => setImportOnly(e.target.checked)}
 className="w-3.5 h-3.5 accent-primary"
 />
 Nur gültige Zeilen importieren ({validRows.length} von {importRows.length})
 </label>
 )}

 {/* Confirm button */}
 <div className="flex gap-3">
 <button
 onClick={handleConfirmImport}
 disabled={validRows.length === 0 || (hasErrors && !importOnly)}
 className="flex items-center gap-2 h-9 px-4 rounded-lg bg-primary text-white text-[13px] font-medium hover:bg-primary-dark transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
 >
 <CheckCircle size={14} />
 Import bestätigen ({validRows.length} Zeilen)
 </button>
 {hasErrors && !importOnly && (
 <p className="text-[12px] text-red-600 self-center">
 Bitte Fehler beheben oder &quot;Nur gültige Zeilen importieren&quot; aktivieren.
 </p>
 )}
 </div>
 </div>
 )}

 {/* Step 3: Importing */}
 {step ==='importing'&& (
 <div className="flex items-center gap-3 py-6">
 <RefreshCw size={18} className="animate-spin text-primary"/>
 <span className="text-[13px] text-muted-foreground">Importiere {validRows.length} Fragen…</span>
 </div>
 )}

 {/* Done */}
 {step ==='done'&& summary && (
 <div className="space-y-4">
 <div className="flex items-center gap-2 text-success">
 <CheckCircle size={18} />
 <span className="text-[14px] font-semibold">Import abgeschlossen</span>
 </div>
 <div className="flex flex-wrap gap-3">
 <div className="bg-[#D1FAE5] text-[#065F46] rounded-lg px-4 py-3 text-center min-w-[80px]">
 <p className="text-[22px] font-bold">{summary.created}</p>
 <p className="text-[11px] font-medium">Erstellt</p>
 </div>
 <div className="bg-[#FEF3C7] text-status-yellow rounded-lg px-4 py-3 text-center min-w-[80px]">
 <p className="text-[22px] font-bold">{summary.updated}</p>
 <p className="text-[11px] font-medium">Aktualisiert</p>
 </div>
 {summary.errors > 0 && (
 <div className="bg-[#FEE2E2] text-[#991B1B] rounded-lg px-4 py-3 text-center min-w-[80px]">
 <p className="text-[22px] font-bold">{summary.errors}</p>
 <p className="text-[11px] font-medium">Übersprungen</p>
 </div>
 )}
 </div>
 <button onClick={reset} className="flex items-center gap-1.5 h-8 px-3 rounded border border-border text-[12px] text-foreground hover:bg-background">
 <Upload size={13} /> Weiteren Import starten
 </button>
 </div>
 )}
 </div>

 {/* Format reference */}
 <div className="bg-background rounded-xl border border-border p-5">
 <h3 className="text-[12px] font-semibold text-foreground mb-3">Import-Format (Spalten A–I)</h3>
 <div className="grid grid-cols-3 sm:grid-cols-5 gap-2">
 {[
 ['A','Index'],
 ['B','Hauptkategorie'],
 ['C','Unterkategorie'],
 ['D','Frage'],
 ['E','Antwort 1'],
 ['F','Antwort 2'],
 ['G','Antwort 3'],
 ['H','Antwort 4'],
 ['I','Aktiv'],
 ].map(([col, name]) => (
 <div key={col} className="flex items-center gap-2">
 <span className="shrink-0 w-6 h-6 rounded bg-primary-dark text-white text-[10px] font-bold flex items-center justify-center">{col}</span>
 <span className="text-[11px] text-muted-foreground">{name}</span>
 </div>
 ))}
 </div>
 <p className="text-[11px] text-muted-foreground mt-3">
 Hauptkategorie: Code (z.B. <code className="font-mono">DEV</code>). Unterkategorie: Code (z.B. <code className="font-mono">DEV.1</code>). Aktiv: &quot;Ja&quot; oder &quot;Nein&quot;.
 </p>
 </div>

 {showPicker && (
 <DocumentPickerModal
 title="Katalog-Datei aus Datenablage"
 onSelect={(doc: Document) => handlePickFromRepository(doc)}
 onClose={() => setShowPicker(false)}
 />
 )}
 </div>
 )
}
