import React, { useState, useEffect, useCallback } from 'react'
import { Folder, FileText, ChevronLeft, RefreshCw, HardDrive } from 'lucide-react'
import { clsx } from 'clsx'
import { fetchRemoteFiles, fetchRemoteDrives, type RemoteFileItem } from '../../api'

interface RemoteFilePanelProps {
  serverHost: string
  port: number
  password?: string
  selectedFile: RemoteFileItem | null
  onSelect: (file: RemoteFileItem | null) => void
  onDownload: () => void
  disabled?: boolean
}

export const RemoteFilePanel: React.FC<RemoteFilePanelProps> = ({
  serverHost,
  port,
  password,
  selectedFile,
  onSelect,
  onDownload,
  disabled,
}) => {
  const [currentPath, setCurrentPath] = useState('')
  const [files, setFiles] = useState<RemoteFileItem[]>([])
  const [loading, setLoading] = useState(false)
  const [pathHistory, setPathHistory] = useState<string[]>([''])
  const [showDrives, setShowDrives] = useState(true)

  const loadDrives = useCallback(async () => {
    setLoading(true)
    try {
      const drives = await fetchRemoteDrives(serverHost, port, password)
      setFiles(drives)
      setShowDrives(true)
    } catch (err) {
      console.error('Failed to load remote drives:', err)
      setFiles([])
    } finally {
      setLoading(false)
    }
  }, [serverHost, port, password])

  const loadFiles = useCallback(async (path: string) => {
    setLoading(true)
    try {
      const items = await fetchRemoteFiles(serverHost, port, path, password, true)
      setFiles(items)
      setShowDrives(false)
    } catch (err) {
      console.error('Failed to load remote files:', err)
      setFiles([])
    } finally {
      setLoading(false)
    }
  }, [serverHost, port, password])

  useEffect(() => {
    loadDrives()
  }, [loadDrives])

  const handleGoBack = () => {
    if (showDrives) {
      return
    }
    if (pathHistory.length > 1) {
      const newHistory = [...pathHistory]
      newHistory.pop()
      const prevPath = newHistory[newHistory.length - 1]
      setPathHistory(newHistory)
      setCurrentPath(prevPath)
      onSelect(null)
    } else {
      loadDrives()
    }
  }

  const handleGoInto = (file: RemoteFileItem) => {
    if (showDrives) {
      const newPath = file.path + '\\'
      setPathHistory(['', newPath])
      setCurrentPath(newPath)
      loadFiles(newPath)
    } else {
      const newPath = currentPath ? `${currentPath}\\${file.name}` : file.name
      setPathHistory([...pathHistory, newPath])
      setCurrentPath(newPath)
      loadFiles(newPath)
    }
    onSelect(null)
  }

  const handleRefresh = () => {
    if (showDrives) {
      loadDrives()
    } else {
      loadFiles(currentPath)
    }
  }

  const handleGoToRoot = () => {
    setPathHistory([''])
    setCurrentPath('')
    loadDrives()
    onSelect(null)
  }

  const getDisplayPath = () => {
    if (showDrives) return '选择驱动器'
    if (!currentPath) return '远程文件'
    return currentPath
  }

  return (
    <div className="flex flex-col h-full border border-gray-200 dark:border-gray-700 overflow-hidden">
      <div className="h-12 flex items-center justify-between px-4 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-2">
          <button
            onClick={handleGoBack}
            disabled={showDrives}
            className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed"
            title={showDrives ? '已是根目录' : '返回上级'}
          >
            <ChevronLeft size={18} />
          </button>
          <button
            onClick={handleGoToRoot}
            className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
            title="回到驱动器列表"
          >
            <HardDrive size={18} />
          </button>
          <span className="text-base font-medium text-gray-700 dark:text-gray-300 truncate max-w-[150px]">
            {getDisplayPath()}
          </span>
        </div>
        <button
          onClick={handleRefresh}
          disabled={loading}
          className="p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
          title="刷新"
        >
          <RefreshCw size={16} className={clsx(loading && 'animate-spin')} />
        </button>
      </div>

      <div className="flex-1 overflow-y-auto p-2" onClick={(e) => {
        if ((e.target as HTMLElement).classList.contains('space-y-1') || (e.target as HTMLElement).classList.contains('p-2')) {
          onSelect(null)
        }
      }}>
        {loading ? (
          <div className="flex items-center justify-center h-full text-gray-400">
            加载中...
          </div>
        ) : files.length === 0 ? (
          <div className="flex items-center justify-center h-full text-gray-400">
            空文件夹
          </div>
        ) : (
          <div className="space-y-1">
            {files.map((file) => {
              const isDrive = showDrives && file.name.length === 2 && file.name.endsWith(':')
              return (
                <div
                  key={file.path}
                  onClick={() => onSelect(selectedFile?.path === file.path ? null : file)}
                  onDoubleClick={() => (file.type === 'dir' || isDrive) && handleGoInto(file)}
                  className={clsx(
                    'flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer transition-colors text-sm',
                    selectedFile?.path === file.path
                      ? 'bg-gray-100 text-gray-800 dark:bg-gray-700/60 dark:text-gray-200'
                      : 'hover:bg-gray-100 dark:hover:bg-gray-700/50 text-gray-700 dark:text-gray-200'
                  )}
                >
                  {isDrive ? (
                    <HardDrive size={16} className="text-blue-500 dark:text-blue-400 shrink-0" />
                  ) : file.type === 'dir' ? (
                    <Folder size={16} className="text-gray-500 dark:text-gray-400 shrink-0" />
                  ) : (
                    <FileText size={16} className="text-gray-500 dark:text-gray-400 shrink-0" />
                  )}
                  <span className="flex-1 truncate">
                    {file.name}
                  </span>
                </div>
              )
            })}
          </div>
        )}
      </div>

      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
        <button
          onClick={onDownload}
          disabled={!selectedFile || disabled}
          className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-gray-600 hover:bg-gray-700 disabled:bg-gray-400 dark:disabled:bg-gray-700 dark:disabled:text-gray-500 text-white rounded-lg transition-colors"
        >
          <span>↓</span>
          下载
        </button>
      </div>
    </div>
  )
}
