"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 { Currencies } from "@/constants/enums";
import { useMemo } from "react";
import {
  FieldValues,
  UseFormHandleSubmit,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";

interface CompanyListFiltersProps {
  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 keys = ["name", "email", "phone"] as const;
  for (const k of keys) {
    const v = values[k];
    if (typeof v === "string" && v.trim()) n++;
  }
  const cur = values.currency;
  if (cur !== undefined && cur !== null && cur !== "" && String(cur).trim()) {
    n++;
  }
  const ec = values.employee_count;
  if (ec !== undefined && ec !== null && ec !== "" && String(ec).trim()) {
    n++;
  }
  return n;
}

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

  return (
    <InlineListFiltersPanel
      title="Filter companies"
      activeFilterCount={activeCount}
      expandAriaLabel="Expand company filters"
      collapseAriaLabel="Collapse company filters"
      panelToggleDataCy="companies-filter-panel-toggle"
    >
      <form
        className="space-y-5 px-4 pb-6 pt-1 sm:px-6"
        onSubmit={handleFilterSubmit(search)}
        data-cy="companies-filter-form"
      >
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          <InputGroup
            {...filterRegister("name")}
            name="name"
            label="Name"
            placeholder="Name"
            type="text"
          />
          <InputGroup
            {...filterRegister("email")}
            name="email"
            label="Email"
            placeholder="Email"
            type="email"
          />
          <InputGroup
            {...filterRegister("phone")}
            name="phone"
            label="Phone"
            placeholder="Phone"
            type="tel"
          />
          <Select
            {...filterRegister("currency")}
            items={Currencies}
            label="Currency"
            name="currency"
            placeholder="Currency"
            clearable
            value={watch("currency")}
            onClear={() => setValue("currency", undefined)}
          />
          <InputGroup
            {...filterRegister("employee_count")}
            name="employee_count"
            label="Employee count"
            placeholder="Employee count"
            type="number"
          />
        </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="companies-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="companies-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 CompanyListFilters;
