'use client';

import { useEffect, useState } from 'react';

interface Entry { name: string; path: string }

export function FolderPicker({ onSelect, onClose }: {
  onSelect: (path: string) => void;
  onClose: () => void;
}) {
  const [path, setPath] = useState<string>('');
  const [parent, setParent] = useState<string | null>(null);
  const [home, setHome] = useState<string>('');
  const [entries, setEntries] = useState<Entry[]>([]);
  const [error, setError] = useState<string>('');

  const load = (p?: string) => {
    setError('');
    const q = p ? `?path=${encodeURIComponent(p)}` : '';
    fetch(`/api/fs/browse${q}`).then(r => r.json()).then(d => {
      if (!d.ok) { setError(d.error || 'failed'); return; }
      setPath(d.path);
      setParent(d.parent);
      setHome(d.home);
      setEntries(d.entries);
    }).catch(e => setError(e.message));
  };

  useEffect(() => { load(); }, []);

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60]" onClick={onClose}>
      <div
        className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-lg w-[520px] max-h-[70vh] flex flex-col"
        onClick={e => e.stopPropagation()}
      >
        <div className="px-4 py-3 border-b border-[var(--border)] flex items-center gap-2">
          <span className="text-xs font-semibold">Select Folder</span>
          <button onClick={() => load(home)} className="text-[10px] px-2 py-0.5 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-primary)]">~ Home</button>
          <button onClick={onClose} className="ml-auto text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]">✕</button>
        </div>

        <div className="px-4 py-2 border-b border-[var(--border)] flex items-center gap-2">
          <button
            onClick={() => parent && load(parent)}
            disabled={!parent}
            className="text-[10px] px-2 py-0.5 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-primary)] disabled:opacity-40"
          >↑ Up</button>
          <input
            value={path}
            onChange={e => setPath(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && load(path)}
            className="flex-1 px-2 py-1 bg-[var(--bg-tertiary)] border border-[var(--border)] rounded text-[11px] font-mono"
          />
          <button onClick={() => load(path)} className="text-[10px] px-2 py-0.5 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-primary)]">Go</button>
        </div>

        <div className="flex-1 overflow-y-auto px-2 py-2 min-h-[200px]">
          {error && <div className="text-[11px] text-red-400 px-2 py-1">{error}</div>}
          {entries.map(e => (
            <button
              key={e.path}
              onClick={() => load(e.path)}
              className="w-full text-left px-2 py-1 rounded text-[11px] font-mono hover:bg-[var(--bg-tertiary)] flex items-center gap-2"
            >
              <span className="text-[var(--text-secondary)]">📁</span>
              <span>{e.name}</span>
            </button>
          ))}
          {!error && entries.length === 0 && (
            <div className="text-[11px] text-[var(--text-secondary)] px-2 py-4 text-center">(no subdirectories)</div>
          )}
        </div>

        <div className="px-4 py-3 border-t border-[var(--border)] flex items-center justify-between gap-2">
          <span className="text-[10px] text-[var(--text-secondary)] font-mono truncate flex-1" title={path}>{path}</span>
          <button
            onClick={() => { onSelect(path); onClose(); }}
            disabled={!path}
            className="text-[10px] px-3 py-1 bg-[var(--accent)] text-white rounded disabled:opacity-50"
          >Select this folder</button>
        </div>
      </div>
    </div>
  );
}
