'use client'

import { useState, useRef } from'react'
import {
 FolderOpen, FolderClosed, FileText, FileImage, FileSpreadsheet, FilePieChart, File,
 Download, MoreVertical, Move, Copy, Trash2, ChevronDown, ChevronRight, Plus,
} from'lucide-react'
import Link from'next/link'
import { createClient } from'@/lib/supabase/client'
import { formatFileSize } from'@/lib/repository-types'

export interface DocRow {
 id: string
 title: string
 original_filename: string
 mime_type: string | null
 file_size: number | null
 created_at: string
 storage_key: string
 project_id: string | null
}

export interface SubProjectFolder {
 id: string
 project_code: string | null
 supplier_name: string
 documents: DocRow[]
}

interface Props {
 mainProjectId: string
 mainProjectLabel: string
 mainDocs: DocRow[]
 subProjects: SubProjectFolder[]
}

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

async function downloadDoc(storageKey: string, filename: string) {
 const supabase = createClient()
 const { data } = await supabase.storage.from('documents').createSignedUrl(storageKey, 60)
 if (!data?.signedUrl) return
 const a = document.createElement('a')
 a.href = data.signedUrl
 a.download = filename
 a.click()
}

interface ActionMenuProps {
 doc: DocRow
 mainProjectId: string
 subProjects: SubProjectFolder[]
 onMoved: (docId: string, newProjectId: string | null) => void
 onDeleted: (docId: string) => void
}

