"use client";

import { SearchIcon } from "@/assets/icons";
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 { AdminStatus } from "@/constants/enums";
import { getEnumAsArray } from "@/utils/shared";
import { useMemo } from "react";
import {
  FieldValues,
  UseFormHandleSubmit,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";

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

function countActiveAdminFilters(values: Record<string, unknown>): number {
  let n = 0;
  const searchVal = values.search;
  if (typeof searchVal === "string" && searchVal.trim()) n++;
  const statusVal = values.status;
  if (
    statusVal !== undefined &&
    statusVal !== null &&
    statusVal !== "" &&
    String(statusVal).trim()
  ) {
    n++;
  }
  return n;
}

export default function AdminListFilters({
  filterRegister,
  isMutating,
  handleFilterSubmit,
  search,
  watch,
  setValue,
  onClearAll,
}: AdminListFiltersProps) {
  const watched = watch();
  const activeCount = useMemo(
    () => countActiveAdminFilters(watched as Record<string, unknown>),
    [watched],
  );

  return (
    <InlineListFiltersPanel
      title="Filter admins"
      activeFilterCount={activeCount}
      expandAriaLabel="Expand admin filters"
      collapseAriaLabel="Collapse admin filters"
      panelToggleDataCy="admins-filter-panel-toggle"
    >
      <form
        className="space-y-5 px-4 pb-6 pt-1 sm:px-6"
        onSubmit={handleFilterSubmit(search)}
        data-cy="admins-filter-form"
      >
        <div className="flex flex-col gap-3 lg:flex-row lg:items-end">
          <div className="min-h-[52px] flex-1">
            <InputGroup
              {...filterRegister("search")}
              name="search"
              label="Keyword search"
              type="search"
              placeholder="Name, email, username…"
              icon={
                <SearchIcon className="text-primary dark:text-primary/90" />
              }
              iconPosition="left"
              dataCy="admins-filter-search-input"
              className="[&_input]:rounded-2xl [&_input]:border-stroke/70 [&_input]:bg-white/90 [&_input]:py-3.5 [&_input]:text-sm dark:[&_input]:border-dark-3 dark:[&_input]:bg-dark-2/80"
            />
          </div>
          <div className="flex shrink-0 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="admins-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="admins-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>
        </div>

        <div className="max-w-xl">
          <Select<FieldValues>
            {...filterRegister("status")}
            items={getEnumAsArray(AdminStatus)}
            label="Status"
            name="status"
            placeholder="Any status"
            clearable
            value={watch("status")}
            onClear={() => setValue("status", undefined)}
            dataCy="admins-filter-status-select"
          />
        </div>
      </form>
    </InlineListFiltersPanel>
  );
}
