import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { getAllCategoriesWithCounts } from "../../services/categoryService";

interface CategoryOption {
  id: number;
  name: string;
  color: string | null;
  parent_id: number | null;
}

export interface CategoryZoomHeaderProps {
  categoryId: number | null;
  includeSubcategories: boolean;
  onCategoryChange: (id: number | null) => void;
  onIncludeSubcategoriesChange: (flag: boolean) => void;
}

export default function CategoryZoomHeader({
  categoryId,
  includeSubcategories,
  onCategoryChange,
  onIncludeSubcategoriesChange,
}: CategoryZoomHeaderProps) {
  const { t } = useTranslation();
  const [categories, setCategories] = useState<CategoryOption[]>([]);

  useEffect(() => {
    getAllCategoriesWithCounts()
      .then((rows) =>
        setCategories(
          rows.map((r) => ({ id: r.id, name: r.name, color: r.color, parent_id: r.parent_id })),
        ),
      )
      .catch(() => setCategories([]));
  }, []);

  return (
    <div className="flex flex-col sm:flex-row sm:items-center gap-3 bg-[var(--card)] border border-[var(--border)] rounded-xl p-4">
      <label className="flex flex-col gap-1 flex-1 min-w-0">
        <span className="text-xs font-medium text-[var(--muted-foreground)] uppercase tracking-wide">
          {t("reports.category.selectCategory")}
        </span>
        <select
          value={categoryId ?? ""}
          onChange={(e) => onCategoryChange(e.target.value ? Number(e.target.value) : null)}
          className="bg-[var(--card)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm"
        >
          <option value="">—</option>
          {categories.map((cat) => (
            <option key={cat.id} value={cat.id}>
              {cat.name}
            </option>
          ))}
        </select>
      </label>
      <label className="inline-flex items-center gap-2 text-sm">
        <input
          type="checkbox"
          checked={includeSubcategories}
          onChange={(e) => onIncludeSubcategoriesChange(e.target.checked)}
          className="accent-[var(--primary)]"
        />
        <span>
          {includeSubcategories
            ? t("reports.category.includeSubcategories")
            : t("reports.category.directOnly")}
        </span>
      </label>
    </div>
  );
}
