import { fetchReq } from "@/lib/req";
import ClinicsPage from "@/components/clinics";
import Layout from "@/components/layout/StLayout";
import { getStateInfo } from "@/lib/getStateInfo";
import { buildClinicParams } from "@/helper";

export default async function Clinics({ searchParams }) {
  const { matchedCity, matchedState } = getStateInfo();
  const API_URL = process.env.NEXT_PUBLIC_API_URL;
  const stateParams = searchParams.state;
  const cityParams = searchParams.city;

  let clinics;
  try {
    // Params
    let newSearchParams = searchParams;

    // Conditional State
    if (stateParams) newSearchParams.state = stateParams;
    else if (matchedState) newSearchParams.state = matchedState.name;

    // Conditional City
    if (cityParams) newSearchParams.city = cityParams;
    else if (matchedCity && matchedCity.id !== "600")
      newSearchParams.city = matchedCity.name;

    const params = buildClinicParams(newSearchParams);

    // Req
    clinics = await fetchReq(`${API_URL}/api/v1/clinics`, {
      params,
    });
  } catch (err) {}

  return (
    <Layout name="/clinics">
      <ClinicsPage
        clinics={clinics}
        matchedCity={matchedCity}
        matchedState={matchedState}
      />
    </Layout>
  );
}
