import { Link, useSearchParams } from 'react-router';
import { Puzzle, AlertTriangle } from 'lucide-react';
import { usePlugins, type PluginItem } from './usePlugins';

// The left panel: every plugin in the tree, installed or not.
//
// Rows are real `<Link>`s carrying `?selected=`, not buttons with the name in a closure — so cmd-click,
// middle-click and "copy link" all work, and the detail panel reads the URL rather than being told.
// See docs/navigation-audit.md on the opaque-click anti-pattern.

const Status = ({ plugin }: { plugin: PluginItem }) => {
  if (!plugin.installed) return <span className="text-xs text-duck-dark/40">not installed</span>;
  if (!plugin.enabled) return <span className="text-xs text-amber-600">disabled</span>;
  if (plugin.outdated) return <span className="text-xs text-amber-600">update available</span>;
  return <span className="text-xs text-emerald-600">enabled</span>;
};

export const PluginsList = () => {
  const { plugins, broken, isLoading } = usePlugins();
  const [params] = useSearchParams();
  const selected = params.get('selected');

  if (isLoading) return <div className="p-4 text-sm text-duck-dark/50">Loading…</div>;

  return (
    <div className="h-full overflow-auto">
      {plugins.length === 0 && broken.length === 0 ? (
        <div className="p-4 text-sm text-duck-dark/50">
          No plugins in <code>plugins/</code> yet.
        </div>
      ) : null}

      {plugins.map((plugin) => (
        <Link
          key={plugin.appName}
          to={`/plugins?selected=${encodeURIComponent(plugin.appName)}`}
          className={`flex items-center gap-3 px-3 py-2.5 border-b border-duck-dark/5 transition-colors ${
            selected === plugin.appName ? 'bg-duck-teal/10' : 'hover:bg-duck-dark/5'
          }`}
        >
          <Puzzle className="h-4 w-4 shrink-0" style={{ color: plugin.color }} />
          <div className="min-w-0 flex-1">
            <div className="truncate text-sm font-medium text-duck-dark">{plugin.label}</div>
            <div className="truncate text-xs text-duck-dark/50">{plugin.prefix}</div>
          </div>
          <Status plugin={plugin} />
        </Link>
      ))}

      {/* A directory that could not be read is shown rather than swallowed — otherwise a malformed
          manifest looks exactly like a plugin nobody wrote. */}
      {broken.map((b) => (
        <div key={b.appName} className="flex items-start gap-3 px-3 py-2.5 border-b border-duck-dark/5">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-red-500" />
          <div className="min-w-0">
            <div className="truncate text-sm font-medium text-duck-dark">{b.appName}</div>
            <div className="text-xs text-red-600">{b.error}</div>
          </div>
        </div>
      ))}
    </div>
  );
};
