"use client";
import { getLocation } from "@/app/actions";
import { useState } from "react";
import { useFormStatus } from "react-dom";

export default function LocationSearch(props: any) {
  const [searchLocation, setSearchLocation] = useState("");
  const setGeoLocation = props.setGeoLocation;
  const { pending } = useFormStatus();
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchLocation(e.target.value);
  };
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      const coordinates = await getLocation(searchLocation);
      setGeoLocation(coordinates);
    } catch (error) {
      console.error("Error fetching location:", error);
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input
          id="location"
          name="locationSearch"
          type="text"
          placeholder="enter a location to get the weather"
          value={searchLocation}
          onChange={handleChange}
        />
        <button type="submit" disabled={pending}>
          {pending ? "Searching..." : "Search"}
        </button>
        <label htmlFor="location" className="hidden">
          Enter location to get the weather!
        </label>
      </form>
    </>
  );
}
