import { useState } from 'react'
import { browse } from '../lib/api'

export default function DirectoryBrowser({ onSelect, onClose }) {
  const [current, setCurrent] = useState(null)   // null = roots
  const [parent, setParent]   = useState(null)
  const [dirs, setDirs]       = useState(null)   // null = not loaded yet
  const [loading, setLoading] = useState(false)
  const [error, setError]     = useState(null)

  async function navigate(path) {
    setLoading(true)
    setError(null)
    try {
      const data = await browse(path)
      setCurrent(data.path)
      setParent(data.parent)
      setDirs(data.dirs)
    } catch (e) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  // Load roots on first render
  if (dirs === null && !loading && !error) {
    navigate(null)
  }

  const breadcrumbs = current ? current.replace(/\\/g, '/').split('/').filter(Boolean) : []

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
      <div className="bg-slate-900 border border-slate-700 rounded-xl w-full max-w-lg mx-4 flex flex-col shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-slate-800">
          <span className="text-slate-200 font-semibold text-sm">Browse Folder</span>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-200">✕</button>
        </div>

        {/* Breadcrumb */}
        <div className="px-4 py-2 border-b border-slate-800 flex items-center gap-1 text-xs text-slate-400 flex-wrap min-h-[36px]">
          <button onClick={() => navigate(null)} className="hover:text-slate-200">Drives</button>
          {breadcrumbs.map((part, i) => {
            const path = breadcrumbs.slice(0, i + 1).join('\\') + (i === 0 ? '\\' : '')
            return (
              <span key={i} className="flex items-center gap-1">
                <span>/</span>
                <button
                  onClick={() => navigate(path)}
                  className="hover:text-slate-200 truncate max-w-[120px]"
                  title={path}
                >
                  {part}
                </button>
              </span>
            )
          })}
        </div>

        {/* Directory list */}
        <div className="overflow-y-auto max-h-64 divide-y divide-slate-800">
          {loading && (
            <p className="text-slate-500 text-sm text-center py-8">Loading…</p>
          )}
          {error && (
            <p className="text-red-400 text-sm text-center py-8">{error}</p>
          )}
          {!loading && !error && parent !== null && (
            <button
              onClick={() => navigate(parent)}
              className="w-full text-left px-4 py-2.5 text-slate-400 hover:bg-slate-800 text-sm transition-colors"
            >
              ↑ ..
            </button>
          )}
          {!loading && !error && dirs?.map(d => (
            <button
              key={d.path}
              onClick={() => navigate(d.path)}
              className="w-full text-left px-4 py-2.5 text-slate-300 hover:bg-slate-800 text-sm transition-colors flex items-center gap-2"
            >
              <span className="text-slate-500">📁</span>
              {d.name}
            </button>
          ))}
          {!loading && !error && dirs?.length === 0 && (
            <p className="text-slate-500 text-sm text-center py-8">No subdirectories</p>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between gap-2 px-4 py-3 border-t border-slate-800">
          <p className="text-xs text-slate-500 truncate flex-1" title={current ?? ''}>
            {current ?? 'Select a folder'}
          </p>
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="px-3 py-1.5 text-sm rounded-lg border border-slate-700 text-slate-300 hover:bg-slate-800 transition-colors"
            >
              Cancel
            </button>
            <button
              disabled={!current}
              onClick={() => { onSelect(current); onClose() }}
              className="px-3 py-1.5 text-sm rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              Select This Folder
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
