/**
 * 服务器文件浏览面板
 */
import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { ChevronRight, Folder, File, Home, ArrowLeft, Plus, Trash2, RefreshCw, Link, Copy, FileText } from 'lucide-react';
import { browseDirectory, createDirectory, removeFile, pathUtils, type RemoteFileInfo } from '@/services/fileService';
import { message } from 'antd';
import type { ServerFilePanelProps } from './types';

export const ServerFilePanel: React.FC<ServerFilePanelProps> = ({
    serverId,
    currentPath,
    onPathChange,
    refreshTrigger,
}) => {
    const [files, setFiles] = useState<RemoteFileInfo[]>([]);
    const [loading, setLoading] = useState(false);
    const [showNewFolder, setShowNewFolder] = useState(false);
    const [newFolderName, setNewFolderName] = useState('');
    const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
    const [pendingDeleteFile, setPendingDeleteFile] = useState<RemoteFileInfo | null>(null);

    // 加载文件列表
    const loadFiles = async () => {
        setLoading(true);
        try {
            const data = await browseDirectory(serverId, currentPath);
            // 排序：目录在前，文件在后
            const sorted = data.sort((a, b) => {
                if (a.isDirectory === b.isDirectory) {
                    return a.name.localeCompare(b.name);
                }
                return a.isDirectory ? -1 : 1;
            });
            setFiles(sorted);
        } catch (error: any) {
            message.error(error.response?.data?.message || '加载文件列表失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadFiles();
    }, [serverId, currentPath, refreshTrigger]);

    // 进入目录
    const handleEnterDirectory = (file: RemoteFileInfo) => {
        if (file.isDirectory) {
            onPathChange(file.path);
        }
    };

    // 返回上级目录
    const handleGoBack = () => {
        const parent = pathUtils.getParent(currentPath);
        onPathChange(parent);
    };

    // 回到Home
    const handleGoHome = () => {
        onPathChange('/');
    };

    // 创建新文件夹
    const handleCreateFolder = async () => {
        if (!newFolderName.trim()) {
            message.warning('请输入文件夹名称');
            return;
        }
        try {
            const newPath = pathUtils.join(currentPath, newFolderName);
            await createDirectory(serverId, newPath);
            message.success('创建成功');
            setShowNewFolder(false);
            setNewFolderName('');
            loadFiles();
        } catch (error: any) {
            message.error(error.response?.data?.message || '创建失败');
        }
    };

    // 请求删除文件/目录（弹出确认框）
    const handleDelete = (file: RemoteFileInfo) => {
        setPendingDeleteFile(file);
        setDeleteConfirmOpen(true);
    };

    // 确认删除
    const handleConfirmDelete = async () => {
        setDeleteConfirmOpen(false);
        if (!pendingDeleteFile) return;

        try {
            await removeFile(serverId, pendingDeleteFile.path, pendingDeleteFile.isDirectory);
            message.success('删除成功');
            loadFiles();
        } catch (error: any) {
            message.error(error.response?.data?.message || '删除失败');
        } finally {
            setPendingDeleteFile(null);
        }
    };

    // 取消删除
    const handleCancelDelete = () => {
        setDeleteConfirmOpen(false);
        setPendingDeleteFile(null);
    };

    // 面包屑导航
    const breadcrumbs = currentPath.split('/').filter(Boolean);

    return (
        <div className="h-full flex flex-col">
            {/* 工具栏 */}
            <div className="flex items-center gap-2 p-2 border-b flex-shrink-0">
                <Button
                    size="sm"
                    variant="ghost"
                    onClick={handleGoHome}
                    disabled={currentPath === '/'}
                    title="回到根目录"
                >
                    <Home className="h-4 w-4" />
                </Button>
                <Button
                    size="sm"
                    variant="ghost"
                    onClick={handleGoBack}
                    disabled={currentPath === '/'}
                    title="返回上级"
                >
                    <ArrowLeft className="h-4 w-4" />
                </Button>
                <Button
                    size="sm"
                    variant="ghost"
                    onClick={() => setShowNewFolder(true)}
                    title="新建文件夹"
                >
                    <Plus className="h-4 w-4" />
                </Button>
                <Button
                    size="sm"
                    variant="ghost"
                    onClick={loadFiles}
                    title="刷新"
                >
                    <RefreshCw className="h-4 w-4" />
                </Button>
            </div>

            {/* 路径导航 */}
            <div className="flex items-center gap-1 px-3 py-2 text-sm text-gray-600 dark:text-gray-400 border-b overflow-x-auto flex-shrink-0">
                <button
                    className="hover:text-blue-600 dark:hover:text-blue-400"
                    onClick={() => onPathChange('/')}
                    title="返回根目录"
                >
                    /
                </button>
                {breadcrumbs.map((name, index) => (
                    <React.Fragment key={index}>
                        <ChevronRight className="h-4 w-4 flex-shrink-0" />
                        <button
                            className="hover:text-blue-600 dark:hover:text-blue-400"
                            onClick={() => {
                                const path = '/' + breadcrumbs.slice(0, index + 1).join('/');
                                onPathChange(path);
                            }}
                        >
                            {name}
                        </button>
                    </React.Fragment>
                ))}
            </div>

            {/* 新建文件夹输入框 */}
            {showNewFolder && (
                <div className="flex items-center gap-2 p-2 bg-blue-50 dark:bg-blue-900/20 border-b flex-shrink-0">
                    <Input
                        placeholder="文件夹名称"
                        value={newFolderName}
                        onChange={(e) => setNewFolderName(e.target.value)}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter') handleCreateFolder();
                            if (e.key === 'Escape') {
                                setShowNewFolder(false);
                                setNewFolderName('');
                            }
                        }}
                        autoFocus
                        className="flex-1"
                    />
                    <Button size="sm" onClick={handleCreateFolder}>
                        确定
                    </Button>
                    <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => {
                            setShowNewFolder(false);
                            setNewFolderName('');
                        }}
                    >
                        取消
                    </Button>
                </div>
            )}

            {/* 文件列表 */}
            <div className="flex-1 overflow-y-auto" style={{ minHeight: 0 }}>
                {/* 表头 - 固定显示 */}
                <div className="sticky top-0 bg-gray-50 dark:bg-gray-900 border-b px-2 py-1 flex items-center gap-2 text-xs font-medium text-gray-600 dark:text-gray-400 z-10">
                    <div className="flex-1 min-w-[150px]">名称</div>
                    <div className="w-20 text-right flex-shrink-0">大小</div>
                    <div className="w-24 flex-shrink-0">权限</div>
                    <div className="w-16 flex-shrink-0">所有者</div>
                    <div className="w-28 flex-shrink-0">修改时间</div>
                    <div className="w-24 flex-shrink-0"></div>
                </div>

                <div className="p-2 min-h-[200px]">
                    {loading ? (
                        <div className="space-y-2">
                            {/* 骨架屏 - 仅模拟数据行 */}
                            {Array.from({ length: 8 }).map((_, i) => (
                                <div key={i} className="flex items-center gap-2 px-2 py-1.5">
                                    <Skeleton className="h-4 w-4 rounded flex-shrink-0" />
                                    <Skeleton className="h-4 flex-1 min-w-[150px]" />
                                    <Skeleton className="h-4 w-20 flex-shrink-0" />
                                    <Skeleton className="h-4 w-24 flex-shrink-0" />
                                    <Skeleton className="h-4 w-16 flex-shrink-0" />
                                    <Skeleton className="h-4 w-28 flex-shrink-0" />
                                    <Skeleton className="h-4 w-24 flex-shrink-0" />
                                </div>
                            ))}
                        </div>
                    ) : files.length === 0 ? (
                        <div className="flex items-center justify-center h-full text-gray-500">
                            空目录
                        </div>
                    ) : (
                        <div className="space-y-1">
                        {files.map((file) => (
                            <div
                                key={file.path}
                                className="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-800 group"
                            >
                                {/* 文件名 */}
                                <div
                                    className="flex-1 min-w-[150px] flex items-center gap-2 cursor-pointer select-none"
                                    onDoubleClick={() => handleEnterDirectory(file)}
                                    title={file.isSymlink ? `链接到: ${file.linkTarget || '未知'}` : file.name}
                                >
                                    {file.isDirectory ? (
                                        <Folder className="h-4 w-4 text-blue-500 flex-shrink-0" />
                                    ) : (
                                        <File className="h-4 w-4 text-gray-500 flex-shrink-0" />
                                    )}
                                    <span className="text-sm truncate flex items-center gap-1">
                                        {file.name}
                                        {file.isSymlink && (
                                            <Link className="h-3 w-3 text-cyan-500 flex-shrink-0" />
                                        )}
                                    </span>
                                </div>
                                
                                {/* 文件大小 */}
                                <span className="text-xs text-gray-500 w-20 text-right flex-shrink-0">
                                    {file.sizeFormatted}
                                </span>
                                
                                {/* 权限 */}
                                <span className="text-xs text-gray-500 font-mono w-24 flex-shrink-0">
                                    {file.permissions}
                                </span>
                                
                                {/* 所有者:组 */}
                                <span className="text-xs text-gray-500 w-16 flex-shrink-0 truncate" title={`${file.owner}:${file.group}`}>
                                    {file.owner}
                                </span>
                                
                                {/* 修改时间 */}
                                <span className="text-xs text-gray-500 w-28 flex-shrink-0">
                                    {new Date(file.modifyTime).toLocaleDateString('zh-CN', {
                                        month: '2-digit',
                                        day: '2-digit',
                                        hour: '2-digit',
                                        minute: '2-digit'
                                    })}
                                </span>
                                
                                {/* 操作按钮 */}
                                <div className="flex items-center gap-1 w-24 flex-shrink-0">
                                    {/* 复制文件名按钮 */}
                                    <Button
                                        size="sm"
                                        variant="ghost"
                                        className="h-6 w-8 p-0 opacity-0 group-hover:opacity-100"
                                        onClick={() => {
                                            navigator.clipboard.writeText(file.name);
                                            message.success('文件名已复制');
                                        }}
                                        title="复制文件名"
                                    >
                                        <FileText className="h-3.5 w-3.5 text-blue-500" />
                                    </Button>
                                    {/* 复制路径按钮 */}
                                    <Button
                                        size="sm"
                                        variant="ghost"
                                        className="h-6 w-8 p-0 opacity-0 group-hover:opacity-100"
                                        onClick={() => {
                                            navigator.clipboard.writeText(file.path);
                                            message.success('路径已复制');
                                        }}
                                        title="复制路径"
                                    >
                                        <Copy className="h-3.5 w-3.5 text-gray-500" />
                                    </Button>
                                    {/* 删除按钮 */}
                                    <Button
                                        size="sm"
                                        variant="ghost"
                                        className="h-6 w-8 p-0 opacity-0 group-hover:opacity-100"
                                        onClick={() => handleDelete(file)}
                                        title="删除"
                                    >
                                        <Trash2 className="h-3.5 w-3.5 text-red-500" />
                                    </Button>
                                </div>
                            </div>
                        ))}
                        </div>
                    )}
                </div>
            </div>

            {/* 删除确认对话框 */}
            <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>确认删除</AlertDialogTitle>
                        <AlertDialogDescription>
                            {pendingDeleteFile?.isDirectory ? (
                                <>
                                    确定删除目录 <span className="font-semibold text-foreground">"{pendingDeleteFile.name}"</span> 及其所有内容吗？
                                    <br />
                                    <span className="text-red-600">此操作不可恢复！</span>
                                </>
                            ) : (
                                <>
                                    确定删除文件 <span className="font-semibold text-foreground">"{pendingDeleteFile?.name}"</span> 吗？
                                </>
                            )}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={handleCancelDelete}>
                            取消
                        </AlertDialogCancel>
                        <AlertDialogAction onClick={handleConfirmDelete} className="bg-red-600 hover:bg-red-700">
                            删除
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
};
