/**
 * DirPickerModal — 本地目录选择弹窗（调用后端 /setup/browse-dir）
 *
 * 用法:
 *   <DirPickerModal
 *     initial="/Users/me/papers"
 *     onSelect={(path) => setWorkDir(path)}
 *     onClose={() => setPickerOpen(false)}
 *   />
 */
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
  Folder,
  FolderOpen,
  ChevronRight,
  Home,
  ArrowLeft,
  Eye,
  EyeOff,
  Check,
} from 'lucide-react'
import { api } from '../api/client'
import { Spinner } from './ui'

interface DirEntry {
  name: string
  path: string
  hidden: boolean
}

interface BrowseResult {
  current: string
  parent: string | null
  home: string
  entries: DirEntry[]
}

function fetchBrowse(path: string): Promise<BrowseResult> {
  return api.get(`/setup/browse-dir?path=${encodeURIComponent(path)}`)
}

interface Props {
  initial?: string
  onSelect: (path: string) => void
  onClose: () => void
}

export default function DirPickerModal({ initial, onSelect, onClose }: Props) {
  const [current, setCurrent] = useState(initial || '~')
  const [showHidden, setShowHidden] = useState(false)

  const { data, isLoading, error } = useQuery<BrowseResult>({
    queryKey: ['browse-dir', current],
    queryFn: () => fetchBrowse(current),
    staleTime: 5_000,
    retry: 1,
  })

  const entries = (data?.entries ?? []).filter(e => showHidden || !e.hidden)

  /** Render the current path as clickable breadcrumb segments. */
  function Breadcrumb() {
    if (!data) return null
    const parts = data.current.split('/').filter(Boolean)
    const segments = parts.map((seg, i) => ({
      label: seg,
      path: '/' + parts.slice(0, i + 1).join('/'),
    }))
    return (
      <div className="flex items-center gap-0.5 flex-wrap text-xs text-gray-500 min-h-[20px]">
        <button
          onClick={() => setCurrent('/')}
          className="hover:text-indigo-600 px-1 rounded"
        >
          /
        </button>
        {segments.map((s, i) => (
          <span key={s.path} className="flex items-center gap-0.5">
            <ChevronRight size={11} className="text-gray-300 shrink-0" />
            <button
              onClick={() => setCurrent(s.path)}
              className={
                i === segments.length - 1
                  ? 'font-semibold text-gray-800 px-1 rounded'
                  : 'hover:text-indigo-600 px-1 rounded'
              }
            >
              {s.label}
            </button>
          </span>
        ))}
      </div>
    )
  }

  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-[60]">
      <div className="bg-white rounded-xl shadow-2xl w-full max-w-md flex flex-col" style={{ height: '520px' }}>
        {/* Header */}
        <div className="flex items-center justify-between px-4 pt-4 pb-2 border-b border-gray-100">
          <h3 className="text-sm font-semibold text-gray-900">选择工作目录</h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-lg leading-none"
          >
            ×
          </button>
        </div>

        {/* Toolbar */}
        <div className="flex items-center gap-2 px-4 py-2 border-b border-gray-100 bg-gray-50">
          {/* Back */}
          <button
            onClick={() => data?.parent && setCurrent(data.parent)}
            disabled={!data?.parent}
            className="p-1.5 rounded hover:bg-gray-200 disabled:opacity-30 disabled:cursor-not-allowed"
            title="上级目录"
          >
            <ArrowLeft size={14} />
          </button>
          {/* Home */}
          <button
            onClick={() => data?.home && setCurrent(data.home)}
            className="p-1.5 rounded hover:bg-gray-200"
            title="主目录"
          >
            <Home size={14} />
          </button>

          {/* Breadcrumb */}
          <div className="flex-1 overflow-hidden">
            <Breadcrumb />
          </div>

          {/* Show/hide hidden */}
          <button
            onClick={() => setShowHidden(v => !v)}
            className={`p-1.5 rounded hover:bg-gray-200 ${showHidden ? 'text-indigo-600' : 'text-gray-400'}`}
            title={showHidden ? '隐藏隐藏文件夹' : '显示隐藏文件夹'}
          >
            {showHidden ? <Eye size={14} /> : <EyeOff size={14} />}
          </button>
        </div>

        {/* Directory list */}
        <div className="flex-1 overflow-y-auto px-2 py-2">
          {isLoading && (
            <div className="flex justify-center py-8"><Spinner size={20} /></div>
          )}
          {error && (
            <p className="text-xs text-red-500 px-2 py-4 text-center">
              无法读取目录
            </p>
          )}
          {!isLoading && !error && entries.length === 0 && (
            <p className="text-xs text-gray-400 px-2 py-4 text-center">
              此目录下没有子目录
            </p>
          )}
          {entries.map(entry => (
            <button
              key={entry.path}
              onDoubleClick={() => setCurrent(entry.path)}
              onClick={() => setCurrent(entry.path)}
              className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-left text-sm transition-colors
                ${current === entry.path
                  ? 'bg-indigo-50 text-indigo-700'
                  : 'hover:bg-gray-50 text-gray-700'
                }
                ${entry.hidden ? 'opacity-60 italic' : ''}
              `}
            >
              {current === entry.path
                ? <FolderOpen size={15} className="text-indigo-500 shrink-0" />
                : <Folder size={15} className="text-amber-500 shrink-0" />
              }
              <span className="truncate">{entry.name}</span>
              <ChevronRight size={12} className="ml-auto text-gray-300 shrink-0" />
            </button>
          ))}
        </div>

        {/* Selected path preview + confirm */}
        <div className="px-4 py-3 border-t border-gray-100 bg-gray-50 rounded-b-xl">
          <p className="text-[11px] text-gray-500 mb-2 font-medium">已选目录</p>
          <div className="flex items-center gap-2">
            <code className="flex-1 text-xs bg-white border border-gray-200 rounded-lg px-3 py-2 text-gray-800 truncate font-mono">
              {data?.current ?? current}
            </code>
            <button
              onClick={() => { onSelect(data?.current ?? current); onClose() }}
              disabled={!data?.current}
              className="flex items-center gap-1.5 px-4 py-2 bg-indigo-600 text-white text-sm rounded-lg hover:bg-indigo-700 disabled:opacity-40 shrink-0"
            >
              <Check size={14} />
              选择
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
