'use client'

import { useState } from'react'
import { Check, GitMerge, SkipForward } from'lucide-react'
import type { DuplicateMatch } from'@/lib/duplicates/detection'
import MergeDialog from'./merge-dialog'

export interface DuplicateResolution {
 action:'merge'|'skip'|'create_anyway'
 targetMatch?: DuplicateMatch
 fieldResolutions?: Record<string,'keep_existing'|'use_incoming'>
}

interface Props {
 duplicates: Map<number, DuplicateMatch[]>
 incomingRows: Record<string, unknown>[]
 fieldLabels: Array<{ key: string; label: string }>
 entityLabel: string
 resolutions: Map<number, DuplicateResolution>
 onResolutionChange: (rowIndex: number, res: DuplicateResolution) => void
 onResolveAllExact: () => void
}

function confidenceLabel(c: number): string {
 if (c >= 95) return'Exakt'
 if (c >= 80) return'Hoch'
 return'Mittel'
}

function confidenceBadgeClass(c: number): string {
 if (c >= 95) return'bg-red-100 text-destructive'
 if (c >= 80) return'bg-orange-100 text-orange-700'
 return'bg-yellow-100 text-yellow-700'
}

function rowBgClass(c: number): string {
 if (c >= 95) return'bg-red-50'
 if (c >= 80) return'bg-orange-50'
 return'bg-yellow-50'
}

function getKeyFieldsDisplay(record: Record<string, unknown>, fieldLabels: Array<{ key: string; label: string }>): string {
 return fieldLabels
 .slice(0, 2)
 .map(({ key }) => record[key] ??'')
 .filter(Boolean)
 .join('/')
}

function getBestMatch(matches: DuplicateMatch[]): DuplicateMatch {
 return matches.reduce((best, m) => (m.confidence > best.confidence ? m : best), matches[0])
}

