import DoctorsPage from "@/components/doctors";
import Layout from "@/components/layout/StLayout";
import { buildDoctorParams } from "@/helper";
import { getStateInfo } from "@/lib/getStateInfo";
import axios from "axios";

async function Doctors({ searchParams }) {
  const { matchedCity, matchedState } = getStateInfo();
  const API_URL = process.env.NEXT_PUBLIC_API_URL;

  let doctors = null;
  const stateParams = searchParams.state;
  const cityParams = searchParams.city;

  try {
    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 = buildDoctorParams(newSearchParams);

    const response = await axios.get(`${API_URL}/api/v1/doctors`, {
      params,
    });
    doctors = response.data;
  } catch (error) {
    console.error("Error fetching doctors:", error);
  }

  return (
    <Layout>
      <DoctorsPage
        list={doctors}
        params={searchParams}
        matchedCity={matchedCity}
        matchedState={matchedState}
      />
    </Layout>
  );
}

export default Doctors;
