import { defineAsyncComponent, h } from 'vue';
import { renderDialog } from '../../utils/components';
import type {
	BannerConfig,
	ColumnField,
	DocumentResource,
	Route,
	Row,
} from './types';
import { trialDays } from '../../utils/site';
import { planTitle } from '../../utils/format';

export const unreachable = Error('unreachable'); // used to indicate that a codepath is unreachable

export const clusterOptions = [
	'',
	'中国大陆',
	'中国香港',
	'美国-洛杉矶',
	'新加坡',
	'英国-伦敦',
	'德国-法兰克福',
	'阿联酋-迪拜',
];

export function getUpsellBanner(site: DocumentResource, title: string) {
	if (
		!site.pg.current_plan ||
		site.pg.current_plan?.private_benches ||
		site.pg.current_plan?.is_trial_plan ||
		!site.pg.group_public
	)
		return;

	return {
		title: title,
		dismissable: true,
		id: site.name,
		type: 'gray',
		button: {
			label: '升级计划',
			variant: 'outline',
			onClick() {
				let SitePlansDialog = defineAsyncComponent(
					() => import('../../components/ManageSitePlansDialog.vue')
				);
				renderDialog(h(SitePlansDialog, { site: site.name }));
			},
		},
	} satisfies BannerConfig as BannerConfig;
}

export function getSitesTabColumns(forBenchTab: boolean) {
	return [
		{
			label: '站点',
			fieldname: 'host_name',
			format(value, row) {
				return value || row.name;
			},
			prefix: () => {
				if (forBenchTab) return;
				return h('div', { class: 'ml-2 w-3.5 h-3.5' });
			},
		},
		{
			label: '状态',
			fieldname: 'status',
			type: 'Badge',
			width: 0.5,
		},
		{
			label: '区域',
			fieldname: 'cluster_title',
			width: 0.5,
			prefix(row) {
				if (row.cluster_title)
					return h('img', {
						src: row.cluster_image,
						class: 'w-4 h-4',
						alt: row.cluster_title,
					});
			},
		},
		{
			label: '计划',
			width: 0.5,
			format(value, row) {
				if (row.trial_end_date) {
					return trialDays(row.trial_end_date);
				}
				return planTitle(row);
			},
		},
	] satisfies ColumnField[] as ColumnField[];
}

export function siteTabFilterControls() {
	return [
		{
			type: 'select',
			label: '状态',
			fieldname: 'status',
			options: [
				{ label: '', value: '' },
				{ label: '激活', value: 'Active' },
				{ label: '未激活', value: 'Inactive' },
				{ label: '已暂停', value: 'Suspended' },
				{ label: '已损坏', value: 'Broken' }
			],
		},
		{
			type: 'select',
			label: '区域',
			fieldname: 'cluster',
			options: [
				'',
				'中国大陆',
				'中国香港',
				'美国-洛杉矶',
				'新加坡',
				'英国-伦敦',
				'德国-法兰克福',
				'阿联酋-迪拜',
			],
		},
	];
}

export function sitesTabRoute(r: Row) {
	return {
		name: '站点详情',
		params: { name: r.name },
	} satisfies Route as Route;
}