"use client";

import React, { useState } from "react";
import Link from "next/link";
import dynamic from "next/dynamic";
import { URL } from "../url";

// AsyncPaginate client-side only
const AsyncPaginate = dynamic(
  () =>
    import("react-select-async-paginate").then(
      (mod) => mod.AsyncPaginate
    ),
  { ssr: false }
);

export default function SearchBar({ slug = "properties" }) {
  const [userSelect, setUserSelect] = useState(null);
  const [search, setSearch] = useState("");

  /* ================= LOAD OPTIONS ================= */
  const loadOptionsPlayer = async (inputValue, loadedOptions, additional) => {
    const page = additional?.page || 1;

    const res = await fetch(
      `${URL.API_BASE_URL}/publicApi/searchareaforproductDis2?key=${inputValue}&page=${page}`
    );
    const json = await res.json();

    const options =
      json?.results?.map((item) => ({
        ...item,
        value: item._id,
        label:
          item.type === "state"
            ? `${item.State} (ALL)`
            : item.type === "district"
            ? `${item.District}, ${item.State} (ALL)`
            : `${item.Area}, ${item.District}, ${item.State}, ${item.Pincode}`,
      })) || [];

    return {
      options,
      hasMore: json?.has_more ?? false,
      additional: {
        page: page + 1,
      },
    };
  };

  /* ================= HANDLE LOCATION ================= */
  const handleLocation = (value) => {
    setUserSelect(value);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  /* ================= BUILD SAFE HREF ================= */
  const href = {
    pathname: `/${slug}`,
    query: {
      ...(search ? { search } : {}),
      ...(userSelect
        ? userSelect.type === "state"
          ? { locationst: userSelect._id }
          : userSelect.type === "district"
          ? { location: userSelect._id }
          : { locationar: userSelect._id }
        : {}),
    },
  };

  /* ================= UI ================= */
  return (
    <div className="container mt-1 mb-3">
      <div className="row g-2 align-items-center">
        {/* SEARCH INPUT */}
        <div className="col-md-6">
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="form-control"
            placeholder="Search..."
          />
        </div>

        {/* LOCATION DROPDOWN */}
        <div className="col-md-3 col-6">
          <AsyncPaginate
            value={userSelect}
            loadOptions={loadOptionsPlayer}
            onChange={handleLocation}
            additional={{ page: 1 }}
            placeholder="Location"
            className="liceninput"
          />
        </div>

        {/* SEARCH BUTTON */}
        <div className="col-md-3 col-6">
          <Link href={href} className="btn btn-primary w-100">
            Search
          </Link>
        </div>
      </div>
    </div>
  );
}
