"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 { AdminRoles, CustomerStatus, CustomerType } from "@/constants/enums";
import { ILabelValue } from "@/types/shared";
import { getEnumAsArray } from "@/utils/shared";
import {
  FieldValues,
  UseFormHandleSubmit,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import { useMemo } from "react";

interface CustomerListFiltersProps {
  filterRegister: UseFormRegister<FieldValues>;
  isMutating: number;
  handleFilterSubmit: UseFormHandleSubmit<FieldValues>;
  search: (data: any) => void;
  watch: UseFormWatch<FieldValues>;
  setValue: UseFormSetValue<any>;
  onClearAll: () => void;
  /** Lazy-loaded company options for the company dropdown. */
  companyItems: ILabelValue[];
  onCompanySearch: (query: string) => void;
  onCompanyLoadMore: () => void;
  companyHasMore?: boolean;
  companyIsLoading: boolean;
  companyIsLoadingMore: boolean;
}

function countActive(values: Record<string, unknown>): number {
  let n = 0;
  for (const key of [
    "status",
    "role",
    "type",
    "full_name",
    "email",
    "company_id",
  ] as const) {
    const v = values[key];
    if (v !== undefined && v !== null && v !== "" && String(v).trim()) n++;
  }
  return n;
}

const CustomerListFilters = ({
  filterRegister,
  isMutating,
  handleFilterSubmit,
  search,
  watch,
  setValue,
  onClearAll,
  companyItems,
  onCompanySearch,
  onCompanyLoadMore,
  companyHasMore,
  companyIsLoading,
  companyIsLoadingMore,
}: CustomerListFiltersProps) => {
  const watched = watch();
  const activeCount = useMemo(
    () => countActive(watched as Record<string, unknown>),
    [watched],
  );

  return (
    <InlineListFiltersPanel
      title="Filter customers"
      description="Slice by status, role, or account type — inline, no popup."
      activeFilterCount={activeCount}
      expandAriaLabel="Expand customer filters"
      collapseAriaLabel="Collapse customer filters"
      panelToggleDataCy="customers-filter-panel-toggle"
    >
      <form
        className="space-y-5 px-4 pb-6 pt-1 sm:px-6"
        onSubmit={handleFilterSubmit(search)}
        data-cy="customers-filter-form"
      >
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          <InputGroup
            {...filterRegister("full_name")}
            name="full_name"
            label="Full name"
            type="text"
            placeholder="Search by full name"
          />
          <InputGroup
            {...filterRegister("email")}
            name="email"
            label="Email"
            type="text"
            placeholder="Search by email"
          />
          <Select
            {...filterRegister("company_id")}
            items={companyItems}
            label="Company"
            name="company_id"
            placeholder="Select company"
            clearable
            value={watch("company_id")}
            onClear={() => setValue("company_id", undefined)}
            searchPlaceholder="Search companies…"
            onSearch={onCompanySearch}
            onLoadMore={onCompanyLoadMore}
            hasMore={companyHasMore}
            isLoading={companyIsLoading}
            isLoadingMore={companyIsLoadingMore}
          />
          <Select
            {...filterRegister("status")}
            items={getEnumAsArray(CustomerStatus)}
            label="Status"
            name="status"
            placeholder="Status"
            clearable
            value={watch("status")}
            onClear={() => setValue("status", undefined)}
          />
          <Select
            {...filterRegister("role")}
            items={getEnumAsArray(AdminRoles)}
            label="Role"
            name="role"
            placeholder="Role"
            clearable
            value={watch("role")}
            onClear={() => setValue("role", undefined)}
          />
          <Select
            {...filterRegister("type")}
            items={getEnumAsArray(CustomerType)}
            label="Type"
            name="type"
            placeholder="Type"
            clearable
            value={watch("type")}
            onClear={() => setValue("type", undefined)}
          />
        </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="customers-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="customers-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 CustomerListFilters;
