"use client";

import { useRef, useEffect } from "react";
import { Group } from "@/lib/api";
import { useTranslation } from "@/lib/i18n";

interface GroupSelectorProps {
  groups: Group[];
  selected: string | null;
  onSelect: (id: string | null) => void;
}

export default function GroupSelector({
  groups,
  selected,
  onSelect,
}: GroupSelectorProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const activeRef = useRef<HTMLButtonElement>(null);
  const { t } = useTranslation();

  // Scroll active button into view
  useEffect(() => {
    if (activeRef.current && scrollRef.current) {
      const container = scrollRef.current;
      const btn = activeRef.current;
      const containerRect = container.getBoundingClientRect();
      const btnRect = btn.getBoundingClientRect();

      if (btnRect.left < containerRect.left || btnRect.right > containerRect.right) {
        btn.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
      }
    }
  }, [selected]);

  return (
    <div
      ref={scrollRef}
      className="flex gap-2 overflow-x-auto scrollbar-hide snap-x snap-mandatory px-4 py-3"
      style={{ WebkitOverflowScrolling: "touch" } as React.CSSProperties}
    >
      <button
        ref={selected === null ? activeRef : undefined}
        onClick={() => onSelect(null)}
        className={`flex-shrink-0 px-4 py-2.5 rounded-full text-sm font-medium transition-all whitespace-nowrap snap-center ${
          selected === null
            ? "bg-gray-800 text-white dark:bg-white dark:text-gray-900 shadow-md scale-105 min-h-[44px]"
            : "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700 min-h-[44px]"
        }`}
      >
        {t("tasks.all")}
      </button>
      {groups.map((g) => (
        <button
          key={g.id}
          ref={selected === g.id ? activeRef : undefined}
          onClick={() => onSelect(g.id)}
          className={`flex-shrink-0 px-4 py-2.5 rounded-full text-sm font-medium transition-all flex items-center gap-1.5 whitespace-nowrap snap-center ${
            selected === g.id
              ? "text-white shadow-md scale-105 min-h-[44px]"
              : "hover:opacity-80 min-h-[44px]"
          }`}
          style={{
            backgroundColor: selected === g.id ? g.color : undefined,
            border: selected !== g.id ? `2px solid ${g.color}` : undefined,
            color: selected !== g.id ? g.color : undefined,
          }}
        >
          {g.icon && <span className="text-lg">{g.icon}</span>}
          <span>{g.name}</span>
        </button>
      ))}
    </div>
  );
}