export default function DuplicateReviewStep({
 duplicates,
 incomingRows,
 fieldLabels,
 entityLabel,
 resolutions,
 onResolutionChange,
 onResolveAllExact,
}: Props) {
 const [mergingRowIndex, setMergingRowIndex] = useState<number | null>(null)

 const entries = Array.from(duplicates.entries())
 const exactCount = entries.filter(([, matches]) => getBestMatch(matches).confidence >= 95).length
 const highCount = entries.filter(([, matches]) => { const c = getBestMatch(matches).confidence; return c >= 80 && c < 95 }).length
 const medCount = entries.filter(([, matches]) => getBestMatch(matches).confidence < 80).length

 const hasExact = exactCount > 0

 return (
 <div className="space-y-4">
 {/* Summary bar */}
 <div className="flex flex-wrap items-center gap-3">
 <span className="text-sm font-semibold text-foreground">
 {duplicates.size} Duplikat{duplicates.size !== 1 ?'e':''} gefunden
 </span>
 {exactCount > 0 && (
 <span className="text-[11px] font-medium px-2.5 py-1 rounded-full bg-red-100 text-destructive">
 {exactCount} Genau
 </span>
 )}
 {highCount > 0 && (
 <span className="text-[11px] font-medium px-2.5 py-1 rounded-full bg-orange-100 text-orange-700">
 {highCount} Hoch
 </span>
 )}
 {medCount > 0 && (
 <span className="text-[11px] font-medium px-2.5 py-1 rounded-full bg-yellow-100 text-yellow-700">
 {medCount} Mittel
 </span>
 )}
 {hasExact && (
 <button
 onClick={onResolveAllExact}
 className="ml-auto text-xs font-medium px-3 py-1.5 rounded bg-primary text-white hover:bg-primary-dark transition-colors"
 >
 Alle exakten zusammenführen
 </button>
 )}
 </div>

 {/* Table */}
 <div className="border border-border rounded-lg overflow-hidden">
 <div className="overflow-x-auto">
 <table className="w-full text-xs min-w-[640px]">
 <thead className="bg-background border-b border-border">
 <tr className="text-muted-foreground">
 <th className="px-3 py-2 text-left w-12">Zeile</th>
 <th className="px-3 py-2 text-left">Eingehend</th>
 <th className="px-3 py-2 text-left">Bestehendes Match</th>
 <th className="px-3 py-2 text-left w-28">Übereinstimmung</th>
 <th className="px-3 py-2 text-left w-40">Aktion</th>
 </tr>
 </thead>
 <tbody className="divide-y divide-border">
 {entries.map(([rowIndex, matches]) => {
 const best = getBestMatch(matches)
 const resolution = resolutions.get(rowIndex)
 const incoming = incomingRows[rowIndex]

 return (
 <tr key={rowIndex} className={rowBgClass(best.confidence)}>
 <td className="px-3 py-2.5 font-mono text-muted-foreground">{rowIndex + 1}</td>
 <td className="px-3 py-2.5 text-foreground">
 {getKeyFieldsDisplay(incoming, fieldLabels)}
 </td>
 <td className="px-3 py-2.5 text-foreground">
 {getKeyFieldsDisplay(best.existingRecord, fieldLabels)}
 </td>
 <td className="px-3 py-2.5">
 <span className={`inline-block text-[10px] font-semibold px-2 py-0.5 rounded-full ${confidenceBadgeClass(best.confidence)}`}>
 {best.confidence}% {confidenceLabel(best.confidence)}
 </span>
 </td>
 <td className="px-3 py-2.5">
 {resolution?.action ==='merge'? (
 <span className="flex items-center gap-1 text-success">
 <Check size={12} />
 Wird zusammengeführt
 </span>
 ) : resolution?.action ==='skip'? (
 <span className="flex items-center gap-1 text-muted-foreground">
 <SkipForward size={12} />
 Wird übersprungen
 </span>
 ) : (
 <div className="flex items-center gap-1.5">
 <button
 onClick={() => setMergingRowIndex(rowIndex)}
 className="flex items-center gap-1 text-[10px] font-medium px-2 py-1 rounded bg-primary text-white hover:bg-primary-dark transition-colors"
 >
 <GitMerge size={10} />
 Zusammenführen
 </button>
 <button
 onClick={() => onResolutionChange(rowIndex, { action:'skip'})}
 className="text-[10px] font-medium px-2 py-1 rounded border border-border text-muted-foreground hover:bg-background transition-colors"
 >
 Überspringen
 </button>
 {best.confidence < 95 && (
 <button
 onClick={() => onResolutionChange(rowIndex, { action:'create_anyway'})}
 className="text-[10px] font-medium px-2 py-1 rounded border border-border text-muted-foreground hover:bg-background transition-colors"
 >
 Trotzdem anlegen
 </button>
 )}
 </div>
 )}
 </td>
 </tr>
 )
 })}
 </tbody>
 </table>
 </div>
 </div>

 {/* Inline MergeDialog */}
 {mergingRowIndex !== null && duplicates.get(mergingRowIndex) && (
 <MergeDialog
 entityLabel={entityLabel}
 existingRecord={getBestMatch(duplicates.get(mergingRowIndex)!).existingRecord}
 incomingRecord={incomingRows[mergingRowIndex]}
 fieldLabels={fieldLabels}
 confidence={getBestMatch(duplicates.get(mergingRowIndex)!).confidence}
 matchType={getBestMatch(duplicates.get(mergingRowIndex)!).matchType}
 onMerge={(fieldResolutions) => {
 const best = getBestMatch(duplicates.get(mergingRowIndex)!)
 onResolutionChange(mergingRowIndex, {
 action:'merge',
 targetMatch: best,
 fieldResolutions,
 })
 setMergingRowIndex(null)
 }}
 onSkip={() => {
 onResolutionChange(mergingRowIndex, { action:'skip'})
 setMergingRowIndex(null)
 }}
 onCancel={() => setMergingRowIndex(null)}
 />
 )}
 </div>
 )
}
