import React from 'react'
import { Folder, FileText, ArrowUp, ChevronRight, ChevronLeft, RefreshCw, HardDrive } from 'lucide-react'
import { clsx } from 'clsx'
import type { FileItem } from '@/lib/api'
import { fetchSystemFiles } from '@/lib/api'

interface LocalFilePanelProps {
  selectedFile: FileItem | null
  onSelect: (file: FileItem | null) => void
  onUpload: () => void
  disabled?: boolean
}

export const LocalFilePanel: React.FC<LocalFilePanelProps> = ({
  selectedFile,
  onSelect,
  onUpload,
  disabled,
}) => {
  const [currentPath, setCurrentPath] = React.useState('')
  const [files, setFiles] = React.useState<FileItem[]>([])
  const [loading, setLoading] = React.useState(false)
  const [pathHistory, setPathHistory] = React.useState<string[]>([''])

  const loadFiles = React.useCallback(async (systemPath: string) => {
    setLoading(true)
    try {
      const items = await fetchSystemFiles(systemPath)
      setFiles(items)
    } catch (err) {
      console.error('Failed to load local files:', err)
    } finally {
      setLoading(false)
    }
  }, [])

  React.useEffect(() => {
    loadFiles(currentPath)
  }, [currentPath, loadFiles])

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

  const handleGoInto = (folder: FileItem) => {
    setPathHistory([...pathHistory, folder.path])
    setCurrentPath(folder.path)
    onSelect(null)
  }

  const handleRefresh = () => {
    loadFiles(currentPath)
  }

  const getDisplayPath = () => {
    if (!currentPath) return '本地文件'
    if (currentPath === '' || currentPath === '/') return '根目录'
    const parts = currentPath.split(/[/\\]/)
    return parts[parts.length - 1] || currentPath
  }

  const getFullPathDisplay = () => {
    if (!currentPath) return ''
    return currentPath
  }

  return (
    <div className="flex flex-col h-full border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
      <div className="flex items-center justify-between px-3 py-2 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={pathHistory.length <= 1}
            className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed"
            title="返回上级"
          >
            <ChevronLeft size={16} />
          </button>
          <span className="text-sm font-medium text-gray-700 dark:text-gray-300 truncate max-w-[120px]">
            {getDisplayPath()}
          </span>
        </div>
        <button
          onClick={handleRefresh}
          disabled={loading}
          className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
          title="刷新"
        >
          <RefreshCw size={14} className={clsx(loading && 'animate-spin')} />
        </button>
      </div>

      <div className="flex-1 overflow-y-auto p-2">
        {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) => (
              <div
                key={file.path}
                onClick={() => onSelect(file.type === 'dir' ? null : file)}
                onDoubleClick={() => file.type === 'dir' && handleGoInto(file)}
                className={clsx(
                  'flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors',
                  selectedFile?.path === file.path
                    ? 'bg-blue-100 dark:bg-blue-900/30'
                    : 'hover:bg-gray-100 dark:hover:bg-gray-700/50'
                )}
              >
                {file.type === 'dir' ? (
                  <Folder size={16} className="text-yellow-500 flex-shrink-0" />
                ) : (
                  <FileText size={16} className="text-gray-400 flex-shrink-0" />
                )}
                <span className="flex-1 truncate text-sm text-gray-700 dark:text-gray-300">
                  {file.name}
                </span>
                {selectedFile?.path === file.path && (
                  <div className="w-4 h-4 rounded-full bg-blue-500 flex items-center justify-center">
                    <span className="text-white text-xs">✓</span>
                  </div>
                )}
              </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={onUpload}
          disabled={!selectedFile || disabled}
          className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 dark:disabled:bg-gray-600 text-white rounded-lg transition-colors"
        >
          <ArrowUp size={16} />
          上传
        </button>
      </div>
    </div>
  )
}
