"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";

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

  const selectedState = searchParams.get("state") || matchedState?.name;
  const selectedCity =
    searchParams.get("city") ||
    (matchedCity?.name && matchedCity?.id !== "600"
      ? 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?.page || []}
        setFilteredClinics={setFilteredClinics}
      />
    </div>
  );
}

export default ClinicsPage;
