"use client";

import { useState } from "react";

import { PanchangLocation } from "@/app/lib/panchang";

import PlaceAutocomplete from "@/app/components/PlaceAutocomplete";

interface Props {
  date: string;

  onDateChange: (date: string) => void;

  location: PanchangLocation;

  locationLabel: string;

  onLocationChange: (location: PanchangLocation, label: string) => void;

  buttonLabel: string;
}

/*
|--------------------------------------------------------------------------
| Panchang Search Bar
|--------------------------------------------------------------------------
|
| Shared location + date search used across all panchang pages
| (Today/Tomorrow Panchang, Rahu Kaal, Tithi, Choghadiya, Vaar, Hora).
| Keeps its own staged input state — the parent's committed
| date/location only change when the button is clicked.
|
*/

export default function PanchangSearchBar({
  date,
  onDateChange,
  location,
  locationLabel,
  onLocationChange,
  buttonLabel,
}: Props) {
  const [dateInput, setDateInput] = useState(date);

  const [locationInput, setLocationInput] = useState(locationLabel);

  // Set by PlaceAutocomplete's onSelect once Google Place Details
  // resolves for whatever the user picked — the search box only stores
  // a label, so the actual coordinates have to be captured separately.
  const [resolvedLocation, setResolvedLocation] = useState<PanchangLocation | null>(null);

  const handleSubmit = () => {
    onDateChange(dateInput || date);

    onLocationChange(resolvedLocation || location, resolvedLocation ? locationInput : locationLabel);
  };

  return (
    <div className="panchang-search-bar">
      <div className="panchang-search-field">
        <PlaceAutocomplete
          placeholder="Search city, e.g. New Delhi, India"
          value={locationInput}
          onChange={setLocationInput}
          onSelect={(details) =>
            setResolvedLocation({
              latitude: details.latitude,
              longitude: details.longitude,
              timezone: details.timezone,
            })
          }
        />
      </div>

      <div className="panchang-search-date">
        <span>📅</span>

        <input
          type="date"
          value={dateInput}
          onChange={(event) => setDateInput(event.target.value)}
        />
      </div>

      <button type="button" className="panchang-search-btn" onClick={handleSubmit}>
        {buttonLabel}
      </button>
    </div>
  );
}
