"use client";
import React, { useContext, useState } from "react";
import { LocationContext } from "@/context/LocationContext";
import { coordType } from "@/types/types";

export default function LocationSearch() {
  const [searchLocation, setSearchLocation] = useState("");
  const { setGeoLocation } = useContext(LocationContext);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchLocation(e.target.value);
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setPending(true);
    setError(null);

    try {
      const coordinates = await getLocation(searchLocation);
      if (coordinates) {
        setGeoLocation(coordinates);
      }
    } catch (error) {
      console.error("Error fetching location:", error);
      setError("Error fetching location");
    } finally {
      setPending(false);
    }
  };

  const getLocation = async (
    searchLocation: string
  ): Promise<coordType | null> => {
    try {
      const response = await fetch(
        `/api/location?location=${encodeURIComponent(searchLocation)}`
      );
      if (!response.ok) {
        throw new Error("Failed to fetch the location data");
      }
      const data = await response.json();
      return data;
    } catch (error: any) {
      console.error("Error fetching location:", error);
      setError(error.message);
      return null;
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        className="my-4 w-full rounded h-8 px-2 box-border border-2 hover:shadow-md max-w-md"
        id="location"
        name="locationSearch"
        type="text"
        placeholder="Enter a location to get the weather"
        value={searchLocation}
        onChange={handleChange}
        disabled={pending}
        aria-label="Enter location to query the weather"
      />
      {error && <p className="text-red-500">{error}</p>}
    </form>
  );
}
