import React, { useRef, useEffect } from 'react';
import type { UnknownPlimiPlugin } from '../../core/plugins/plugin-types';
import { CategoryIcon } from '../ui/CategoryIcon';

export function PlimiSearch({
  value,
  onChange,
  count,
  total,
  onArrow,
  onEnter,
}: {
  value: string;
  onChange: (val: string) => void;
  count: number;
  total: number;
  onArrow?: (dir: number) => void;
  onEnter?: () => void;
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const shortcutText =
    typeof window !== "undefined" &&
    /Mac|iPod|iPhone|iPad/.test(navigator.userAgent || navigator.platform || "")
      ? "⌘ K"
      : "Ctrl K";

  useEffect(() => {
    const handleGlobalKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        inputRef.current?.focus();
        inputRef.current?.select();
      }
    };

    window.addEventListener('keydown', handleGlobalKeyDown);
    return () => {
      window.removeEventListener('keydown', handleGlobalKeyDown);
    };
  }, []);

  return (
    <div className="w-full">
      <div
        className="relative bg-[var(--p-surface)] border-[1.5px] border-[var(--p-border)] rounded-[18px] md:rounded-[20px] px-4 py-4 md:px-[22px] md:py-[20px] flex items-center gap-3 md:gap-[14px] transition-colors cursor-text"
        style={{
          boxShadow: '0 1px 0 0 var(--p-shadow-inset), 0 12px 30px -22px var(--p-shadow-soft)',
        }}
        onClick={() => inputRef.current?.focus()}
      >
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="var(--p-muted)"
          strokeWidth="2"
          strokeLinecap="round"
          className="shrink-0 w-6 h-6 md:w-7 md:h-7"
        >
          <circle cx="11" cy="11" r="7" />
          <path d="m20 20-3.5-3.5" />
        </svg>
        <input
          ref={inputRef}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
              e.preventDefault();
              onArrow?.(e.key === 'ArrowDown' ? 1 : -1);
            }
            if (e.key === 'Enter') {
              e.preventDefault();
              onEnter?.();
            }
            if (e.key === 'Escape') {
              onChange('');
            }
          }}
          placeholder="Search tools…"
          spellCheck={false}
          className="flex-1 min-w-0 border-none outline-none bg-transparent text-[var(--p-text)] text-lg md:text-2xl font-sans tracking-tight font-medium"
        />
        <span className="shrink-0 inline-flex items-center gap-1.5 font-mono text-xs text-[var(--p-muted)]">
          {value ? (
            <button
              onClick={(e) => {
                e.stopPropagation();
                onChange('');
              }}
              className="px-2 py-1 rounded-lg bg-[var(--p-chip)] text-[var(--p-muted)] cursor-pointer"
            >
              clear
            </button>
          ) : (
            <kbd className="hidden sm:inline-flex px-2 py-1.5 rounded-md bg-[var(--p-chip)] border border-[var(--p-border)] text-[var(--p-muted)]">
              {shortcutText}
            </kbd>
          )}
        </span>
      </div>
      <div className="mt-2.5 flex justify-between font-mono text-[11px] text-[var(--p-muted)] tracking-wider uppercase">
        <span>{value ? `${count} match${count === 1 ? '' : 'es'}` : `${total} tools`}</span>
        <span className="hidden sm:inline">↑↓ to browse · enter to open</span>
      </div>
    </div>
  );
}

export function CategoryChips({
  active,
  onPick,
  counts,
  categories,
}: {
  active: string;
  onPick: (cat: string) => void;
  counts: Record<string, number>;
  categories: { id: string; label: string }[];
}) {
  return (
    <div className="flex gap-2 overflow-x-auto no-scrollbar snap-x -mx-6 px-6 md:mx-0 md:px-0 md:flex-wrap md:overflow-visible">
      {categories.map((c) => {
        const on = active === c.id;
        return (
          <button
            key={c.id}
            onClick={() => onPick(c.id)}
            className={`shrink-0 snap-start cursor-pointer px-3.5 py-2 rounded-full font-sans text-[13px] font-medium tracking-tight inline-flex items-center gap-2 transition-all ${
              on
                ? 'bg-[var(--p-accent)] text-[var(--p-accent-ink)] border-[var(--p-accent)]'
                : 'bg-[var(--p-surface)] text-[var(--p-text)] border-[var(--p-border)]'
            } border`}
          >
            {c.label}
            <span
              className={`font-mono text-[11px] ${
                on ? 'opacity-70' : 'opacity-55'
              }`}
            >
              {counts[c.id] || 0}
            </span>
          </button>
        );
      })}
    </div>
  );
}

function tilt(id: string, range = 1.5) {
  let h = 0;
  for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) | 0;
  const x = (Math.abs(h) % 1000) / 1000;
  return (x - 0.5) * 2 * range;
}

