"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";

interface urlProp {
  value: string | null;
}

function SearchUserWithDate(props: urlProp) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const todayISO = new Date().toLocaleDateString("en-CA");

  const [numAcount, setNumAcount] = useState("");
  const [date, setDate] = useState(todayISO);

  useEffect(() => {
    const num = searchParams.get("numAcount");
    const dateParam = searchParams.get("date");

    if (num) setNumAcount(num);
    if (dateParam) setDate(dateParam);
  }, [searchParams]);

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

    const params = new URLSearchParams(searchParams.toString());

    if (numAcount) {
      params.set("numAcount", numAcount);
    }

    if (date) {
      params.set("date", date);
    }

    router.push(`${pathname}?${params.toString()}`);
  };

  return (
    <form className="containerForm" onSubmit={handleSubmit}>
      <label className="label">No.Cuenta</label>
      <div className="groupInput">
        <input
          type="text"
          value={numAcount}
          onChange={(e) => {
            const value = e.target.value;
            if (/^\d*$/.test(value) && value.length <= 9) {
              setNumAcount(value);
            }
          }}
          placeholder="Coloca un número de cuenta..."
        />
      </div>

      <label className="label">Fecha</label>
      <div className="groupInput">

        <input
          type="date"
          value={date}
          onChange={(e) => setDate(e.target.value)}
        />

        <button className="button buttonSearch" type="submit">
          Buscar
        </button>
      </div>
    </form>
  );
}

export default SearchUserWithDate;
