import { h } from 'preact';
import { useState, useMemo } from 'preact/hooks';
import type { SignalRef } from './lib/types';

interface Props {
  onClose: () => void;
  onAddSignals: (signals: SignalRef[]) => void;
}

interface Rule {
  type: 'name' | 'tag' | 'property';
  key?: string;
  value: string;
}

type SearchSource = 'cfs' | 'archiver';

export default function ChannelFinderModal({ onClose, onAddSignals }: Props) {
  const [source, setSource] = useState<SearchSource>('cfs');
  
  // CFS State
  const [rules, setRules] = useState<Rule[]>([{ type: 'name', value: '' }]);
  const [cfsResults, setCfsResults] = useState<Array<{ name: string, properties: any, tags: any }>>([]);
  
  // Archiver State
  const [archPattern, setArchPattern] = useState('');
  const [archResults, setArchResults] = useState<string[]>([]);

  const [searching, setSearching] = useState(false);
  const [error, setError] = useState('');

  async function handleCfsSearch() {
    if (!rules.some(r => r.value.trim() !== '')) return;
    setSearching(true);
    setError('');
    
    try {
      const params = new URLSearchParams();
      for (const r of rules) {
        if (!r.value.trim()) continue;
        if (r.type === 'name') {
          params.append('~name', r.value.includes('*') ? r.value : `*${r.value}*`);
        } else if (r.type === 'tag') {
          params.append('~tag', r.value);
        } else if (r.type === 'property' && r.key) {
          params.append(r.key, r.value);
        }
      }

      const res = await fetch(`/api/v1/channel-finder?${params.toString()}`);
      if (!res.ok) throw new Error(`CFS Search failed: ${res.statusText}`);
      const data = await res.json();
      setCfsResults(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setSearching(false);
    }
  }

  async function handleArchSearch() {
    if (!archPattern.trim()) return;
    setSearching(true);
    setError('');
    
    try {
      const res = await fetch(`/api/v1/archiver/search?q=${encodeURIComponent(archPattern)}`);
      if (!res.ok) {
          if (res.status === 501) throw new Error("Archiver discovery not configured");
          throw new Error(`Archiver Search failed: ${res.statusText}`);
      }
      const data = await res.json();
      setArchResults(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setSearching(false);
    }
  }

  function addRule() {
    setRules([...rules, { type: 'property', key: '', value: '' }]);
  }

  function updateRule(idx: number, patch: Partial<Rule>) {
    setRules(rules.map((r, i) => i === idx ? { ...r, ...patch } : r));
  }

  function removeRule(idx: number) {
    setRules(rules.filter((_, i) => i !== idx));
  }

  function handleAddAll() {
    const refs = source === 'cfs' 
      ? cfsResults.map(r => ({ ds: 'epics', name: r.name }))
      : archResults.map(name => ({ ds: 'epics', name }));
    onAddSignals(refs);
    onClose();
  }

  const resultsCount = source === 'cfs' ? cfsResults.length : archResults.length;

  return (
    <div class="wizard-backdrop" onClick={onClose}>
      <div class="wizard" onClick={e => e.stopPropagation()} style="max-width: 750px; height: 85vh;">
        <div class="wizard-header">
          <span>PV Discovery</span>
          <button class="icon-btn" onClick={onClose}>✕</button>
        </div>

        <div class="wizard-body" style="display: flex; flex-direction: column;">
          {/* Source Tabs */}
          <div class="signal-tree-tabs" style="margin-bottom: 1.5rem;">
            <button
              class={`stab${source === 'cfs' ? ' stab-active' : ''}`}
              onClick={() => { setSource('cfs'); setError(''); }}
            >Channel Finder</button>
            <button
              class={`stab${source === 'archiver' ? ' stab-active' : ''}`}
              onClick={() => { setSource('archiver'); setError(''); }}
            >Archive Appliance</button>
          </div>

          {source === 'cfs' ? (
            <div style="flex: 0 0 auto;">
              <div class="wizard-section-title">Channel Finder Rules</div>
              <p class="hint" style="padding: 0 0 0.5rem 0;">Filter by name, tags, or properties.</p>
              
              {rules.map((rule, idx) => (
                <div key={idx} class="wizard-field wizard-field-row" style="align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                  <select 
                    class="prop-select" 
                    style="flex: 0 0 100px;"
                    value={rule.type}
                    onChange={e => updateRule(idx, { type: (e.target as HTMLSelectElement).value as any })}
                  >
                    <option value="name">Name</option>
                    <option value="tag">Tag</option>
                    <option value="property">Property</option>
                  </select>

                  {rule.type === 'property' && (
                    <input 
                      class="prop-input" 
                      style="flex: 1;"
                      placeholder="Property name" 
                      value={rule.key} 
                      onInput={e => updateRule(idx, { key: (e.target as HTMLInputElement).value })}
                    />
                  )}

                  <input 
                    class="prop-input" 
                    style="flex: 2;"
                    placeholder={rule.type === 'name' ? 'PV name pattern' : 'Value'} 
                    value={rule.value}
                    onInput={e => updateRule(idx, { value: (e.target as HTMLInputElement).value })}
                    onKeyDown={e => e.key === 'Enter' && handleCfsSearch()}
                  />

                  <button 
                    class="icon-btn" 
                    onClick={() => removeRule(idx)}
                    disabled={rules.length === 1}
                  >✕</button>
                </div>
              ))}

              <div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;">
                <button class="panel-btn" onClick={addRule}>+ Add Rule</button>
                <button 
                  class="toolbar-btn toolbar-btn-primary" 
                  onClick={handleCfsSearch} 
                  disabled={searching}
                  style="padding: 0 1.5rem;"
                >
                  {searching ? 'Searching…' : 'Search CFS'}
                </button>
              </div>
            </div>
          ) : (
            <div style="flex: 0 0 auto;">
              <div class="wizard-section-title">Archiver Search</div>
              <p class="hint" style="padding: 0 0 0.5rem 0;">Search for archived PVs using glob patterns (e.g. <code>*TEMP*</code>).</p>
              
              <div class="wizard-field wizard-field-row" style="gap: 0.5rem;">
                <input 
                  class="prop-input" 
                  style="flex: 1;"
                  autoFocus
                  placeholder="PV pattern..." 
                  value={archPattern}
                  onInput={e => setArchPattern((e.target as HTMLInputElement).value)}
                  onKeyDown={e => e.key === 'Enter' && handleArchSearch()}
                />
                <button 
                  class="toolbar-btn toolbar-btn-primary" 
                  onClick={handleArchSearch} 
                  disabled={searching || !archPattern.trim()}
                  style="padding: 0 1.5rem;"
                >
                  {searching ? 'Searching…' : 'Search Archiver'}
                </button>
              </div>
            </div>
          )}

          <div class="wizard-section-title" style="margin-top: 1.5rem; display: flex; justify-content: space-between; align-items: center;">
            <span>Results {resultsCount > 0 && `(${resultsCount})`}</span>
            {resultsCount > 0 && (
              <button class="panel-btn" style="font-size: 0.7rem; padding: 0.1rem 0.4rem;" onClick={handleAddAll}>Add All to Sidebar</button>
            )}
          </div>

          {error && <p class="wizard-error">{error}</p>}

          <div class="panel-list" style="flex: 1; border: 1px solid #2d3748; border-radius: 4px; background: #0f1117; overflow-y: auto;">
            {resultsCount === 0 ? (
              <p class="hint" style="text-align: center; padding: 2rem;">
                {searching ? 'Searching…' : 'No results to show.'}
              </p>
            ) : (
              <ul class="iface-list">
                {source === 'cfs' ? (
                  cfsResults.map(r => (
                    <li key={r.name} class="iface-item" style="cursor: default;">
                      <div style="display: flex; flex-direction: column; gap: 2px;">
                        <span style="font-family: ui-monospace, monospace; color: #e2e8f0;">{r.name}</span>
                        <div style="display: flex; gap: 4px; flex-wrap: wrap;">
                          {r.tags?.map((t: any) => (
                            <span key={t.name} style="font-size: 0.65rem; background: #1e293b; color: #94a3b8; padding: 0 4px; border-radius: 3px; border: 1px solid #334155;">
                              {t.name}
                            </span>
                          ))}
                        </div>
                      </div>
                      <button 
                        class="icon-btn" 
                        title="Add to sidebar"
                        onClick={() => onAddSignals([{ ds: 'epics', name: r.name }])}
                      >+</button>
                    </li>
                  ))
                ) : (
                  archResults.map(name => (
                    <li key={name} class="iface-item" style="cursor: default;">
                      <span style="font-family: ui-monospace, monospace; color: #e2e8f0;">{name}</span>
                      <button 
                        class="icon-btn" 
                        title="Add to sidebar"
                        onClick={() => onAddSignals([{ ds: 'epics', name }])}
                      >+</button>
                    </li>
                  ))
                )}
              </ul>
            )}
          </div>
        </div>

        <div class="wizard-footer">
          <button class="toolbar-btn" onClick={onClose}>Close</button>
        </div>
      </div>
    </div>
  );
}
