'use client';

import * as React from 'react';
import { X, Search, Check } from 'lucide-react';
import { ToolIcon } from '@/app/components/ui/tool-icons';

// One status pill per tool, in priority order. Setup wins because the tool is
// unusable until it's configured — risk pills are irrelevant in that state.
function getStatusPill(tool) {
  if (!tool.available) {
    return {
      label: 'Setup',
      tone: 'soft',
      hint: tool.missing_env?.length
        ? `Needs ${tool.missing_env.join(', ')}`
        : 'Needs setup before this agent can use it',
    };
  }
  if (tool.risk_level === 'irreversible_external') {
    return { label: 'Permanent', tone: 'danger', hint: 'This action cannot be undone' };
  }
  if (tool.risk_level === 'high') {
    return { label: 'Approval', tone: 'warn', hint: 'Asks before running' };
  }
  return null;
}

const CATEGORY_ORDER = [
  'github',
  'supabase',
  'vercel',
  'email',
  'gmail',
  'web',
  'local_machine',
  'core',
];

const CATEGORY_LABELS = {
  github: 'GitHub',
  supabase: 'Supabase',
  vercel: 'Vercel',
  email: 'Email',
  gmail: 'Gmail',
  web: 'Web',
  local_machine: 'Local machine',
  core: 'Core',
};

function normalize(value) {
  return String(value || '').toLowerCase().trim();
}

export default function ToolPicker({ tools, name = 'tools', defaultSelected = [] }) {
  const [selected, setSelected] = React.useState(() => new Set(defaultSelected));
  const [query, setQuery] = React.useState('');
  const searchRef = React.useRef(null);

  const byName = React.useMemo(() => {
    const map = new Map();
    for (const t of tools) map.set(t.name, t);
    return map;
  }, [tools]);

  const grouped = React.useMemo(() => {
    const q = normalize(query);
    const groups = new Map();
    for (const tool of tools) {
      if (q) {
        const hay = `${tool.name} ${tool.title} ${tool.category} ${tool.description}`.toLowerCase();
        if (!hay.includes(q)) continue;
      }
      const key = tool.category || 'core';
      if (!groups.has(key)) groups.set(key, []);
      groups.get(key).push(tool);
    }
    const ordered = [];
    for (const cat of CATEGORY_ORDER) {
      if (groups.has(cat)) ordered.push([cat, groups.get(cat)]);
    }
    for (const [cat, items] of groups) {
      if (!CATEGORY_ORDER.includes(cat)) ordered.push([cat, items]);
    }
    return ordered;
  }, [tools, query]);

  const matchCount = React.useMemo(
    () => grouped.reduce((sum, [, items]) => sum + items.length, 0),
    [grouped],
  );

  const toggle = React.useCallback((toolName) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(toolName)) next.delete(toolName);
      else next.add(toolName);
      return next;
    });
  }, []);

  const remove = React.useCallback((toolName) => {
    setSelected((prev) => {
      const next = new Set(prev);
      next.delete(toolName);
      return next;
    });
  }, []);

  const clear = React.useCallback(() => setSelected(new Set()), []);

  const hiddenValue = React.useMemo(() => Array.from(selected).join(','), [selected]);

  const selectedTools = React.useMemo(
    () => Array.from(selected).map((n) => byName.get(n)).filter(Boolean),
    [selected, byName],
  );

  return (
    <div className="tool-picker">
      <input type="hidden" name={name} value={hiddenValue} />

      <div className="tool-picker-chip-row" aria-live="polite">
        {selectedTools.length === 0 ? (
          <span className="tool-picker-chip-empty">No tools selected — pick from the list below.</span>
        ) : (
          <>
            {selectedTools.map((tool) => (
              <span key={tool.name} className="tool-picker-chip">
                <ToolIcon category={tool.category} size={12} />
                <span className="tool-picker-chip-title">{tool.title}</span>
                <button
                  type="button"
                  className="tool-picker-chip-x"
                  onClick={() => remove(tool.name)}
                  aria-label={`Remove ${tool.title}`}
                >
                  <X size={11} />
                </button>
              </span>
            ))}
            <button type="button" className="tool-picker-clear" onClick={clear}>
              Clear all
            </button>
          </>
        )}
      </div>

      <div className="tool-picker-search">
        <Search size={13} aria-hidden />
        <input
          ref={searchRef}
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search tools…"
          aria-label="Search tools"
        />
        {query ? (
          <button type="button" className="tool-picker-search-clear" onClick={() => setQuery('')} aria-label="Clear search">
            <X size={12} />
          </button>
        ) : null}
      </div>

      <div className="tool-picker-list" role="listbox" aria-multiselectable="true">
        {matchCount === 0 ? (
          <div className="tool-picker-empty">No tools match “{query}”.</div>
        ) : (
          grouped.map(([category, items]) => (
            <div key={category} className="tool-picker-group">
              <div className="tool-picker-group-head">
                <ToolIcon category={category} size={12} />
                <span>{CATEGORY_LABELS[category] || category}</span>
                <small>{items.length}</small>
              </div>
              <ul className="tool-picker-options">
                {items.map((tool) => {
                  const isSelected = selected.has(tool.name);
                  const pill = getStatusPill(tool);
                  return (
                    <li key={tool.name}>
                      <button
                        type="button"
                        role="option"
                        aria-selected={isSelected}
                        className={`tool-picker-option ${isSelected ? 'on' : ''}`}
                        onClick={() => toggle(tool.name)}
                        title={tool.description}
                      >
                        <span className="tool-picker-option-icon">
                          <ToolIcon category={tool.category} size={14} />
                        </span>
                        <span className="tool-picker-option-body">
                          <span className="tool-picker-option-title">{tool.title}</span>
                          <span className="tool-picker-option-name">{tool.name}</span>
                        </span>
                        {pill ? (
                          <span className={`tool-picker-pill ${pill.tone}`} title={pill.hint}>
                            {pill.label}
                          </span>
                        ) : null}
                        <span className={`tool-picker-check ${isSelected ? 'on' : ''}`} aria-hidden>
                          {isSelected ? <Check size={12} strokeWidth={2.5} /> : null}
                        </span>
                      </button>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))
        )}
      </div>

      <div className="tool-picker-foot">
        <span>
          <b>{selected.size}</b> selected · {tools.length} available
        </span>
      </div>
    </div>
  );
}
