import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

import { Column } from "@/common/components/Matrix/Column";
import { Matrix } from "@/common/components/Matrix/Matrix";
import { TableStateResponse } from "@/common/models/TableStateResponse";
import { LockedEventCodeModel } from "@/contracts/client.schemas";
import { useContactId } from "@/hooks/use-contact-id";
import { http } from "@/services/http.service";

import { EventCode } from "./EventCode";

export const LockedEventCodeListPage = () => {
	const { organizationId, assetId } = useParams();
	const [eventCodes, setEventCodes] = useState<EventCode[]>([]);
	const { getMessage, getGroup } = useContactId();

	useEffect(() => {
		if (!organizationId) {
			throw new Error("organizationId is required");
		}
		if (!assetId) {
			throw new Error("assetId is required");
		}

		const load = async () => {
			try {
				const response =
					await http.get<TableStateResponse<EventCode>>(
						`/api/event-codes`,
					);
				setEventCodes(response.items);
			} catch (error) {
				console.error(error);
			}
		};

		load();
	}, [organizationId, assetId]);

	function findEventCode(id: string): EventCode | undefined {
		return eventCodes.find((x) => x.id === id);
	}

	function getTitle(x: string) {
		const keyCode = findEventCode(x)?.value;
		if (!keyCode) {
			return "-";
		}

		return getMessage(keyCode);
	}

	const columns: Column<LockedEventCodeModel>[] = [
		{
			name: "eventCodeId",
			title: "Code",
			convert: (x) => findEventCode(x)?.value.toFixed(0) ?? x,
		},
		{
			name: "eventCodeId",
			title: "Name",
			convert: getTitle,
		},
		{
			name: "eventCodeId",
			title: "Group",
			convert: (x) => {
				const keyCode = findEventCode(x)?.group;
				if (!keyCode) {
					return null;
				}

				return getGroup(keyCode);
			},
		},
	];

	return (
		<Matrix<LockedEventCodeModel>
			title="Locked Event Codes"
			columns={columns}
			baseUrl={`/api/organizations/${organizationId}/assets/${assetId}/locked-event-codes`}
			defaultSort={[
				{
					field: "index",
					direction: "asc",
				},
			]}
			notificationMethodPrefix="LOCKED_EVENT_CODES"
			getModelTitle={(x) => getTitle(x.eventCodeId)}
			canCreate={true}
			canView={true}
			canRemove={true}
		/>
	);
};