const TINTS: Record<string, { paper: string; ink: string; neon: string }> = {
  image: { paper: '#E8F5E9', ink: '#2E7D32', neon: '#69F0AE' },
  pdf: { paper: '#FFEBEE', ink: '#C62828', neon: '#FF5252' },
  developer: { paper: '#E3F2FD', ink: '#1565C0', neon: '#448AFF' },
  text: { paper: '#FFF8E1', ink: '#F57F17', neon: '#FFD740' },
  crypto: { paper: '#F3E5F5', ink: '#6A1B9A', neon: '#E040FB' },
  privacy: { paper: '#E0F2F1', ink: '#00695C', neon: '#64FFDA' },
};

export function ToolTile({
  plugin,
  focused,
  onClick,
  dark,
  index = 0,
}: {
  plugin: UnknownPlimiPlugin;
  focused: boolean;
  onClick: (plugin: UnknownPlimiPlugin) => void;
  dark: boolean;
  index?: number;
}) {
  const [hover, setHover] = React.useState(false);
  const tints = TINTS[plugin.manifest.category] || TINTS.developer;
  const t = tilt(plugin.manifest.id, 1.5);
  const lifted = hover || focused;

  const iconColor = dark ? tints.neon : tints.ink;

  const bg = 'var(--p-surface)';
  const stickerEdge = dark
    ? `color-mix(in oklab, ${tints.neon} 22%, var(--p-border))`
    : `color-mix(in oklab, ${tints.ink} 18%, var(--p-border))`;

  return (
    <div
      className="animate-plimi-rise h-full"
      style={{ animationDelay: `${Math.min(index, 12) * 34}ms` }}
    >
    <button
      onClick={() => onClick(plugin)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      className="relative flex h-full w-full flex-col gap-3.5 px-[18px] py-[20px] rounded-[18px] text-left overflow-hidden cursor-pointer"
      style={{
        background: bg,
        border: `1.5px solid ${lifted ? stickerEdge : 'var(--p-border)'}`,
        boxShadow: lifted
          ? '0 18px 38px -22px var(--p-shadow-soft), 0 1px 0 0 var(--p-shadow-inset)'
          : '0 6px 18px -16px var(--p-shadow-soft), 0 1px 0 0 var(--p-shadow-inset)',
        transform: `rotate(${lifted ? 0 : t}deg) translateY(${lifted ? -2 : 0}px)`,
        transition: 'transform .18s cubic-bezier(.2,.8,.2,1), box-shadow .18s, border-color .18s',
        minHeight: 158,
      }}
    >
      <span
        style={{
          position: 'absolute',
          top: -10,
          right: 18,
          width: 26,
          height: 18,
          borderRadius: '0 0 6px 6px',
          background: dark ? tints.neon : tints.paper,
          opacity: dark ? 0.5 : 1,
          transform: `rotate(${t * 1.5}deg)`,
          boxShadow: '0 2px 6px -2px var(--p-shadow-soft)',
        }}
      />
      <div
        className="inline-flex items-center justify-center w-[52px] h-[52px] rounded-[14px]"
        style={{
          background: dark
            ? `color-mix(in oklab, ${tints.neon} 8%, transparent)`
            : tints.paper,
          border: dark ? `1px solid color-mix(in oklab, ${tints.neon} 20%, transparent)` : 'none',
        }}
      >
        <CategoryIcon category={plugin.manifest.category} color={iconColor} size={24} strokeWidth={2} />
      </div>

      <div className="flex flex-col gap-1">
        <div className="font-sans font-semibold text-base tracking-tight text-[var(--p-text)]">
          {plugin.manifest.name}
        </div>
        <div className="font-sans font-normal text-[13px] text-[var(--p-muted)] leading-snug text-balance">
          {plugin.manifest.description}
        </div>
      </div>
    </button>
    </div>
  );
}

export function SectionHeader({ catLabel, catId, n }: { catLabel: string; catId: string; n: number }) {
  const tints = TINTS[catId] || TINTS.developer;
  
  return (
    <div className="flex items-baseline justify-between pb-1.5">
      <div className="inline-flex items-baseline gap-2.5 font-mono text-xs text-[var(--p-muted)] tracking-wider uppercase">
        <span
          className="inline-block w-2.5 h-2.5 rounded-sm transform translate-y-px -rotate-6"
          style={{
            background: tints.paper,
            border: `1.5px solid color-mix(in oklab, ${tints.ink} 40%, transparent)`,
          }}
        />
        <span>{catLabel}</span>
        <span className="opacity-50">{String(n).padStart(2, '0')}</span>
      </div>
    </div>
  );
}
