import { OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';
import { fetchAddons, fetchAppointmentTypes, fetchCalendars, fetchLabels } from '.';
import { acuitySchedulingAuth } from '../auth';

interface DropdownParams {
	displayName: string;
	description?: string;
	required: boolean;
}

export const appointmentTypeIdDropdown = (params: DropdownParams) =>
	Property.Dropdown({
		auth: acuitySchedulingAuth,
		displayName: params.displayName,
		description: params.description,
		required: params.required,
		refreshers: [],
		options: async ({ auth }) => {
			if (!auth) {
				return {
					disabled: true,
					placeholder: 'Please authenticate first',
					options: [],
				};
			}
			const { access_token } = auth as OAuth2PropertyValue;

			return {
				disabled: false,
				options: await fetchAppointmentTypes(access_token),
			};
		},
	});

export const calendarIdDropdown = (params: DropdownParams) =>
	Property.Dropdown({
		auth: acuitySchedulingAuth,
		displayName: params.displayName,
		description: params.description,
		required: params.required,
		refreshers: [],
		options: async ({ auth }) => {
			if (!auth) {
				return {
					disabled: true,
					placeholder: 'Please authenticate first',
					options: [],
				};
			}
			const { access_token } = auth as OAuth2PropertyValue;

			return {
				disabled: false,
				options: await fetchCalendars(access_token),
			};
		},
	});

export const addonIdsDropdown = (params: DropdownParams) =>
	Property.MultiSelectDropdown({
		auth: acuitySchedulingAuth,
		displayName: params.displayName,
		description: params.description,
		required: params.required,
		refreshers: ['appointmentTypeID'],
		options: async ({ auth, appointmentTypeID }) => {
			if (!auth || !appointmentTypeID) {
				return {
					disabled: true,
					placeholder: 'Please authenticate first',
					options: [],
				};
			}
			const { access_token } = auth as OAuth2PropertyValue;

			return {
				disabled: false,
				options: await fetchAddons(access_token, appointmentTypeID as number),
			};
		},
	});

export const labelIdDropdown = (params: DropdownParams) =>
	Property.Dropdown({
		auth: acuitySchedulingAuth,
		displayName: params.displayName,
		description: params.description,
		required: params.required,
		refreshers: [],
		options: async ({ auth }) => {
			if (!auth) {
				return {
					disabled: true,
					placeholder: 'Please authenticate first',
					options: [],
				};
			}
			const { access_token } = auth as OAuth2PropertyValue;

			return {
				disabled: false,
				options: await fetchLabels(access_token),
			};
		},
	});
