'use client';

import * as React from 'react';

/**
 * Folder selection helper used by new-project + edit-project modals.
 * Three ways to set a path:
 *   1. Type / paste it into the input
 *   2. "Choose folder…" → native OS dialog via /api/fs/pick-folder
 *   3. "Create new folder" → inline parent+name → /api/fs/create-folder
 */
export default function FolderPicker({ name = 'folder_path', value, onChange, inputRef, placeholder = '/Users/you/Documents/my-project' }) {
  const [feedback, setFeedback] = React.useState(null);
  const [showCreate, setShowCreate] = React.useState(false);
  const [createParent, setCreateParent] = React.useState('');
  const [createName, setCreateName] = React.useState('');
  const [busy, setBusy] = React.useState(null);

  React.useEffect(() => {
    if (showCreate && !createParent) setCreateParent(value || '~/Documents');
  }, [showCreate, value, createParent]);

  async function pasteFromClipboard() {
    setFeedback(null);
    if (!navigator.clipboard?.readText) { setFeedback({ kind: 'error', message: 'Clipboard not available.' }); return; }
    let raw;
    try { raw = await navigator.clipboard.readText(); }
    catch { setFeedback({ kind: 'error', message: 'Allow clipboard access.' }); return; }
    let v = (raw || '').trim();
    if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
    if (v.startsWith('file://')) { try { v = decodeURI(v.slice('file://'.length)); } catch {} }
    if (!v) { setFeedback({ kind: 'error', message: 'Clipboard is empty.' }); return; }
    if (!v.startsWith('/') && !v.startsWith('~')) { setFeedback({ kind: 'error', message: 'Path must be absolute.' }); return; }
    onChange(v);
    setFeedback({ kind: 'success', message: 'Pasted.' });
  }

  async function openNativePicker() {
    setFeedback(null);
    setBusy('pick');
    try {
      const res = await fetch('/api/fs/pick-folder', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ title: 'Choose project folder', start_path: value && value.startsWith('/') ? value : undefined }),
      });
      if (res.status === 499) { setFeedback({ kind: 'error', message: 'Cancelled.' }); return; }
      const data = await res.json();
      if (!res.ok) { setFeedback({ kind: 'error', message: data.error || 'Picker failed.' }); return; }
      onChange(data.folder_path);
      setFeedback({ kind: 'success', message: `Selected ${data.folder_path}` });
    } catch (err) {
      setFeedback({ kind: 'error', message: String(err?.message || err) });
    } finally { setBusy(null); }
  }

  async function createFolder() {
    setFeedback(null);
    if (!createParent.trim() || !createName.trim()) {
      setFeedback({ kind: 'error', message: 'Parent and name required.' });
      return;
    }
    setBusy('create');
    try {
      const res = await fetch('/api/fs/create-folder', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ parent: createParent.trim(), name: createName.trim() }),
      });
      const data = await res.json();
      if (!res.ok) { setFeedback({ kind: 'error', message: data.error || 'Create failed.' }); return; }
      onChange(data.folder_path);
      setShowCreate(false);
      setCreateName('');
      setFeedback({ kind: 'success', message: `Created ${data.folder_path}` });
    } catch (err) {
      setFeedback({ kind: 'error', message: String(err?.message || err) });
    } finally { setBusy(null); }
  }

  return (
    <>
      <div className="agents-modal-paste-row">
        <input
          ref={inputRef}
          name={name}
          type="text"
          placeholder={placeholder}
          autoComplete="off"
          spellCheck={false}
          value={value || ''}
          onChange={(e) => { onChange(e.target.value); if (feedback) setFeedback(null); }}
          required
        />
        <button type="button" className="admin-button secondary" onClick={openNativePicker} disabled={busy === 'pick'}>
          {busy === 'pick' ? 'Opening…' : 'Choose folder…'}
        </button>
      </div>

      <div className="agents-modal-folder-tools">
        <button type="button" className="admin-button secondary" onClick={pasteFromClipboard}>Paste from clipboard</button>
        <button type="button" className="admin-button secondary" onClick={() => onChange('~/Documents')}>~/Documents</button>
        <button type="button" className="admin-button secondary" onClick={() => onChange('~/Desktop')}>~/Desktop</button>
        <button type="button" className="admin-button secondary" onClick={() => setShowCreate((s) => !s)}>
          {showCreate ? 'Cancel new folder' : '+ New folder'}
        </button>
      </div>

      {showCreate ? (
        <div className="agents-modal-create-folder">
          <small>Create a folder anywhere outside system directories. Parent must exist.</small>
          <div className="agents-modal-create-row">
            <input
              type="text"
              placeholder="Parent (e.g. ~/Documents)"
              value={createParent}
              onChange={(e) => setCreateParent(e.target.value)}
              spellCheck={false}
              autoComplete="off"
            />
          </div>
          <div className="agents-modal-create-row">
            <input
              type="text"
              placeholder="New folder name"
              value={createName}
              onChange={(e) => setCreateName(e.target.value)}
              spellCheck={false}
              autoComplete="off"
            />
            <button type="button" className="admin-button" onClick={createFolder} disabled={busy === 'create'}>
              {busy === 'create' ? 'Creating…' : 'Create'}
            </button>
          </div>
        </div>
      ) : null}

      {feedback ? (
        <p className={`agents-modal-feedback ${feedback.kind}`} role="status" aria-live="polite">{feedback.message}</p>
      ) : null}
    </>
  );
}