function DocActionMenu({ doc, mainProjectId, subProjects, onMoved, onDeleted }: ActionMenuProps) {
 const [open, setOpen] = useState(false)
 const [mode, setMode] = useState<'main'|'move'|'copy'|'confirmDelete'>('main')
 const [targetId, setTargetId] = useState<string>(mainProjectId)
 const [busy, setBusy] = useState(false)
 const supabase = createClient()

 const allProjects = [
 { id: mainProjectId, label:'📁 Hauptprojekt'},
 ...subProjects.map(s => ({ id: s.id, label: `📁 ${s.project_code ?? s.id.slice(0, 6)} — ${s.supplier_name}` })),
 ]

 async function doMove() {
 setBusy(true)
 await supabase.from('documents').update({ project_id: targetId }).eq('id', doc.id)
 try {
 await supabase.from('user_audit_log').insert({
 actor_id: null, target_user_id: null, action:'document.moved',
 details: { document_id: doc.id, to_project_id: targetId },
 })
 } catch { /* audit log is best-effort */ }
 onMoved(doc.id, targetId)
 setOpen(false)
 setBusy(false)
 }

 async function doCopy() {
 setBusy(true)
 const { data } = await supabase.from('documents').insert({
 title: doc.title,
 original_filename: doc.original_filename,
 mime_type: doc.mime_type,
 file_size: doc.file_size,
 storage_key: doc.storage_key,
 project_id: targetId,
 }).select().single()
 if (data) {
 try {
 await supabase.from('user_audit_log').insert({
 actor_id: null, target_user_id: null, action:'document.copied',
 details: { source_id: doc.id, copy_id: data.id, to_project_id: targetId },
 })
 } catch { /* audit log is best-effort */ }
 }
 setOpen(false)
 setBusy(false)
 }

 async function doDelete() {
 setBusy(true)
 await supabase.from('documents').update({ is_deleted: true }).eq('id', doc.id)
 try {
 await supabase.from('user_audit_log').insert({
 actor_id: null, target_user_id: null, action:'document.deleted',
 details: { document_id: doc.id },
 })
 } catch { /* audit log is best-effort */ }
 onDeleted(doc.id)
 setOpen(false)
 setBusy(false)
 }

 return (
 <div className="relative">
 <button
 onClick={e => { e.stopPropagation(); setOpen(v => !v); setMode('main') }}
 className="p-1.5 rounded hover:bg-background text-muted-foreground hover:text-foreground transition-colors shrink-0"
 title="Aktionen"
 >
 <MoreVertical size={13} />
 </button>

 {open && (
 <div className="absolute right-0 top-7 z-30 bg-card border border-border rounded-xl w-52 p-1"onClick={e => e.stopPropagation()}>
 {mode ==='main'&& (
 <>
 <button
 onClick={() => void downloadDoc(doc.storage_key, doc.original_filename)}
 className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs text-foreground hover:bg-background transition-colors"
 >
 <Download size={13} className="text-muted-foreground"/> Herunterladen
 </button>
 <button
 onClick={() => setMode('move')}
 className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs text-foreground hover:bg-background transition-colors"
 >
 <Move size={13} className="text-muted-foreground"/> Verschieben nach…
 </button>
 <button
 onClick={() => setMode('copy')}
 className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs text-foreground hover:bg-background transition-colors"
 >
 <Copy size={13} className="text-muted-foreground"/> Kopieren nach…
 </button>
 <div className="my-1 border-t border-border"/>
 <button
 onClick={() => setMode('confirmDelete')}
 className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs text-destructive hover:bg-[#FEE2E2] transition-colors"
 >
 <Trash2 size={13} /> Löschen
 </button>
 </>
 )}

 {(mode ==='move'|| mode ==='copy') && (
 <div className="p-2 space-y-2">
 <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wide">
 {mode ==='move'?'Verschieben nach':'Kopieren nach'}
 </p>
 <select
 value={targetId}
 onChange={e => setTargetId(e.target.value)}
 className="w-full h-8 px-2 rounded-lg border border-border text-xs bg-card focus:outline-none focus:border-primary"
 >
 {allProjects.map(p => (
 <option key={p.id} value={p.id}>{p.label}</option>
 ))}
 </select>
 <div className="flex gap-1">
 <button onClick={() => setMode('main')} className="flex-1 h-7 rounded-md border border-border text-[10px] text-muted-foreground">Zurück</button>
 <button
 onClick={() => void (mode ==='move'? doMove() : doCopy())}
 disabled={busy}
 className="flex-1 h-7 rounded-md bg-primary text-white text-[10px] font-semibold disabled:opacity-50"
 >
 {busy ?'…': mode ==='move'?'Verschieben':'Kopieren'}
 </button>
 </div>
 </div>
 )}

 {mode ==='confirmDelete'&& (
 <div className="p-3 space-y-2">
 <p className="text-xs text-foreground font-medium">Dokument löschen?</p>
 <p className="text-[10px] text-muted-foreground">{doc.title}</p>
 <div className="flex gap-1">
 <button onClick={() => setMode('main')} className="flex-1 h-7 rounded-md border border-border text-[10px] text-muted-foreground">Abbrechen</button>
 <button
 onClick={() => void doDelete()}
 disabled={busy}
 className="flex-1 h-7 rounded-md bg-destructive text-white text-[10px] font-semibold disabled:opacity-50"
 >
 {busy ?'…':'Löschen'}
 </button>
 </div>
 </div>
 )}
 </div>
 )}
 </div>
 )
}

function DocList({ docs, mainProjectId, subProjects, onMoved, onDeleted }: {
 docs: DocRow[]
 mainProjectId: string
 subProjects: SubProjectFolder[]
 onMoved: (docId: string, newProjectId: string | null) => void
 onDeleted: (docId: string) => void
}) {
 if (docs.length === 0) {
 return (
 <div className="py-4 px-4 text-[11px] text-muted-foreground flex items-center gap-2">
 <File size={13} className="opacity-40"/>
 Keine Dokumente
 </div>
 )
 }
 return (
 <ul className="divide-y divide-[#F0F4F8]">
 {docs.map(doc => (
 <li key={doc.id} className="flex items-center gap-3 px-4 py-2.5 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)} · {new Date(doc.created_at).toLocaleDateString('de-DE')}
 </p>
 </div>
 <button
 onClick={() => void downloadDoc(doc.storage_key, doc.original_filename)}
 title="Herunterladen"
 className="p-1.5 rounded hover:bg-secondary text-muted-foreground hover:text-primary transition-colors shrink-0"
 >
 <Download size={13} />
 </button>
 <DocActionMenu
 doc={doc}
 mainProjectId={mainProjectId}
 subProjects={subProjects}
 onMoved={onMoved}
 onDeleted={onDeleted}
 />
 </li>
 ))}
 </ul>
 )
}

function FolderSection({ label, count, children }: { label: string; count: number; children: React.ReactNode }) {
 const [open, setOpen] = useState(true)
 return (
 <div className="border border-border rounded-xl overflow-hidden">
 <button
 onClick={() => setOpen(v => !v)}
 className="w-full flex items-center gap-2 px-4 py-3 bg-background hover:bg-[#EEF4FA] transition-colors border-b border-border"
 >
 {open ? <FolderOpen size={15} className="text-primary shrink-0"/> : <FolderClosed size={15} className="text-muted-foreground shrink-0"/>}
 <span className="text-sm font-medium text-foreground flex-1 text-left">{label}</span>
 <span className="text-xs text-muted-foreground">{count} Dok.</span>
 {open ? <ChevronDown size={14} className="text-muted-foreground"/> : <ChevronRight size={14} className="text-muted-foreground"/>}
 </button>
 {open && <div>{children}</div>}
 </div>
 )
}

export default function DocumentsTree({ mainProjectId, mainProjectLabel, mainDocs: initialMainDocs, subProjects: initialSubProjects }: Props) {
 const [mainDocs, setMainDocs] = useState(initialMainDocs)
 const [subProjects, setSubProjects] = useState(initialSubProjects)

 function handleMoved(docId: string, newProjectId: string | null) {
 // Remove from current location, optionally re-add if staying in scope
 setMainDocs(prev => prev.filter(d => d.id !== docId))
 setSubProjects(prev => prev.map(sp => ({
 ...sp,
 documents: sp.documents.filter(d => d.id !== docId),
 })))
 // If moved within scope, find the new location
 if (newProjectId === mainProjectId) {
 // Moved to main — we'd need to re-fetch; just remove for now (will show on reload)
 }
 }

 function handleDeleted(docId: string) {
 setMainDocs(prev => prev.filter(d => d.id !== docId))
 setSubProjects(prev => prev.map(sp => ({
 ...sp,
 documents: sp.documents.filter(d => d.id !== docId),
 })))
 }

 const totalCount = mainDocs.length + subProjects.reduce((s, sp) => s + sp.documents.length, 0)

 return (
 <div className="space-y-4">
 <div className="flex items-center justify-between">
 <div className="flex items-center gap-2">
 <FolderOpen size={17} className="text-primary"/>
 <h2 className="text-base font-semibold text-foreground">Dokumente</h2>
 {totalCount > 0 && (
 <span className="text-xs font-semibold text-primary bg-secondary rounded-full px-2 py-0.5">{totalCount}</span>
 )}
 </div>
 <Link
 href={`/repository/projects?project=${mainProjectId}`}
 className="flex items-center gap-1.5 h-8 px-3 rounded-lg border border-primary text-xs text-primary hover:bg-secondary transition-colors"
 >
 <Plus size={13} />
 Hochladen
 </Link>
 </div>

 {/* Main project folder */}
 <FolderSection label={mainProjectLabel} count={mainDocs.length}>
 <DocList
 docs={mainDocs}
 mainProjectId={mainProjectId}
 subProjects={subProjects}
 onMoved={handleMoved}
 onDeleted={handleDeleted}
 />
 </FolderSection>

 {/* Sub-project folders */}
 {subProjects.map(sp => (
 <FolderSection
 key={sp.id}
 label={`${sp.project_code ? sp.project_code +'—':''}${sp.supplier_name}`}
 count={sp.documents.length}
 >
 <DocList
 docs={sp.documents}
 mainProjectId={mainProjectId}
 subProjects={subProjects}
 onMoved={handleMoved}
 onDeleted={handleDeleted}
 />
 </FolderSection>
 ))}

 {totalCount === 0 && (
 <div className="text-center py-10 text-muted-foreground text-sm">
 <File size={28} className="mx-auto mb-3 opacity-25"/>
 Noch keine Dokumente
 <div className="mt-2">
 <Link href={`/repository/projects?project=${mainProjectId}`} className="text-primary hover:underline text-xs">
 Erstes Dokument hochladen
 </Link>
 </div>
 </div>
 )}
 </div>
 )
}
