import { useEffect, useRef, useState } from 'react';
import { COLUMN_LIST, COLUMN_LABELS, SortMode, StatusColumn } from '../../lib/urlState';

interface FilterBarProps {
  selectedStatus: 'all' | StatusColumn;
  sortMode: SortMode;
  searchQuery: string;
  counts: Record<string, number>;
  totalCount: number;
  onStatusChange: (status: 'all' | StatusColumn) => void;
  onSortChange: (sort: SortMode) => void;
  onSearchChange: (q: string) => void;
}

const SORT_OPTIONS: Array<{ value: SortMode; label: string }> = [
  { value: 'updated', label: '新しい順' },
  { value: 'status', label: 'ステータス順' },
  { value: 'title', label: 'タイトル順' },
];

function SortMenu({
  sortMode,
  onSortChange,
}: {
  sortMode: SortMode;
  onSortChange: (sort: SortMode) => void;
}) {
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const triggerRef = useRef<HTMLButtonElement | null>(null);

  useEffect(() => {
    if (!open) return;
    const handleMouseDown = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setOpen(false);
        triggerRef.current?.focus();
      }
    };
    document.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('mousedown', handleMouseDown);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [open]);

  const current = SORT_OPTIONS.find(o => o.value === sortMode) ?? SORT_OPTIONS[0];

  const handleSelect = (value: SortMode) => {
    onSortChange(value);
    setOpen(false);
    triggerRef.current?.focus();
  };

  return (
    <div ref={containerRef} className="relative flex-shrink-0">
      <button
        ref={triggerRef}
        type="button"
        onClick={() => setOpen(v => !v)}
        title={`並び順: ${current.label}`}
        aria-haspopup="true"
        aria-expanded={open}
        aria-label={`並び順: ${current.label}`}
        className={`inline-flex items-center justify-center w-7 h-7 rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-ring ${
          open ? 'bg-accent-soft text-accent' : 'text-slate-500 hover:bg-surface-2'
        }`}
      >
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth={2}
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M3 6h13M3 12h9M3 18h5M17 8V4m0 0l-3 3m3-3l3 3" />
        </svg>
      </button>
      {open && (
        <div className="absolute right-0 top-[calc(100%+6px)] z-10 bg-white border border-hairline rounded-md shadow min-w-[160px] p-1">
          {SORT_OPTIONS.map(o => {
            const selected = sortMode === o.value;
            return (
              <button
                key={o.value}
                type="button"
                onClick={() => handleSelect(o.value)}
                className={`flex items-center justify-between w-full px-2.5 py-1.5 rounded text-xs text-left transition-colors ${
                  selected
                    ? 'bg-accent-soft text-accent font-semibold'
                    : 'text-slate-700 font-medium hover:bg-surface-2'
                }`}
              >
                {o.label}
                {selected && (
                  <svg
                    width="14"
                    height="14"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth={2.5}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    aria-hidden="true"
                  >
                    <path d="M5 13l4 4L19 7" />
                  </svg>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

export function FilterBar({
  selectedStatus,
  sortMode,
  searchQuery,
  counts,
  totalCount,
  onStatusChange,
  onSortChange,
  onSearchChange,
}: FilterBarProps) {
  return (
    <div className="flex flex-col gap-2 pb-3 border-b border-hairline">
      <div className="flex items-center gap-1.5 bg-white border border-hairline rounded-md pl-2.5 pr-1 h-8">
        <svg aria-hidden="true" className="w-3.5 h-3.5 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        <input
          aria-label="検索"
          value={searchQuery}
          onChange={e => onSearchChange(e.target.value)}
          placeholder="検索..."
          className="flex-1 bg-transparent border-0 outline-none text-[13px] text-slate-900 placeholder:text-slate-400 min-w-0"
        />
        <div aria-hidden="true" className="w-px h-4 bg-hairline flex-shrink-0" />
        <SortMenu sortMode={sortMode} onSortChange={onSortChange} />
      </div>

      <div role="tablist" aria-label="ステータスフィルター" className="flex gap-1 overflow-x-auto pb-1 scrollbar-none">
        <button
          role="tab"
          aria-selected={selectedStatus === 'all'}
          onClick={() => onStatusChange('all')}
          className={`flex-shrink-0 px-2 h-7 rounded text-2xs font-medium border transition-colors whitespace-nowrap focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-ring ${
            selectedStatus === 'all'
              ? 'border-accent/60 bg-accent-soft text-accent font-semibold'
              : 'border-hairline bg-white text-slate-600 hover:bg-surface'
          }`}
        >
          すべて <span className="text-slate-400 ml-0.5 font-mono tabular-nums">{totalCount}</span>
        </button>
        {COLUMN_LIST.map(status => (
          <button
            key={status}
            role="tab"
            aria-selected={selectedStatus === status}
            onClick={() => onStatusChange(status)}
            className={`flex-shrink-0 px-2 h-7 rounded text-2xs font-medium border transition-colors whitespace-nowrap focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-ring ${
              selectedStatus === status
                ? 'border-accent/60 bg-accent-soft text-accent font-semibold'
                : 'border-hairline bg-white text-slate-600 hover:bg-surface'
            }`}
          >
            {COLUMN_LABELS[status]} <span className="text-slate-400 ml-0.5 font-mono tabular-nums">{counts[status] ?? 0}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
