//next.js page to show all locatons in the database with a link to the location page
import { Location, UserRole } from "@prisma/client";
import Layout from "../../../components/layout";
import LocationCard from "../../../components/location/LocationCard";
import axiosServer from '../../../src/axiosServer';
import ProtectedRoute from '../../../components/protectedRoute';
import CongregationCRUD from "../publishers/congregationCRUD";
interface IProps {
  item: Location;
}

function LocationsPage({ items = [] }: IProps) {
  const renderLocations = () => {

    if (!Array.isArray(items) || items.length === 0) return <h1>No Locations</h1>;

    return items.map((item) => (
      <LocationCard key={item.id} location={item} />
    ));

  };

  return (
    <Layout>
      <ProtectedRoute allowedRoles={[UserRole.POWERUSER, UserRole.ADMIN]}>
        <div className="grid gap-4 grid-cols-1 md:grid-cols-4">
          {renderLocations()}
        </div>
        {/* add location link */}
        <div className="flex justify-center">
          <a href="/cart/locations/new" className="btn">
            Add Location
          </a>
        </div>
      </ProtectedRoute>
      <CongregationCRUD />
    </Layout>
  );
}

export default LocationsPage;

export const getServerSideProps = async (context) => {
  const axios = await axiosServer(context);
  const { data: items } = await axios.get("/api/data/locations");
  console.log('get server props - locations:' + items.length);
  //console.log(items);
  return {
    props: {
      items,
    },
  };
};