"use client";

import { useState } from "react";

import List from "./list";
import SearchBar from "./head/SearchBar";
import HeadPageList from "@/app/component/head";
import specialtiesData from "@/data/specialties.json";
import { useSearchParams } from "next/navigation";

// Data
import states from "@/data/state.json";
import cities from "@/data/city.json";
import { isRootCity } from "@/lib/rootCity";

function ClinicsPage({ clinics, matchedCity, matchedState }) {
  const searchParams = useSearchParams();
  const [page, setPage] = useState(clinics?.meta?.currentPage || 1);
  const [filteredClinics, setFilteredClinics] = useState(clinics?.data);

  const isRoot = isRootCity(matchedCity);
  const selectedState =
    searchParams.get("state") || (!isRoot ? matchedState?.name : undefined);
  const selectedCity =
    searchParams.get("city") ||
    (matchedCity?.name && !isRoot ? matchedCity?.name : false);

  const [selected, setSelected] = useState({
    province:
      selectedState && states.find((item) => item.name === selectedState),
    city: selectedCity && cities.find((item) => item.name === selectedCity),
    specialty: searchParams.get("specialty") || "",
  });

  return (
    <div>
      <HeadPageList
        title="لیست کلینیک ها و درمانگاه های تخصصی"
        detail="در قسمت زیر می توانید کلینیک مورد نظر خود را جستجو نمایید"
      >
        <SearchBar
          limit={12}
          setPage={setPage}
          selected={selected}
          state={matchedState}
          setSelected={setSelected}
          specialties={specialtiesData}
          setFilteredClinics={setFilteredClinics}
        />
      </HeadPageList>
      <List
        limit={12}
        page={page}
        setPage={setPage}
        selected={selected}
        clinics={filteredClinics}
        pages={clinics?.meta || {}}
        setFilteredClinics={setFilteredClinics}
      />
    </div>
  );
}

export default ClinicsPage;
