"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 { useUser } from "@/contexts";
import { apiDefaultParams } from "@/constants/Api_Params";
import { userService } from "@/lib/api/services/user-services";
import { ILabelValue } from "@/types/shared";
import {
  FieldValues,
  UseFormHandleSubmit,
  UseFormRegister,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import { useMemo } from "react";

interface NotificationHistoryListFiltersProps {
  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 seen = values.seen;
  if (
    seen !== undefined &&
    seen !== null &&
    seen !== "" &&
    String(seen).trim()
  ) {
    n++;
  }
  const userId = values.user_id;
  if (
    userId !== undefined &&
    userId !== null &&
    userId !== "" &&
    String(userId).trim()
  ) {
    n++;
  }
  const searchVal = values.search;
  if (typeof searchVal === "string" && searchVal.trim()) n++;
  return n;
}

const searchUsers = async (query: string): Promise<ILabelValue[]> => {
  const response = await userService.adminsList({
    ...apiDefaultParams,
    search: query,
    offset: 0,
    limit: 20,
  });

  return (response.data?.users ?? []).map((user) => ({
    value: user.id,
    label:
      user.full_name ||
      user.username ||
      user.email ||
      user.id,
  }));
};

const NotificationHistoryListFilters = ({
  filterRegister,
  isMutating,
  handleFilterSubmit,
  search,
  watch,
  setValue,
  onClearAll,
}: NotificationHistoryListFiltersProps) => {
  const { user } = useUser();
  const watched = watch();
  const currentUserOption = useMemo<ILabelValue[]>(() => {
    if (!user?.id) return [];

    return [
      {
        value: user.id,
        label:
          user.full_name ||
          user.username ||
          user.email ||
          user.id,
      },
    ];
  }, [user?.email, user?.full_name, user?.id, user?.username]);
  const activeCount = useMemo(
    () => countActive(watched as Record<string, unknown>),
    [watched],
  );

  return (
    <InlineListFiltersPanel
      title="Filter notifications"
      description="Seen state and message search — inline, no popup."
      activeFilterCount={activeCount}
      expandAriaLabel="Expand notification filters"
      collapseAriaLabel="Collapse notification filters"
      panelToggleDataCy="notification-history-filter-panel-toggle"
    >
      <form
        className="space-y-5 px-4 pb-6 pt-1 sm:px-6"
        onSubmit={handleFilterSubmit(search)}
        data-cy="notification-history-filter-form"
      >
        <div className="grid gap-4 lg:grid-cols-3">
          <Select
            {...filterRegister("seen")}
            items={[
              { label: "Seen", value: "true" },
              { label: "Not seen", value: "false" },
            ]}
            label="Seen"
            name="seen"
            placeholder="Any"
            clearable
            value={watch("seen")}
            onClear={() => setValue("seen", undefined)}
          />
          <Select
            {...filterRegister("user_id")}
            items={currentUserOption}
            label="User"
            name="user_id"
            placeholder="Current user"
            clearable
            searchable
            searchMode="server"
            searchPlaceholder="Search users"
            searchQueryKey={["notification-history-user-filter"]}
            searchFn={searchUsers}
            value={watch("user_id")}
            onClear={() => setValue("user_id", undefined)}
            dataCy="notification-history-filter-user-select"
          />
          <InputGroup
            {...filterRegister("search")}
            name="search"
            label="Search"
            placeholder="Search"
            type="search"
            dataCy="notification-history-filter-search-input"
          />
        </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="notification-history-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="notification-history-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 NotificationHistoryListFilters;
