import { ref } from 'vue'
import type { FileItem, FolderItem } from './types'

// 默认的 SKILL.md 内容
const DEFAULT_SKILL_CONTENT = `# Skill Configuration

## Overview
This skill is configured to process data and generate outputs.

## Dependencies
- Python 3.8+
- Node.js 16+
`

export function useFileTree() {
  // 文件树数据
  const fileTree = ref<FolderItem[]>([
    {
      id: 'folder-1',
      name: 'Data',
      icon: 'fa-folder',
      type: 'folder',
      expanded: true,
      children: [
        { id: 'file-1', name: 'user_data.csv', icon: 'fa-file', content: 'id,name,email,age\n1,John Doe,john@example.com,28\n2,Jane Smith,jane@example.com,32', type: 'file' },
        { id: 'file-2', name: 'config.json', icon: 'fa-code', content: '{\n  "appName": "MyApp",\n  "version": "1.0.0",\n  "debug": true\n}', type: 'file' },
      ]
    },
    {
      id: 'folder-2',
      name: 'Script',
      icon: 'fa-folder',
      type: 'folder',
      expanded: true,
      children: [
        { id: 'file-3', name: 'process.py', icon: 'fa-code', content: 'import pandas as pd\n\ndef process_data(data):\n    """Process the input data"""\n    return data.apply(lambda x: x.strip())\n\nif __name__ == "__main__":\n    df = pd.read_csv("user_data.csv")\n    processed = process_data(df)\n    processed.to_csv("output.csv", index=False)', type: 'file' },
        { id: 'file-4', name: 'transform.js', icon: 'fa-code', content: 'function transformData(input) {\n  return input.map(item => ({\n    ...item,\n    processed: true,\n    timestamp: Date.now()\n  }));\n}\n\nmodule.exports = { transformData };', type: 'file' },
      ]
    },
    {
      id: 'folder-3',
      name: 'Reference',
      icon: 'fa-folder',
      type: 'folder',
      expanded: true,
      children: [
        { id: 'file-5', name: 'api_docs.md', icon: 'fa-code', content: '# API Documentation\n\n## Endpoints\n\n### GET /api/users\nReturns list of users.\n\n### POST /api/users\nCreate a new user.', type: 'file' },
      ]
    },
  ])

  // 根目录文件
  const rootFiles = ref<FileItem[]>([
    { id: 'file-root-1', name: 'SKILL.md', icon: 'fa-file', content: DEFAULT_SKILL_CONTENT, type: 'file' },
  ])

  // 展开/收起文件夹
  const toggleFolder = (folder: FolderItem) => {
    folder.expanded = !folder.expanded
  }

  // 新建文件夹 - 内联输入模式
  const inlineNewFolderName = ref('')
  const inlineCreatingFolderId = ref<string | null>(null)

  const showInlineNewFolderInput = (parentId: string | null = null) => {
    inlineNewFolderName.value = ''
    inlineCreatingFolderId.value = parentId === null ? 'root' : parentId
  }

  const confirmInlineCreateFolder = () => {
    if (!inlineNewFolderName.value.trim()) {
      inlineCreatingFolderId.value = null
      return
    }

    const newFolder: FolderItem = {
      id: 'folder-' + Date.now(),
      name: inlineNewFolderName.value,
      icon: 'fa-folder',
      type: 'folder',
      expanded: true,
      children: []
    }

    if (inlineCreatingFolderId.value && inlineCreatingFolderId.value !== 'root') {
      const parentFolder = findFolderById(fileTree.value, inlineCreatingFolderId.value)
      if (parentFolder && parentFolder.children) {
        parentFolder.children.push(newFolder)
        // 选中新创建的文件夹
        selectedFolder.value = newFolder.id
        parentFolder.expanded = true
      }
    } else {
      fileTree.value.push(newFolder)
      // 选中新创建的文件夹
      selectedFolder.value = newFolder.id
    }
    inlineCreatingFolderId.value = null
    inlineNewFolderName.value = ''
  }

  const cancelInlineCreateFolder = () => {
    inlineCreatingFolderId.value = null
    inlineNewFolderName.value = ''
    // 恢复选中之前选中的文件夹
    if (selectedFolder.value) {
      const folder = findFolderById(fileTree.value, selectedFolder.value)
      if (folder) {
        folder.expanded = true
      }
    }
  }

  // 递归查找文件夹
  const findFolderById = (folders: (FileItem | FolderItem)[], id: string): FolderItem | null => {
    for (const folder of folders) {
      if ('children' in folder && folder.id === id) return folder as FolderItem
      if ('children' in folder && folder.children) {
        const found = findFolderById(folder.children, id)
        if (found) return found
      }
    }
    return null
  }

  // 新建文件 - 内联输入模式
  const inlineNewFileName = ref('')
  const inlineCreatingFileId = ref<string | null>(null)

  const showInlineNewFileInput = (folderId: string | null = null) => {
    inlineNewFileName.value = ''
    inlineCreatingFileId.value = folderId === null ? 'root' : folderId
  }

  const confirmInlineCreateFile = () => {
    if (!inlineNewFileName.value.trim()) {
      inlineCreatingFileId.value = null
      return
    }

    const newFile: FileItem = {
      id: 'file-' + Date.now(),
      name: inlineNewFileName.value,
      icon: getFileIconByName(inlineNewFileName.value),
      content: '',
      type: 'file'
    }

    if (inlineCreatingFileId.value && inlineCreatingFileId.value !== 'root') {
      const folder = findFolderById(fileTree.value, inlineCreatingFileId.value)
      if (folder && folder.children) {
        folder.children.push(newFile)
        // 选中父文件夹
        selectedFolder.value = folder.id
        folder.expanded = true
      }
    } else {
      rootFiles.value.push(newFile)
    }

    inlineCreatingFileId.value = null
    inlineNewFileName.value = ''
  }

  const cancelInlineCreateFile = () => {
    inlineCreatingFileId.value = null
    inlineNewFileName.value = ''
    // 恢复选中之前选中的文件夹
    if (selectedFolder.value) {
      const folder = findFolderById(fileTree.value, selectedFolder.value)
      if (folder) {
        folder.expanded = true
      }
    }
  }

  // 根据文件名获取图标
  const getFileIconByName = (filename: string): string => {
    const ext = filename.split('.').pop()?.toLowerCase()
    const codeExtensions = ['js', 'ts', 'py', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'java', 'c', 'cpp', 'go', 'rs', 'php', 'rb', 'swift', 'kt', 'sql', 'sh', 'bash', 'md']
    if (codeExtensions.includes(ext || '')) {
      return 'fa-code'
    }
    return 'fa-file'
  }

  // 上传文件
  const handleFileUpload = (event: Event, folderId: string | null = null) => {
    const input = event.target as HTMLInputElement
    if (!input.files?.length) return

    Array.from(input.files).forEach(file => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const newFile: FileItem = {
          id: 'file-' + Date.now() + Math.random(),
          name: file.name,
          icon: getFileIconByName(file.name),
          content: e.target?.result as string || '',
          type: 'file'
        }

        if (folderId) {
          const folder = findFolderById(fileTree.value, folderId)
          if (folder && folder.children) {
            folder.children.push(newFile)
          }
        } else {
          rootFiles.value.push(newFile)
        }
      }
      reader.readAsText(file)
    })

    input.value = ''
  }

  // 递归查找文件
  const findFile = (items: (FileItem | FolderItem)[], fileId: string): FileItem | null => {
    for (const item of items) {
      if (item.type === 'file' && item.id === fileId) {
        return item
      }
      if (item.type === 'folder' && item.children) {
        const found = findFile(item.children, fileId)
        if (found) return found
      }
    }
    return null
  }

  // 文件编辑相关状态
  const isEditingFile = ref(false)
  const isEditingFileClosing = ref(false)
  const editingFile = ref<FileItem | null>(null)
  const editingFileName = ref('')
  const editingFileContent = ref('')
  const editingFileType = ref('')

  // 选中文件/文件夹状态
  const hoveringItem = ref<string | null>(null)
  const selectedFolder = ref<string | null>(null)

  // 选中文件夹
  const selectFolder = (folderId: string) => {
    if (selectedFolder.value === folderId) {
      selectedFolder.value = null
    } else {
      selectedFolder.value = folderId
      const folder = findFolderById(fileTree.value, folderId)
      if (folder) {
        folder.expanded = true
      }
    }
  }

  // 删除文件
  const deleteFile = (file: FileItem, parentId: string | null) => {
    if (!parentId) {
      rootFiles.value = rootFiles.value.filter(f => f.id !== file.id)
    } else {
      const folder = fileTree.value.find(f => f.id === parentId)
      if (folder && folder.children) {
        folder.children = folder.children.filter(c => (c as FileItem).id !== file.id)
      }
    }
  }

  // 删除文件夹
  const deleteFolder = (folder: FolderItem) => {
    fileTree.value = fileTree.value.filter(f => f.id !== folder.id)
  }

  // 打开文件编辑器
  const openFile = (file: FileItem) => {
    editingFile.value = file
    editingFileName.value = file.name
    editingFileContent.value = file.content || ''
    editingFileType.value = 'file'
    isEditingFile.value = true
  }

  const saveFileEdit = () => {
    if (!editingFile.value) return
    editingFile.value.content = editingFileContent.value
    isEditingFileClosing.value = true
    setTimeout(() => {
      isEditingFile.value = false
      isEditingFileClosing.value = false
      editingFile.value = null
    }, 300)
  }

  const cancelFileEdit = () => {
    isEditingFileClosing.value = true
    setTimeout(() => {
      isEditingFile.value = false
      isEditingFileClosing.value = false
      editingFile.value = null
    }, 300)
  }

  return {
    // State
    fileTree,
    rootFiles,
    inlineNewFolderName,
    inlineCreatingFolderId,
    inlineNewFileName,
    inlineCreatingFileId,
    isEditingFile,
    isEditingFileClosing,
    editingFile,
    editingFileName,
    editingFileContent,
    editingFileType,
    hoveringItem,
    selectedFolder,

    // Methods
    toggleFolder,
    showInlineNewFolderInput,
    confirmInlineCreateFolder,
    cancelInlineCreateFolder,
    findFolderById,
    showInlineNewFileInput,
    confirmInlineCreateFile,
    cancelInlineCreateFile,
    getFileIconByName,
    handleFileUpload,
    findFile,
    selectFolder,
    deleteFile,
    deleteFolder,
    openFile,
    saveFileEdit,
    cancelFileEdit,
  }
}
