"use client";

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

export default function SearchDate() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const todayISO = new Date().toLocaleDateString("en-CA");
  const [date, setDate] = useState(todayISO);

  useEffect(() => {
    const dateParam = searchParams.get("date");
    if (dateParam) {
      setDate(dateParam);
    }
  }, [searchParams]);

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

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

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

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

  return (
    <form className="containerForm" onSubmit={handleSubmit}>
      <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>
  );
}
//IO
//By Tyrannuss
