import { Metadata } from "next";
import { notFound } from "next/navigation";

import {
  Header,
  CommunesList,
  DepartementsList,
  RegionList,
} from "@/components/index";
import communes, {
  Commune,
  getCommuneFromSlug,
  getSlugFromCommune,
  getCodesPostaux,
  getChefLieu,
  CommuneDeleguee,
} from "@/lib/communes";
import {
  Content,
  ContentHeader,
  ContentBody,
  ContentFull,
  ContentHalf,
} from "@/components/Content/Content";

import departements, {
  getSlugFromDepartement,
  getDepartementFromSlug,
} from "@/lib/departements";
import { getRegionFromCode, getSlugFromRegion } from "@/lib/regions";
import Link from "next/link";

import { getMSPFromCodesPostaux } from "@/lib/api-annuaire-sante";

export const metadata: Metadata = {
  title: "Annuaire",
  description: "L'annuaire collaboratif des professionnels de la santé",
};

export async function generateStaticParams() {
  return communes.map((commune) => ({
    commune: getSlugFromCommune(commune),
  }));
}

async function getData(codesPostaux: Array<string>) {
  const res = await fetch(
    `http://localhost:8000/fhir/v1/Organization?address-postalcode%3Aexact=${codesPostaux.join(
      "%2C",
    )}&_count=5000&type=https://mos.esante.gouv.fr/NOS/TRE_R66-CategorieEtablissement/FHIR/TRE-R66-CategorieEtablissement%7C603`,
    { cache: "force-cache" },
  );
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

export default async function CommunePage({
  params,
}: {
  params: { regionSlug: string; departementSlug: string; communeSlug: string };
}) {
  const commune = getCommuneFromSlug(params.communeSlug);
  if (!commune) return notFound();
  const departement = getDepartementFromSlug(params.departementSlug);
  if (!departement) return notFound();
  const region = getRegionFromCode(departement.region);
  if (!region) return notFound();

  let chefLieu: Commune | Boolean = commune.chefLieu
    ? getChefLieu(commune)
    : false;

  const codesPostaux = commune.chefLieu
    ? [commune.chefLieu]
    : commune.codesPostaux;
  const msps = await getMSPFromCodesPostaux(codesPostaux);

  return (
    <>
      <Header searchField={true} />
      <Content>
        <div className="bg-primary pb-24">
          <div className="max-w-7xl mx-auto pt-16 px-10">
            <div className="rounded-md bg-base-100 p-8 w-full flex items-center">
              <div className="prose w-96 text-center">
                <h1 className="pb-0 mb-0">{commune.nom}</h1>
                <p className="mt-0 pt-0">{getCodesPostaux(commune)}</p>
              </div>
              <div className="overflow-x-auto">
                <table className="table">
                  <tbody>
                    <tr>
                      <th>Région</th>
                      <td>
                        <Link href={`/annuaire/${getSlugFromRegion(region)}`}>
                          {region.nom}
                        </Link>
                      </td>
                    </tr>
                    <tr>
                      <th>Département</th>
                      <td>
                        <Link
                          href={`/annuaire/${getSlugFromRegion(
                            region,
                          )}/${getSlugFromDepartement(departement)}`}
                        >
                          {departement.nom} ({departement.code})
                        </Link>
                      </td>
                    </tr>
                    {commune.population && (
                      <tr>
                        <th>Population</th>
                        <td>
                          {commune.population.toLocaleString("fr-FR")} habiants
                        </td>
                      </tr>
                    )}
                    {chefLieu && (
                      <tr>
                        <th>Cheflieu</th>
                        <td>
                          <Link
                            href={`/annuaire/${getSlugFromRegion(
                              region,
                            )}/${getSlugFromDepartement(
                              departement,
                            )}/${getSlugFromCommune(chefLieu)}`}
                          >
                            {chefLieu.nom}
                          </Link>
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <ContentBody>
          <div className="max-w-7xl mx-auto pt-8 px-10 flex flex-wrap">
            {msps.entry && (
              <div className="w-6/12 pr-8">
                <div className="rounded-md bg-base-100 p-8 prose">
                  <h2>Informations sur les {msps.total} structures</h2>
                  <ul>
                    {msps.entry.map((msp) => (
                      <li key={msp.resource.name}>{msp.resource.name}</li>
                    ))}
                  </ul>
                </div>
              </div>
            )}
            <div className="w-6/12">
              <div className="rounded-md bg-base-100 p-8">
                <h2>Dirigeants et représentants de P4PILLON</h2>
              </div>
            </div>
          </div>
          <ContentFull>test</ContentFull>
        </ContentBody>
      </Content>
      <RegionList selected={region} />
      <hr></hr>
      <DepartementsList selected={departement} region={region} />
      <hr></hr>
      <CommunesList selected={commune} departement={departement} />
    </>
  );
}
