import React from "react";

export const SwarmControlNodeSelectorModal = ({
  show,
  onClose,
  accessibleNodes,
  attachedNodeIds,
  syncConfig,
  setSyncConfig,
  workspaceId,
  isSearchingPath,
  showPathSuggestions,
  setShowPathSuggestions,
  pathSuggestions,
  setPathSuggestions,
  handleInitiateSync,
  isInitiatingSync,
  handleToggleNode,
  handleToggleReadOnly,
  onCancel
}) => {
  if (!show) return null;

  return (
    <div className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm flex justify-center items-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden animate-in zoom-in-95 duration-200">
        <div className="px-6 py-5 border-b dark:border-gray-700 flex justify-between items-center bg-gray-50 dark:bg-gray-800/50">
          <h3 className="font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <svg className="w-5 h-5 text-indigo-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" /></svg>
            Mesh Node Selection
          </h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
          </button>
        </div>
        <div className="p-6">
          <p className="text-xs text-gray-500 dark:text-gray-400 mb-4 font-medium">
            Select agent nodes to attach to this session. <strong>Click "Save & Sync" below to apply your changes.</strong> Attached nodes share the workspace <span className="font-mono bg-gray-100 dark:bg-gray-700 px-1 py-0.5 rounded italic">{workspaceId}</span>.
          </p>

          <div className="bg-indigo-50 dark:bg-indigo-900/10 p-4 rounded-xl mb-6 border border-indigo-100 dark:border-indigo-800">
            <h4 className="text-[10px] font-black uppercase text-indigo-600 dark:text-indigo-400 mb-3 tracking-widest">Initialization Strategy</h4>
            <div className="flex flex-col sm:flex-row gap-4 sm:gap-6">
              <label className="flex items-center gap-2 cursor-pointer group">
                <input
                  type="radio"
                  className="text-indigo-600 focus:ring-indigo-500"
                  checked={syncConfig.source === 'server'}
                  onChange={() => setSyncConfig({ ...syncConfig, source: 'server' })}
                />
                <div className="flex flex-col">
                  <span className="text-xs font-bold text-gray-700 dark:text-gray-200">Sync from Hub</span>
                  <span className="text-[10px] text-gray-400">Pull latest session state (Default)</span>
                </div>
              </label>
              <label className="flex items-center gap-2 cursor-pointer group">
                <input
                  type="radio"
                  className="text-indigo-600 focus:ring-indigo-500"
                  checked={syncConfig.source === 'node_local'}
                  onChange={() => setSyncConfig({ ...syncConfig, source: 'node_local' })}
                />
                <div className="flex flex-col">
                  <span className="text-xs font-bold text-gray-700 dark:text-gray-200">Seed from Local</span>
                  <span className="text-[10px] text-gray-400">Initialize from a node folder</span>
                </div>
              </label>
            </div>

            {syncConfig.source === 'node_local' && (
              <div className="mt-4 space-y-3 p-3 bg-white dark:bg-gray-800 rounded-lg border dark:border-gray-700">
                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1">Source Node</label>
                  <select
                    className="w-full bg-gray-50 dark:bg-gray-900 border-none rounded-lg px-3 py-2 text-xs font-bold dark:text-white"
                    value={syncConfig.source_node_id}
                    onChange={(e) => setSyncConfig({ ...syncConfig, source_node_id: e.target.value })}
                  >
                    <option value="">Select a source node...</option>
                    {accessibleNodes.filter(n => n.last_status === 'online' || n.last_status === 'idle').map(n => (
                      <option key={n.node_id} value={n.node_id}>{n.display_name} ({n.node_id})</option>
                    ))}
                  </select>
                </div>

                <div className="relative">
                  <label className="block text-[10px] font-bold text-gray-400 uppercase mb-1 flex justify-between">
                    <span>Local Absolute Path</span>
                    {isSearchingPath && <span className="animate-pulse text-indigo-500">Searching...</span>}
                  </label>
                  <input
                    type="text"
                    placeholder="/home/user/my-project"
                    className="w-full bg-gray-50 dark:bg-gray-900 border-none rounded-lg px-3 py-2 text-xs font-mono focus:ring-1 focus:ring-indigo-500 transition-all dark:text-white"
                    value={syncConfig.path}
                    onChange={(e) => {
                      setSyncConfig({ ...syncConfig, path: e.target.value });
                      setShowPathSuggestions(true);
                    }}
                    onFocus={() => setShowPathSuggestions(true)}
                    onBlur={() => setTimeout(() => setShowPathSuggestions(false), 200)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && pathSuggestions.length > 0 && showPathSuggestions) {
                        e.preventDefault();
                        const topSuggestion = pathSuggestions[0];
                        const lastSlash = syncConfig.path.lastIndexOf('/');
                        const base = lastSlash >= 0 ? syncConfig.path.substring(0, lastSlash + 1) : "";
                        setSyncConfig({ ...syncConfig, path: `${base}${topSuggestion}/` });
                        setPathSuggestions([]);
                      }
                    }}
                  />

                  {showPathSuggestions && pathSuggestions.length > 0 && (
                    <div className="absolute left-0 right-0 top-full mt-1 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-xl z-[70] max-h-40 overflow-y-auto overflow-x-hidden">
                      {pathSuggestions.map((suggestion, idx) => (
                        <div
                          key={idx}
                          className="px-3 py-2 text-[11px] font-mono cursor-pointer hover:bg-indigo-50 dark:hover:bg-indigo-900/30 dark:text-gray-300 border-b last:border-none dark:border-gray-700 truncate"
                          onClick={() => {
                            const lastSlash = syncConfig.path.lastIndexOf('/');
                            const base = lastSlash >= 0 ? syncConfig.path.substring(0, lastSlash + 1) : "";
                            setSyncConfig({ ...syncConfig, path: `${base}${suggestion}/` });
                            setPathSuggestions([]);
                          }}
                        >
                          📁 {suggestion}/
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          <div className="space-y-2 max-h-80 overflow-y-auto pr-2">
            {accessibleNodes.length === 0 && <span className="text-sm text-gray-400 italic">No nodes available for your account.</span>}
            {accessibleNodes.map(node => {
              const isAttached = attachedNodeIds.includes(node.node_id);
              const isOnline = node.last_status === 'online' || node.last_status === 'idle';

              return (
                <div
                  key={node.node_id}
                  className={`flex flex-col sm:flex-row sm:items-center justify-between p-4 rounded-xl border-2 transition-all gap-4 ${isAttached ? 'border-indigo-500 bg-indigo-50/50 dark:bg-indigo-900/10' : 'border-gray-100 dark:border-gray-700 hover:border-gray-200'}`}
                >
                  <div className="flex items-center space-x-3">
                    <div className={`w-2.5 h-2.5 rounded-full ${isOnline ? 'bg-green-500' : 'bg-gray-300'}`}></div>
                    <div>
                      <p className="font-bold text-sm text-gray-900 dark:text-gray-100">{node.display_name}</p>
                      <p className="text-[10px] text-gray-500 font-mono italic">{node.node_id}</p>
                    </div>
                  </div>
                  <div className="flex flex-wrap items-center gap-2">
                    {isAttached && (
                      <button
                        onClick={() => handleToggleReadOnly(node.node_id)}
                        className={`px-2 py-1.5 rounded-lg text-[10px] font-black uppercase tracking-tighter transition-all flex items-center gap-1 ${syncConfig.read_only_node_ids?.includes(node.node_id) ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-600 border border-amber-200 dark:border-amber-800' : 'bg-gray-50 dark:bg-gray-700/50 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200'}`}
                        title={syncConfig.read_only_node_ids?.includes(node.node_id) ? "Receiver only mode active" : "Enable receiver only mode"}
                      >
                        <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                        </svg>
                        {syncConfig.read_only_node_ids?.includes(node.node_id) ? 'Receiver Only' : 'Full Sync'}
                      </button>
                    )}
                    <button
                      onClick={() => handleToggleNode(node.node_id, isAttached)}
                      disabled={!isOnline && !isAttached}
                      className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all ${isAttached
                        ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-600/20'
                        : isOnline
                          ? 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-indigo-500 hover:text-white'
                          : 'bg-gray-50 dark:bg-gray-800 text-gray-300 dark:text-gray-600 cursor-not-allowed grayscale'
                        }`}
                      title={!isOnline && !isAttached ? "Node is currently offline" : ""}
                    >
                      {isAttached ? 'DETACH' : 'ATTACH'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="px-6 py-4 border-t dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 flex justify-between">
          <button
            onClick={handleInitiateSync}
            disabled={
              isInitiatingSync ||
              (syncConfig.source === 'node_local' && (!syncConfig.source_node_id || !syncConfig.path))
            }
            className="bg-indigo-600 text-white px-6 py-2 rounded-xl text-sm font-bold shadow-lg shadow-indigo-600/20 active:scale-95 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {isInitiatingSync ? (
              <>
                <svg className="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                Initiating...
              </>
            ) : 'Save & Sync'}
          </button>
          <button
            onClick={() => {
              if (onCancel) {
                onCancel();
              } else {
                onClose();
              }
            }}
            className="bg-gray-900 dark:bg-white dark:text-gray-900 text-white px-6 py-2 rounded-xl text-sm font-bold shadow-lg shadow-gray-900/20 active:scale-95 transition-all"
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  )}
