'use client'

import { useState, useEffect, useCallback } from'react'
import {
 X,
 Search,
 FileText,
 FileImage,
 FileSpreadsheet,
 FilePieChart,
 File,
} from'lucide-react'
import { createClient } from'@/lib/supabase/client'
import type { Document } from'@/lib/repository-types'
import { UploadForm } from'./upload-dialog'

interface Props {
 projectId?: string
 onSelect: (doc: Document) => void
 onClose: () => void
 title?: string
}

type Tab ='upload'|'browse'
type ScopeFilter ='project'|'all'

function formatFileSize(bytes: number | null): string {
 if (bytes === null) return'—'
 if (bytes < 1024) return `${bytes} B`
 if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
 return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

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

export default function DocumentPickerModal({ projectId, onSelect, onClose, title ='Dokument auswählen'}: Props) {
 const [activeTab, setActiveTab] = useState<Tab>('browse')
 const [documents, setDocuments] = useState<Document[]>([])
 const [loading, setLoading] = useState(false)
 const [search, setSearch] = useState('')
 const [scopeFilter, setScopeFilter] = useState<ScopeFilter>(projectId ?'project':'all')

 const loadDocuments = useCallback(async (scope: ScopeFilter, searchTerm: string) => {
 setLoading(true)
 const supabase = createClient()
 let query = supabase
 .from('documents')
 .select('*')
 .eq('is_deleted', false)
 .order('created_at', { ascending: false })
 .limit(100)

 if (scope ==='project'&& projectId) {
 query = query.eq('project_id', projectId)
 }

 if (searchTerm.trim()) {
 query = query.ilike('title', `%${searchTerm.trim()}%`)
 }

 const { data } = await query
 setDocuments((data as Document[]) ?? [])
 setLoading(false)
 }, [projectId])

 useEffect(() => {
 if (activeTab ==='browse') {
 loadDocuments(scopeFilter, search)
 }
 }, [activeTab, scopeFilter, loadDocuments])

 function handleSearchKey(e: React.KeyboardEvent<HTMLInputElement>) {
 if (e.key ==='Enter') {
 loadDocuments(scopeFilter, search)
 }
 }

 function handleScopeChange(scope: ScopeFilter) {
 setScopeFilter(scope)
 loadDocuments(scope, search)
 }

 function handleUploadSuccess(doc: Document) {
 onSelect(doc)
 }

 return (
 <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
 <div className="bg-card text-foreground rounded-xl w-full max-w-2xl max-h-[85vh] flex flex-col">
 {/* Header */}
 <div className="flex items-center justify-between px-6 py-4 border-b border-border">
 <h2 className="font-semibold text-foreground">{title}</h2>
 <button
 onClick={onClose}
 className="text-muted-foreground hover:text-foreground transition-colors"
 >
 <X size={18} />
 </button>
 </div>

 {/* Tabs */}
 <div className="flex border-b border-border px-6">
 <TabButton active={activeTab ==='upload'} onClick={() => setActiveTab('upload')}>
 Neu hochladen
 </TabButton>
 <TabButton active={activeTab ==='browse'} onClick={() => setActiveTab('browse')}>
 Aus Datenablage
 </TabButton>
 </div>

 {/* Tab content */}
 <div className="flex-1 min-h-0 overflow-hidden">
 {activeTab ==='upload'? (
 <div className="h-full overflow-y-auto px-6 py-5">
 <UploadForm
 projectId={projectId}
 repositoryType={projectId ?'project':'global_template'}
 onSuccess={handleUploadSuccess}
 />
 </div>
 ) : (
 <div className="flex flex-col h-full">
 {/* Browse controls */}
 <div className="px-6 py-3 border-b border-border space-y-2">
 <div className="relative">
 <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"/>
 <input
 type="search"
 value={search}
 onChange={(e) => setSearch(e.target.value)}
 onKeyDown={handleSearchKey}
 placeholder="Suchen (Enter zum Suchen)…"
 className="w-full pl-9 pr-3 py-2 text-sm border border-border rounded focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
 />
 </div>
 {projectId && (
 <div className="flex gap-2">
 <ScopeToggle
 active={scopeFilter ==='project'}
 onClick={() => handleScopeChange('project')}
 >
 Dieses Projekt
 </ScopeToggle>
 <ScopeToggle
 active={scopeFilter ==='all'}
 onClick={() => handleScopeChange('all')}
 >
 Alle Dokumente
 </ScopeToggle>
 </div>
 )}
 </div>

 {/* Document list */}
 <div className="flex-1 overflow-y-auto">
 {loading ? (
 <div className="flex items-center justify-center py-16 text-sm text-muted-foreground">
 Lade Dokumente…
 </div>
 ) : documents.length === 0 ? (
 <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
 <FileText size={32} className="opacity-20 mb-3"/>
 <p className="text-sm font-medium">Keine Dokumente gefunden</p>
 </div>
 ) : (
 <table className="w-full text-sm">
 <thead className="sticky top-0 bg-background border-b border-border">
 <tr className="text-xs text-muted-foreground font-medium">
 <th className="px-4 py-3 text-left w-6"></th>
 <th className="px-2 py-3 text-left">Titel</th>
 <th className="px-2 py-3 text-left hidden sm:table-cell">Typ</th>
 <th className="px-2 py-3 text-right hidden md:table-cell">Größe</th>
 <th className="px-4 py-3 text-right"></th>
 </tr>
 </thead>
 <tbody className="divide-y divide-border">
 {documents.map((doc) => (
 <tr
 key={doc.id}
 className="hover:bg-background cursor-pointer transition-colors"
 onClick={() => onSelect(doc)}
 >
 <td className="px-4 py-3">{getMimeIcon(doc.mime_type)}</td>
 <td className="px-2 py-3 max-w-[200px]">
 <p className="font-medium text-foreground text-xs truncate">{doc.title}</p>
 <p className="text-[10px] text-muted-foreground truncate">{doc.original_filename}</p>
 </td>
 <td className="px-2 py-3 hidden sm:table-cell">
 {doc.document_type ? (
 <span className="text-xs bg-secondary text-primary rounded-full px-2 py-0.5 font-medium">
 {doc.document_type}
 </span>
 ) : (
 <span className="text-xs text-muted-foreground">—</span>
 )}
 </td>
 <td className="px-2 py-3 text-xs text-right font-mono text-muted-foreground hidden md:table-cell">
 {formatFileSize(doc.file_size)}
 </td>
 <td className="px-4 py-3 text-right">
 <button
 onClick={(e) => { e.stopPropagation(); onSelect(doc) }}
 className="text-xs text-primary hover:text-primary-dark font-medium px-2.5 py-1 rounded hover:bg-secondary transition-colors"
 >
 Auswählen
 </button>
 </td>
 </tr>
 ))}
 </tbody>
 </table>
 )}
 </div>
 </div>
 )}
 </div>

 {/* Footer */}
 <div className="flex justify-end px-6 py-4 border-t border-border">
 <button
 onClick={onClose}
 className="text-sm px-4 py-2 rounded border border-border text-foreground hover:bg-background transition-colors"
 >
 Schließen
 </button>
 </div>
 </div>
 </div>
 )
}

function TabButton({
 active,
 onClick,
 children,
}: {
 active: boolean
 onClick: () => void
 children: React.ReactNode
}) {
 return (
 <button
 onClick={onClick}
 className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
 active
 ?'border-primary text-primary'
 :'border-transparent text-muted-foreground hover:text-foreground'
 }`}
 >
 {children}
 </button>
 )
}

function ScopeToggle({
 active,
 onClick,
 children,
}: {
 active: boolean
 onClick: () => void
 children: React.ReactNode
}) {
 return (
 <button
 onClick={onClick}
 className={`text-xs px-3 py-1.5 rounded-full font-medium transition-colors ${
 active
 ?'bg-primary text-white'
 :'bg-background text-muted-foreground border border-border hover:border-primary/40'
 }`}
 >
 {children}
 </button>
 )
}

