"use client";

import LocationDialog from "@/components/locations/location-dialog";
import IUser from "@/interfaces/IUser";
import hasPermissions from "@/lib/hasPermissions";
import { useState } from "react";
import { Location } from "@/types/types";
import request from "@/lib/request";
import { useApi } from "@/hooks/use-api";
import { LocationCard } from "@/components/locations/location-card";

export default function LocationsPage({ user }: { user: IUser }) {
	const { locations: locationsPerm } = hasPermissions(user.roles, {
		locations: ["update", "insert", "delete"],
	} as const);

	const locations = useApi<Location[]>("/locations/all");

	const onUpdate = async (l: Location) => {
		try {
			const res = await request("/locations", {
				method: "PATCH",
				body: l,
				requiresAuth: true,
			});
			if (res.status === "Success") {
				locations.mutate();
			} else {
			}
		} catch (e) {
			console.error(e);
		}
	};

	const onDelete = async (l: Location) => {
		try {
			const res = await request("/locations", {
				method: "DELETE",
				body: l,
				requiresAuth: true,
			});

			if (res.status === "Success") locations.mutate();
			else {
			}
		} catch (e) {
			console.error(e);
		}
	};

	return (
		<div className="p-4 flex flex-col gap-2">
			{locationsPerm.insert && (
				<div className="self-end">
					<LocationDialog
						onAdd={async (l) => {
							try {
								const res = await request("/locations/new", {
									body: l,
									method: "POST",
									requiresAuth: true,
									csrfToken: false,
								});
								if (res.status === "Success") {
									locations.mutate();
								} else {
								}
							} catch (e) {}
						}}
					/>
				</div>
			)}
			<section className="flex flex-wrap gap-2">
				{locations.data?.map((l) => {
					return (
						<LocationCard
							key={`${l.city}:${l.street}:${l.postalCode}`}
							location={l}
							onUpdate={onUpdate}
							onDelete={onDelete}
							canUpdate={locationsPerm.update}
							canDelete={locationsPerm.delete}
						/>
					);
				})}
			</section>
		</div>
	);
}
