/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { router } from "@inertiajs/react";
import { useEffect, useRef, useState } from "react";
import { FiSearch } from "react-icons/fi";
import styles from "./search.module.scss";

interface SearchProps {
  url: string;
  param?: string;
  extraParams?: Record<string, any>;
  placeholder?: string;
  preserveScroll?: boolean;
  disabled?: boolean;
  /**
   * Initial query value, optional
   */
  initialQuery?: string;
}

export default function Search({
  url,
  param = "search",
  extraParams = {},
  placeholder = "Search...",
  preserveScroll = true,
  disabled = false,
  initialQuery = "",
}: SearchProps) {
  const [query, setQuery] = useState(initialQuery);
  const mounted = useRef(false);

  // Only trigger auto-reset AFTER first mount
  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
      return;
    }

    // If input is cleared, reload first page
    if (query.trim() === "") {
      router.get(
        url,
        { page: 1, ...extraParams },
        { preserveScroll, preserveState: true, replace: true }
      );
    }
  }, [query]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    // Don't send request if query is empty
    if (!query.trim()) return;

    router.get(
      url,
      { page: 1, [param]: query.trim(), ...extraParams },
      { preserveScroll, preserveState: true, replace: true }
    );
  };

  return (
    <form className={styles.search} onSubmit={handleSubmit}>
      <div className={styles.search__inputWrapper}>
        <FiSearch className={styles.search__icon} />
        <input
          type="text"
          placeholder={placeholder}
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          disabled={disabled}
        />
      </div>
      <button type="submit" disabled={disabled || !query.trim()}>
        Search
      </button>
    </form>
  );
}
