"use client";

import { useState } from "react";
import ListDoctors from "./listDoctors";
import { useSearchParams } from "next/navigation";
import Head from "./head";
import specialties from "@/data/specialties.json";
import states from "@/data/state.json";
import cities from "@/data/city.json";
import { isRootCity } from "@/lib/rootCity";

function DoctorsPage({ matchedCity, matchedState, list }) {
  const searchParams = useSearchParams();
  const [page, setPage] = useState(list?.meta?.currentPage || 1);
  const [doctors, setDoctors] = useState(list?.data);
  const fieldName = searchParams.get("specialty");

  const findItem = (key, name) =>
    specialties.find((item) => item[key] === name);
  const isParent =
    findItem("name", fieldName) && findItem("name", fieldName).parent_id;

  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 valCategory = isParent
    ? findItem("id", isParent)
    : findItem("name", fieldName);
  const valSpecialty = isParent && findItem("name", fieldName);

  const defaultFilter = {
    state: selectedState && states.find((item) => item.name === selectedState),
    city: selectedCity && cities.find((item) => item.name === selectedCity),
    category: valCategory,
    specialty: valSpecialty,
    active: Number(searchParams.get("active")) || 0,
    gender: searchParams.get("gender") || "هر دو",
    degree: searchParams.get("degree") || "همه موارد",
    sort: (searchParams.get("sort") && Number(searchParams.get("sort"))) || "",
    name:
      searchParams.get("name") || valSpecialty?.name || valCategory?.name || "",
  };

  const [filter, setFilter] = useState(defaultFilter);
  const [loading, setLoading] = useState(false);

  return (
    <div className="pt-[95px] sm:pt-[120px] padding-responsive">
      <Head
        limit={12}
        filter={filter}
        setPage={setPage}
        setFilter={setFilter}
        setDoctors={setDoctors}
        setLoading={setLoading}
        matchedCity={matchedCity}
        matchedState={matchedState}
      />
      <ListDoctors
        limit={12}
        data={list}
        page={page}
        filter={filter}
        setPage={setPage}
        doctors={doctors}
        loading={loading}
        setLoading={setLoading}
        setDoctors={setDoctors}
      />
    </div>
  );
}

export default DoctorsPage;
