"use client";

import InputGroup from "@/components/FormElements/InputGroup";
import { Select } from "@/components/FormElements/select";
import { Button } from "@/components/ui-elements/button";
import InlineListFiltersPanel from "@/components/ui/InlineListFiltersPanel";
import {
  FieldValues,
  UseFormHandleSubmit,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import { useMemo } from "react";

interface CompanyCategoryListFiltersProps {
  filterRegister: UseFormRegister<FieldValues>;
  isMutating: number;
  handleFilterSubmit: UseFormHandleSubmit<FieldValues>;
  search: (data: any) => void;
  watch: UseFormWatch<FieldValues>;
  setValue: UseFormSetValue<any>;
  onClearAll: () => void;
}

function countActive(values: Record<string, unknown>): number {
  let n = 0;
  const q = values.q;
  if (typeof q === "string" && q.trim()) n++;
  const pub = values.published;
  if (pub !== undefined && pub !== null && pub !== "" && String(pub).trim()) {
    n++;
  }
  return n;
}

const CompanyCategoryListFilters = ({
  filterRegister,
  isMutating,
  handleFilterSubmit,
  search,
  watch,
  setValue,
  onClearAll,
}: CompanyCategoryListFiltersProps) => {
  const watched = watch();
  const activeCount = useMemo(
    () => countActive(watched as Record<string, unknown>),
    [watched],
  );

  return (
    <InlineListFiltersPanel
      title="Filter categories"
      description="Keyword search and published state — inline, no popup."
      activeFilterCount={activeCount}
      expandAriaLabel="Expand category filters"
      collapseAriaLabel="Collapse category filters"
      panelToggleDataCy="company-categories-filter-panel-toggle"
    >
      <form
        className="space-y-5 px-4 pb-6 pt-1 sm:px-6"
        data-cy="company-categories-filter-form"
        onSubmit={handleFilterSubmit(search)}
      >
        <div className="grid gap-4 sm:grid-cols-2">
          <InputGroup
            {...filterRegister("q")}
            name="q"
            label="Keyword search"
            placeholder="Search"
            type="search"
            dataCy="company-categories-filter-search-input"
          />
          <Select
            {...filterRegister("published")}
            items={[
              { label: "Published", value: "true" },
              { label: "Not Published", value: "false" },
            ]}
            label="Published"
            name="published"
            placeholder="Published status"
            clearable
            value={watch("published")}
            onClear={() => setValue("published", undefined)}
            dataCy="company-categories-filter-published-select"
          />
        </div>
        <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
          <Button
            type="submit"
            size="small"
            className="min-h-[52px] min-w-[140px] rounded-2xl bg-gradient-to-r from-primary via-primary to-violet-600 px-8 text-sm font-semibold transition hover:opacity-[0.97]"
            data-cy="company-categories-filter-submit-button"
            label={
              isMutating ? (
                <span className="inline-flex h-5 w-5 animate-spin rounded-full border-2 border-white/30 border-t-white" />
              ) : (
                <span>Apply filters</span>
              )
            }
          />
          <button
            type="button"
            data-cy="company-categories-filter-reset-button"
            onClick={onClearAll}
            className="min-h-[52px] rounded-2xl border border-stroke/70 bg-white/80 px-6 text-sm font-semibold text-dark transition hover:border-primary/40 hover:text-primary dark:border-dark-3 dark:bg-dark-3/60 dark:text-white dark:hover:bg-white/[0.06]"
          >
            Reset all
          </button>
        </div>
      </form>
    </InlineListFiltersPanel>
  );
};

export default CompanyCategoryListFilters;
