import { Input, message, Modal } from 'antd'
import { useState } from 'react'
import type { FileCategory } from '../api'
import FileCategoryTree from '../components/files/FileCategoryTree'
import FileTable from '../components/files/FileTable'
import FileUploadModal from '../components/files/FileUploadModal'
import PageWrapper from '../components/PageWrapper'
import { useFiles } from '../hooks/useFiles'

interface CategoryDialogState {
  open: boolean
  mode: 'create' | 'rename'
  name: string
  parentId?: string
  categoryId?: string
}

const CLOSED_CATEGORY_DIALOG: CategoryDialogState = {
  open: false,
  mode: 'create',
  name: '',
}

export default function FilesPage() {
  const {
    categories,
    files,
    config,
    selectedCategoryId,
    selectedCategoryName,
    loading,
    selectCategory,
    refresh,
    createCategory,
    renameCategory,
    deleteCategory,
    uploadFiles,
    deleteFile,
    downloadFile,
  } = useFiles()
  const [uploadOpen, setUploadOpen] = useState(false)
  const [categoryDialog, setCategoryDialog] = useState<CategoryDialogState>(CLOSED_CATEGORY_DIALOG)
  const [categorySaving, setCategorySaving] = useState(false)

  const openCreateCategory = (parentId?: string) => {
    setCategoryDialog({ open: true, mode: 'create', name: '', parentId })
  }

  const openRenameCategory = (category: FileCategory) => {
    setCategoryDialog({
      open: true,
      mode: 'rename',
      name: category.name,
      categoryId: category.id,
    })
  }

  const saveCategory = async () => {
    const name = categoryDialog.name.trim()
    if (!name) return
    setCategorySaving(true)
    try {
      if (categoryDialog.mode === 'create') {
        await createCategory(name, categoryDialog.parentId)
        message.success('分类已创建')
      } else if (categoryDialog.categoryId) {
        await renameCategory(categoryDialog.categoryId, name)
        message.success('分类已更新')
      }
      setCategoryDialog(CLOSED_CATEGORY_DIALOG)
    } catch {
      // The shared API interceptor displays the server error.
    } finally {
      setCategorySaving(false)
    }
  }

  const handleDeleteCategory = async (id: string) => {
    try {
      await deleteCategory(id)
      message.success('分类已删除')
    } catch {
      // The shared API interceptor displays the server error.
    }
  }

  const handleDeleteFile = async (id: string) => {
    try {
      await deleteFile(id)
      message.success('文件已删除')
    } catch {
      // The shared API interceptor displays the server error.
    }
  }

  const handleDownload = async (record: Parameters<typeof downloadFile>[0]) => {
    try {
      await downloadFile(record)
    } catch {
      // The shared API interceptor displays the server error.
    }
  }

  return (
    <PageWrapper title="原始文件" description="上传和管理评测相关的原始文件" inline fullHeight>
      <div className="files-layout">
        <FileCategoryTree
          categories={categories}
          selectedCategoryId={selectedCategoryId}
          onSelect={selectCategory}
          onCreate={openCreateCategory}
          onRename={openRenameCategory}
          onDelete={handleDeleteCategory}
        />
        <FileTable
          files={files}
          categories={categories}
          loading={loading}
          categoryName={selectedCategoryName}
          onRefresh={() => void refresh().catch(() => undefined)}
          onOpenUpload={() => setUploadOpen(true)}
          onDownload={handleDownload}
          onDelete={handleDeleteFile}
        />
      </div>

      <FileUploadModal
        open={uploadOpen}
        categories={categories}
        config={config}
        initialCategoryId={selectedCategoryId}
        onClose={() => setUploadOpen(false)}
        onUpload={uploadFiles}
      />

      <Modal
        title={categoryDialog.mode === 'create' ? '新建分类' : '重命名分类'}
        open={categoryDialog.open}
        onOk={() => void saveCategory()}
        onCancel={() => setCategoryDialog(CLOSED_CATEGORY_DIALOG)}
        okText={categoryDialog.mode === 'create' ? '创建' : '保存'}
        confirmLoading={categorySaving}
        okButtonProps={{ disabled: !categoryDialog.name.trim() }}
        width={360}
        destroyOnHidden
      >
        <Input
          autoFocus
          placeholder="分类名称"
          value={categoryDialog.name}
          onChange={(event) => setCategoryDialog((current) => ({
            ...current,
            name: event.target.value,
          }))}
          onPressEnter={() => void saveCategory()}
        />
      </Modal>
    </PageWrapper>
  )
}
