'use client'

import { useState, useEffect, useCallback, useRef } from 'react'
import { Folder, ChevronRight, ChevronLeft, Home, X, Check, Server, User, Globe, Database, Loader2, FolderPlus } from 'lucide-react'

interface DirEntry {
    name: string
    path: string
    hasSubDirs: boolean
}

interface BrowseResult {
    path: string
    parent: string | null
    isWorkspacesRoot: boolean
    directories: DirEntry[]
}

interface QuickAccessEntry {
    label: string
    path: string
    icon: string
}

interface DefaultsResult {
    home: string
    workspacesRoot: string
    platform: string
    quickAccess: QuickAccessEntry[]
}

interface ServerFolderPickerProps {
    open: boolean
    onClose: () => void
    onSelect: (path: string) => void
}

const ICON_MAP: Record<string, React.ReactNode> = {
    home: <Home size={14} />,
    user: <User size={14} />,
    server: <Server size={14} />,
    database: <Database size={14} />,
    globe: <Globe size={14} />,
}

function pathParent(p: string): string {
    const parts = p.split('/').filter(Boolean)
    parts.pop()
    return '/' + parts.join('/')
}

export function ServerFolderPicker({ open, onClose, onSelect }: ServerFolderPickerProps) {
    const [currentPath, setCurrentPath] = useState('')
    const [directories, setDirectories] = useState<DirEntry[]>([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')
    const [selectedPath, setSelectedPath] = useState<string | null>(null)
    const [history, setHistory] = useState<string[]>([])
    const [quickAccess, setQuickAccess] = useState<QuickAccessEntry[]>([])
    const [pathInput, setPathInput] = useState('')
    const [isWorkspacesRoot, setIsWorkspacesRoot] = useState(false)
    const [isCreatingFolder, setIsCreatingFolder] = useState(false)
    const [newFolderName, setNewFolderName] = useState('')
    const [createError, setCreateError] = useState('')
    const [creating, setCreating] = useState(false)
    const listRef = useRef<HTMLDivElement>(null)

    const browse = useCallback(async (dirPath: string, pushHistory = true) => {
        setLoading(true)
        setError('')
        try {
            const res = await fetch(`/api/fs/browse?path=${encodeURIComponent(dirPath)}`)
            const data = await res.json() as BrowseResult & { error?: string }
            if (!res.ok) {
                setError(data.error || 'Failed to browse')
                setLoading(false)
                return
            }
            if (pushHistory && currentPath && currentPath !== data.path) {
                setHistory(prev => [...prev, currentPath])
            }
            setCurrentPath(data.path)
            setPathInput(data.path)
            setDirectories(data.directories)
            setSelectedPath(data.path)
            setIsWorkspacesRoot(data.isWorkspacesRoot)
            setCreateError('')
            if (!data.isWorkspacesRoot) {
                setIsCreatingFolder(false)
                setNewFolderName('')
            }
        } catch {
            setError('Network error')
        } finally {
            setLoading(false)
        }
    }, [currentPath])

    // Load defaults on open
    useEffect(() => {
        if (!open) return
        fetch('/api/fs/defaults')
            .then(r => r.json())
            .then((data: DefaultsResult) => {
                setQuickAccess(data.quickAccess)
                browse(data.workspacesRoot, false)
            })
            .catch(() => {
                // Fallback: browse home
                browse('', false)
            })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open])

    // Scroll to top on directory change
    useEffect(() => {
        if (listRef.current) listRef.current.scrollTop = 0
    }, [directories])

    const handleDoubleClick = useCallback((entry: DirEntry) => {
        browse(entry.path, true)
    }, [browse])

    const handleGoBack = useCallback(() => {
        if (history.length > 0) {
            const prevPath = history[history.length - 1]
            setHistory(h => h.slice(0, -1))
            browse(prevPath, false)
        } else if (currentPath && currentPath !== '/') {
            browse(pathParent(currentPath), false)
        }
    }, [history, currentPath, browse])

    const handlePathSubmit = useCallback(() => {
        const input = pathInput.trim()
        if (input && input !== currentPath) {
            browse(input, true)
        }
    }, [pathInput, currentPath, browse])

    const handlePathKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') handlePathSubmit()
    }, [handlePathSubmit])

    const cancelCreateFolder = useCallback(() => {
        setIsCreatingFolder(false)
        setNewFolderName('')
        setCreateError('')
    }, [])

    const handleCreateFolder = useCallback(async () => {
        const name = newFolderName.trim()
        if (!name || creating) return

        setCreating(true)
        setCreateError('')

        try {
            const res = await fetch('/api/fs/mkdir', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name }),
            })
            const data = await res.json() as { path?: string; error?: string }

            if (!res.ok || !data.path) {
                setCreateError(data.error || 'Failed to create folder')
                return
            }

            setIsCreatingFolder(false)
            setNewFolderName('')
            await browse(currentPath, false)
            setSelectedPath(data.path)
        } catch {
            setCreateError('Network error')
        } finally {
            setCreating(false)
        }
    }, [browse, creating, currentPath, newFolderName])

    const handleCreateFolderKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') handleCreateFolder()
        if (e.key === 'Escape') cancelCreateFolder()
    }, [cancelCreateFolder, handleCreateFolder])

    const handleConfirm = useCallback(() => {
        if (selectedPath) {
            onSelect(selectedPath)
            onClose()
        }
    }, [selectedPath, onSelect, onClose])

    const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
        if (e.key === 'Escape') onClose()
    }, [onClose])

    if (!open) return null

    return (
        <div
            className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 animate-fade-in"
            onClick={(e) => { if (e.target === e.currentTarget) onClose() }}
            onKeyDown={handleKeyDown}
        >
            <div className="w-[700px] max-h-[80vh] bg-surface border border-subtle rounded-2xl flex flex-col shadow-2xl animate-scale-in">

                {/* Header */}
                <div className="flex items-center justify-between px-5 py-4 border-b border-subtle">
                    <h2 className="text-[16px] font-semibold text-primary">Select Server Folder</h2>
                    <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-hover transition-colors">
                        <X size={18} className="text-muted" />
                    </button>
                </div>

                {/* Toolbar: navigation + path input */}
                <div className="flex items-center gap-2 px-5 py-3 border-b border-subtle">
                    <button
                        onClick={handleGoBack}
                        className="p-1.5 rounded-lg hover:bg-hover transition-colors text-secondary"
                        title="Go back"
                    >
                        <ChevronLeft size={16} />
                    </button>
                    <button
                        onClick={() => browse('/', true)}
                        className="p-1.5 rounded-lg hover:bg-hover transition-colors text-secondary"
                        title="Root /"
                    >
                        <Home size={16} />
                    </button>
                    <div className="flex-1 flex items-center gap-1 h-8 px-3 rounded-lg bg-elevated border border-subtle">
                        <input
                            value={pathInput}
                            onChange={(e) => setPathInput(e.target.value)}
                            onKeyDown={handlePathKeyDown}
                            onBlur={handlePathSubmit}
                            className="flex-1 bg-transparent text-[12px] font-mono text-primary outline-none placeholder:text-muted"
                            placeholder="/path/to/folder"
                        />
                    </div>
                </div>

                {/* Body: quick access sidebar + directory list */}
                <div className="flex flex-1 overflow-hidden min-h-[320px]">

                    {/* Quick access sidebar */}
                    {quickAccess.length > 0 && (
                        <div className="w-[140px] shrink-0 border-r border-subtle flex flex-col py-2 px-1.5 overflow-y-auto">
                            <span className="text-[10px] font-semibold text-muted uppercase tracking-wider px-2 mb-1">Quick Access</span>
                            {quickAccess.map(entry => (
                                <button
                                    key={entry.path}
                                    onClick={() => browse(entry.path, true)}
                                    className={`flex items-center gap-2 px-2 py-1.5 rounded-md text-left text-[11px] transition-colors
                    ${currentPath === entry.path ? 'bg-indigo/10 text-indigo font-medium' : 'text-secondary hover:bg-hover'}`}
                                >
                                    {ICON_MAP[entry.icon] || <Folder size={14} />}
                                    <span className="truncate">{entry.label}</span>
                                </button>
                            ))}
                        </div>
                    )}

                    {/* Directory list */}
                    <div ref={listRef} className="flex-1 overflow-y-auto py-1.5 px-2">
                        {loading ? (
                            <div className="flex items-center justify-center h-full text-muted text-[13px] gap-2">
                                <Loader2 size={16} className="animate-spin" />
                                Loading...
                            </div>
                        ) : error ? (
                            <div className="flex flex-col items-center justify-center h-full gap-2">
                                <span className="text-coral text-[13px]">{error}</span>
                                <button
                                    onClick={handleGoBack}
                                    className="text-[11px] text-indigo hover:underline"
                                >
                                    Go back
                                </button>
                            </div>
                        ) : directories.length === 0 && !isWorkspacesRoot ? (
                            <div className="flex flex-col items-center justify-center h-full gap-2">
                                <Folder size={24} className="text-muted" />
                                <span className="text-muted text-[13px]">No subdirectories</span>
                                <span className="text-[11px] text-tertiary">Click &quot;Select&quot; to use this folder, or go back</span>
                            </div>
                        ) : (
                            <>
                                {isWorkspacesRoot && (
                                    <div className="mb-1.5">
                                        {isCreatingFolder ? (
                                            <div className="flex items-center gap-2 px-3 py-[7px] rounded-lg border border-indigo/30 bg-indigo/5">
                                                <FolderPlus size={15} className="text-indigo shrink-0" />
                                                <input
                                                    autoFocus
                                                    value={newFolderName}
                                                    onChange={(e) => {
                                                        setNewFolderName(e.target.value)
                                                        setCreateError('')
                                                    }}
                                                    onKeyDown={handleCreateFolderKeyDown}
                                                    className="flex-1 min-w-0 bg-transparent text-[13px] text-primary outline-none placeholder:text-muted"
                                                    placeholder="New folder name"
                                                />
                                                <button
                                                    onClick={handleCreateFolder}
                                                    disabled={!newFolderName.trim() || creating}
                                                    className="flex h-6 w-6 items-center justify-center rounded-md text-indigo hover:bg-indigo/10 disabled:opacity-40"
                                                    title="Create folder"
                                                >
                                                    {creating ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />}
                                                </button>
                                                <button
                                                    onClick={cancelCreateFolder}
                                                    disabled={creating}
                                                    className="flex h-6 w-6 items-center justify-center rounded-md text-muted hover:bg-hover disabled:opacity-40"
                                                    title="Cancel"
                                                >
                                                    <X size={14} />
                                                </button>
                                            </div>
                                        ) : (
                                            <button
                                                onClick={() => setIsCreatingFolder(true)}
                                                className="flex w-full items-center gap-2 px-3 py-[7px] rounded-lg border border-dashed border-subtle text-secondary hover:bg-hover hover:border-indigo/30 hover:text-primary transition-colors"
                                            >
                                                <FolderPlus size={15} className="text-indigo shrink-0" />
                                                <span className="flex-1 text-left text-[13px]">New Folder</span>
                                            </button>
                                        )}
                                        {createError && (
                                            <div className="px-3 pt-1 text-[11px] text-coral">{createError}</div>
                                        )}
                                    </div>
                                )}
                                {directories.length === 0 ? (
                                    <div className="flex flex-col items-center justify-center h-[240px] gap-2">
                                        <Folder size={24} className="text-muted" />
                                        <span className="text-muted text-[13px]">No subdirectories</span>
                                        <span className="text-[11px] text-tertiary">Create a folder or click &quot;Select&quot; to use this folder</span>
                                    </div>
                                ) : directories.map((entry) => (
                                    <div
                                        key={entry.path}
                                        className={`flex items-center gap-2 px-3 py-[7px] rounded-lg cursor-pointer transition-colors
                    ${selectedPath === entry.path
                                            ? 'bg-indigo/10 border border-indigo/30'
                                            : 'hover:bg-hover border border-transparent'}`}
                                        onClick={() => setSelectedPath(entry.path)}
                                        onDoubleClick={() => handleDoubleClick(entry)}
                                    >
                                        <Folder size={15} className="text-indigo shrink-0" />
                                        <span className="flex-1 text-[13px] text-primary truncate">{entry.name}</span>
                                        {entry.hasSubDirs && (
                                            <ChevronRight size={13} className="text-muted shrink-0" />
                                        )}
                                    </div>
                                ))}
                            </>
                        )}
                    </div>
                </div>

                {/* Footer */}
                <div className="flex items-center justify-between px-5 py-4 border-t border-subtle">
          <span className="text-[12px] font-mono text-muted truncate max-w-[400px]" title={selectedPath || ''}>
            {selectedPath ? `Selected: ${selectedPath}` : 'No folder selected'}
          </span>
                    <div className="flex items-center gap-2">
                        <button
                            onClick={onClose}
                            className="px-4 h-9 rounded-lg border border-subtle text-[13px] text-secondary font-medium hover:bg-hover transition-colors"
                        >
                            Cancel
                        </button>
                        <button
                            onClick={handleConfirm}
                            disabled={!selectedPath}
                            className="px-4 h-9 rounded-lg bg-brand-primary text-on-primary text-[13px] font-semibold hover:bg-brand-primary-hover active:bg-brand-primary-active active:scale-[0.97] transition-colors disabled:opacity-40 flex items-center gap-1.5"
                        >
                            <Check size={14} /> Select
                        </button>
                    </div>
                </div>
            </div>
        </div>
    )
}
