import { LoadingIndicator, Tooltip } from 'jingrow-ui';
import { defineAsyncComponent, h } from 'vue';
import { toast } from 'vue-sonner';
import LucideAppWindow from '~icons/lucide/app-window';
import LucideHardDriveDownload from '~icons/lucide/hard-drive-download';
import LucideRocket from '~icons/lucide/rocket';
import AddAppDialog from '../components/group/AddAppDialog.vue';
import ChangeAppBranchDialog from '../components/group/ChangeAppBranchDialog.vue';
import PatchAppDialog from '../components/group/PatchAppDialog.vue';
import { getTeam, switchToTeam } from '../data/team';
import router from '../router';
import { confirmDialog, icon, renderDialog } from '../utils/components';
import { getToastErrorMessage } from '../utils/toast';
import { date, duration } from '../utils/format';
import { getJobsTab } from './common/jobs';
import { getPatchesTab } from './common/patches';
import { tagTab } from './common/tags';
import { t } from '../utils/i18n';

export default {
	pagetype: 'Release Group',
	whitelistedMethods: {
		addApp: 'add_app',
		removeApp: 'remove_app',
		changeAppBranch: 'change_app_branch',
		fetchLatestAppUpdates: 'fetch_latest_app_update',
		deleteConfig: 'delete_config',
		updateConfig: 'update_config',
		updateEnvironmentVariable: 'update_environment_variable',
		deleteEnvironmentVariable: 'delete_environment_variable',
		updateDependency: 'update_dependency',
		addRegion: 'add_region',
		deployedVersions: 'deployed_versions',
		getAppVersions: 'get_app_versions',
		getCertificate: 'get_certificate',
		generateCertificate: 'generate_certificate',
		sendTransferRequest: 'send_change_team_request',
		addTag: 'add_resource_tag',
		removeTag: 'remove_resource_tag',
		redeploy: 'redeploy',
		initialDeploy: 'initial_deploy'
	},
	list: {
		route: '/groups',
		title: t('Release Group'),
		fields: [{ apps: ['app'] }],
		searchField: 'title',
		filterControls() {
			return [
				{
					type: 'link',
					label: t('Version'),
					fieldname: 'version',
					options: {
						pagetype: 'Jingrow Version'
					}
				},
				{
					type: 'link',
					label: t('Tag'),
					fieldname: 'tags.tag',
					options: {
						pagetype: 'Jcloud Tag',
						filters: {
							pagetype_name: 'Release Group'
						}
					}
				}
			];
		},
		columns: [
			{ label: t('Title'), fieldname: 'title', class: 'font-medium' },
			{
				label: t('Status'),
				fieldname: 'active_benches',
				type: 'Badge',
				width: 0.5,
				format: (value, row) => {
					if (!value) return t('Waiting for Deployment');
					else return t('Active');
				}
			},
			{
				label: t('Version'),
				fieldname: 'version',
				width: 0.5
			},
			{
				label: t('App'),
				fieldname: 'app',
				format: (value, row) => {
					return (row.apps || []).map(d => d.app).join(', ');
				},
				width: '25rem'
			},
			{
				label: t('Sites'),
				fieldname: 'site_count',
				class: 'text-gray-600',
				width: 0.25
			}
		],
		primaryAction() {
			return {
				label: t('New Release Group'),
				variant: 'solid',
				slots: {
					prefix: icon('plus')
				},
				onClick() {
					router.push({ name: 'New Release Group' });
				}
			};
		}
	},
	detail: {
		titleField: 'title',
		statusBadge({ documentResource: releaseGroup }) {
			return { label: releaseGroup.pg.status };
		},
		breadcrumbs({ items, documentResource: releaseGroup }) {
			if (!releaseGroup.pg.server_team) return items;

			let breadcrumbs = [];
			let $team = getTeam();

			if (
				releaseGroup.pg.server_team == $team.pg?.name ||
				$team.pg?.is_desk_user
			) {
				breadcrumbs.push(
					{
						label: releaseGroup.pg?.server_title || releaseGroup.pg?.server,
						route: `/servers/${releaseGroup.pg?.server}`
					},
					items[1]
				);
			} else {
				breadcrumbs.push(...items);
			}
			return breadcrumbs;
		},
		route: '/groups/:name',
		tabs: [
			{
				label: t('Sites'),
				icon: icon(LucideAppWindow),
				route: 'sites',
				type: 'Component',
				component: defineAsyncComponent(() =>
					import('../pages/ReleaseGroupBenchSites.vue')
				),
				props: releaseGroup => {
					return { releaseGroup: releaseGroup.pg.name };
				}
			},
			{
				label: t('App'),
				icon: icon('grid'),
				route: 'apps',
				type: 'list',
				list: {
					pagetype: 'Release Group App',
					filters: releaseGroup => {
						return {
							parenttype: 'Release Group',
							parent: releaseGroup.pg.name
						};
					},
					pageLength: 99999,
					columns: [
						{
							label: t('App'),
							fieldname: 'title',
							width: 1
						},
						{
							label: t('Repository'),
							width: 1,
							format(value, row) {
								return `${row.repository_owner}/${row.repository}`;
							},
							link(value, row) {
								return row.repository_url;
							}
						},
						{
							label: t('Branch'),
							fieldname: 'branch',
							type: 'Badge',
							width: 0.5,
							link(value, row) {
								return `${row.repository_url}/tree/${value}`;
							}
						},
						{
							label: t('Version'),
							type: 'Badge',
							fieldname: 'tag',
							width: 0.5,
							format(value, row) {
								return value || row.hash?.slice(0, 7);
							}
						},
						{
							label: t('Status'),
							type: 'Badge',
							suffix(row) {
								if (!row.last_github_poll_failed) return;

								return h(
									Tooltip,
									{
										text: t("What is this?"),
										placement: 'top',
										class: 'rounded-full bg-gray-100 p-1'
									},
									() => [
										h(
											'a',
											{
												href: 'https://jingrow.com/docs/faq/app-installation-issue',
												target: '_blank'
											},
											[h(icon('help-circle', 'w-3 h-3'), {})]
										)
									]
								);
							},
							format(value, row) {
								let { update_available, deployed, last_github_poll_failed } =
									row;

								return last_github_poll_failed
									? t('Action Required')
									: !deployed
									? t('Not Deployed')
									: update_available
									? t('Update Available')
									: t('Latest Version');
							},
							width: 0.5
						}
					],
					rowActions({
						row,
						listResource: apps,
						documentResource: releaseGroup
					}) {
						let team = getTeam();
						return [
							{
								label: t('View in Desk'),
								condition: () => team.pg?.is_desk_user,
								onClick() {
									window.open(
										`${window.location.protocol}//${window.location.host}/app/app/${row.name}`,
										'_blank'
									);
								}
							},
							{
								label: t('Fetch Latest Updates'),
								onClick() {
									toast.promise(
										releaseGroup.fetchLatestAppUpdates.submit({
											app: row.name
										}),
										{
											loading: t('Fetching latest updates for {app}...', { app: row.title }),
											success: () => {
												apps.reload();
												return t('Latest updates fetched for {app}', { app: row.title });
											},
											error: e => getToastErrorMessage(e)
										}
									);
								}
							},
							{
								label: t('Change Branch'),
								onClick() {
									renderDialog(
										h(ChangeAppBranchDialog, {
											bench: releaseGroup.name,
											app: row,
											onBranchChange() {
												apps.reload();
											}
										})
									);
								}
							},
							{
								label: t('Remove App'),
								condition: () => row.name !== 'jingrow',
								onClick() {
									if (releaseGroup.removeApp.loading) return;
									confirmDialog({
										title: t('Remove App'),
										message: t('Are you sure you want to remove app <b>{app}</b>?', { app: row.title }),
										onSuccess: ({ hide }) => {
											toast.promise(
												releaseGroup.removeApp.submit({
													app: row.name
												}),
												{
													loading: t('Removing app...'),
													success: () => {
														hide();
														apps.reload();
														return t('App removed');
													},
													error: e => getToastErrorMessage(e)
												}
											);
										}
									});
								}
							},
							{
								label: t('Visit Repository'),
								onClick() {
									window.open(
										`${row.repository_url}/tree/${row.branch}`,
										'_blank'
									);
								}
							},
							{
								label: t('Apply Patch'),
								onClick: () => {
									renderDialog(
										h(PatchAppDialog, {
											group: releaseGroup.name,
											app: row.name
										})
									);
								}
							}
						];
					},
					primaryAction({
						listResource: apps,
						documentResource: releaseGroup
					}) {
						return {
							label: t('Add App'),
							slots: {
								prefix: icon('plus')
							},
							onClick() {
								renderDialog(
									h(AddAppDialog, {
										group: releaseGroup.pg,
										onAppAdd() {
											apps.reload();
											releaseGroup.reload();
										},
										onNewApp(app, isUpdate) {
											const loading = isUpdate
												? t('Replacing app...')
												: t('Adding app...');

											toast.promise(
												releaseGroup.addApp.submit({
													app,
													is_update: isUpdate
												}),
												{
													loading,
													success: () => {
														apps.reload();
														releaseGroup.reload();

														if (isUpdate) {
															return t('App {app} updated', { app: app.title });
														}

														return t('App {app} added', { app: app.title });
													},
													error: e => getToastErrorMessage(e)
												}
											);
										}
									})
								);
							}
						};
					}
				}
			},
			{
				label: t('Deploy'),
				route: 'deploys',
				icon: icon('package'),
				childrenRoutes: ['Deploy Candidate'],
				type: 'list',
				list: {
					pagetype: 'Deploy Candidate',
					route: row => ({
						name: 'Deploy Candidate',
						params: { id: row.name }
					}),
					filters: releaseGroup => {
						return {
							group: releaseGroup.name
						};
					},
					orderBy: 'creation desc',
					fields: [{ apps: ['app'] }],
					filterControls() {
						return [
							{
								type: 'select',
								label: t('Status'),
								fieldname: 'status',
								options: [
									'',
									'Draft',
									'Scheduled',
									'Pending',
									'Preparing',
									'Running',
									'Success',
									'Failure'
								]
							}
						];
					},
					banner({ documentResource: releaseGroup }) {
						if (releaseGroup.pg.are_builds_suspended) {
							return {
								title:
									t('<b>Builds suspended:</b> Updates will be scheduled after builds resume.'),
								type: 'warning'
							};
						} else {
							return null;
						}
					},
					columns: [
						{
							label: t('Deploy'),
							fieldname: 'creation',
							format(value) {
								return t('Deployed at {date}', { date: date(value, 'llll') });
							},
							width: '20rem'
						},
						{
							label: t('Status'),
							fieldname: 'status',
							type: 'Badge',
							width: 0.5,
							suffix(row) {
								if (!row.addressable_notification) {
									return;
								}

								return h(
									Tooltip,
									{
										text: t('Attention required!'),
										placement: 'top',
										class: 'rounded-full bg-gray-100 p-1'
									},
									() => h(icon('alert-circle', 'w-3 h-3'), {})
								);
							}
						},
						{
							label: t('App'),
							format(value, row) {
								return (row.apps || []).map(d => d.app).join(', ');
							},
							width: '20rem'
						},
						{
							label: t('Duration'),
							fieldname: 'build_duration',
							format: duration,
							class: 'text-gray-600',
							width: 1
						},
						{
							label: t('Deployer'),
							fieldname: 'owner',
							width: 1
						}
					],
					primaryAction({ listResource: deploys, documentResource: group }) {
						return {
							label: t('Deploy'),
							slots: {
								prefix: icon(LucideRocket)
							},
							onClick() {
								if (group.pg.deploy_information.deploy_in_progress) {
									return toast.error(
										t('Deployment in progress. Please wait for it to complete.')
									);
								} else if (group.pg.deploy_information.update_available) {
									let UpdateReleaseGroupDialog = defineAsyncComponent(() =>
										import('../components/group/UpdateReleaseGroupDialog.vue')
									);
									renderDialog(
										h(UpdateReleaseGroupDialog, {
											bench: group.name,
											onSuccess(candidate) {
												group.pg.deploy_information.deploy_in_progress = true;
												if (candidate) {
													group.pg.deploy_information.last_deploy.name =
														candidate;
												}
											}
										})
									);
								} else {
									confirmDialog({
										title: t('Deploy without app updates?'),
										message:
											t('No app updates detected. Deployment will apply dependency and environment variable changes.'),
										onSuccess: ({ hide }) => {
											toast.promise(group.redeploy.submit(), {
												loading: t('Deploying...'),
												success: () => {
													hide();
													deploys.reload();
													return t('Changes deployed');
												},
												error: e => getToastErrorMessage(e)
											});
										}
									});
								}
							}
						};
					}
				}
			},
			getJobsTab('Release Group'),
			{
				label: t('Config'),
				icon: icon('settings'),
				route: 'bench-config',
				type: 'list',
				list: {
					pagetype: 'Common Site Config',
					filters: releaseGroup => {
						return {
							parenttype: 'Release Group',
							parent: releaseGroup.name
						};
					},
					orderBy: 'creation desc',
					fields: ['name'],
					pageLength: 999,
					columns: [
						{
							label: t('Config Name'),
							fieldname: 'key',
							format(value, row) {
								if (row.title) {
									return `${row.title} (${row.key})`;
								}
								return row.key;
							}
						},
						{
							label: t('Config Value'),
							fieldname: 'value',
							class: 'font-mono'
						},
						{
							label: t('Type'),
							fieldname: 'type',
							type: 'Badge',
							width: '100px'
						}
					],
					primaryAction({
						listResource: configs,
						documentResource: releaseGroup
					}) {
						return {
							label: t('Add Config'),
							slots: {
								prefix: icon('plus')
							},
							onClick() {
								let ConfigEditorDialog = defineAsyncComponent(() =>
									import('../components/ConfigEditorDialog.vue')
								);
								renderDialog(
									h(ConfigEditorDialog, {
										group: releaseGroup.pg.name,
										onSuccess() {
											configs.reload();
										}
									})
								);
							}
						};
					},
					secondaryAction({ listResource: configs }) {
						return {
							label: t('Preview'),
							slots: {
								prefix: icon('eye')
							},
							onClick() {
								let ConfigPreviewDialog = defineAsyncComponent(() =>
									import('../components/ConfigPreviewDialog.vue')
								);
								renderDialog(
									h(ConfigPreviewDialog, {
										configs: configs.data
									})
								);
							}
						};
					},
					rowActions({
						row,
						listResource: configs,
						documentResource: releaseGroup
					}) {
						return [
							{
								label: t('Edit'),
								onClick() {
									let ConfigEditorDialog = defineAsyncComponent(() =>
										import('../components/ConfigEditorDialog.vue')
									);
									renderDialog(
										h(ConfigEditorDialog, {
											group: releaseGroup.pg.name,
											config: row,
											onSuccess() {
												configs.reload();
											}
										})
									);
								}
							},
							{
								label: t('Delete'),
								onClick() {
									confirmDialog({
										title: t('Delete Config'),
										message: t('Are you sure you want to delete config <b>{key}</b>?', { key: row.key }),
										onSuccess({ hide }) {
											if (releaseGroup.deleteConfig.loading) return;
											toast.promise(
												releaseGroup.deleteConfig.submit(
													{ key: row.key },
													{
														onSuccess: () => {
															configs.reload();
															hide();
														}
													}
												),
												{
													loading: t('Deleting config...'),
													success: () => t('Config {key} deleted', { key: row.key }),
													error: e => getToastErrorMessage(e)
												}
											);
										}
									});
								}
							}
						];
					}
				}
			},
			{
				label: t('Actions'),
				icon: icon('sliders'),
				route: 'actions',
				type: 'Component',
				component: defineAsyncComponent(() =>
					import('../components/group/ReleaseGroupActions.vue')
				),
				props: releaseGroup => {
					return { releaseGroup: releaseGroup.name };
				}
			},
			{
				label: t('Region'),
				icon: icon('globe'),
				route: 'regions',
				type: 'list',
				list: {
					pagetype: 'Cluster',
					filters: releaseGroup => {
						return { group: releaseGroup.name };
					},
					columns: [
						{
							label: t('Region'),
							fieldname: 'title'
						},
						{
							label: t('Country'),
							fieldname: 'image',
							format(value, row) {
								return '';
							},
							prefix(row) {
								return h('img', {
									src: row.image,
									class: 'w-4 h-4',
									alt: row.title
								});
							}
						}
					],
					primaryAction({
						listResource: clusters,
						documentResource: releaseGroup
					}) {
						return {
							label: t('Add Region'),
							slots: {
								prefix: icon('plus')
							},
							onClick() {
								let AddRegionDialog = defineAsyncComponent(() =>
									import('../components/group/AddRegionDialog.vue')
								);
								renderDialog(
									h(AddRegionDialog, {
										group: releaseGroup.pg.name,
										onSuccess() {
											clusters.reload();
										}
									})
								);
							}
						};
					}
				}
			},
			getPatchesTab(false),
			{
				label: t('Dependencies'),
				icon: icon('box'),
				route: 'bench-dependencies',
				type: 'list',
				list: {
					pagetype: 'Release Group Dependency',
					filters: releaseGroup => {
						return {
							parenttype: 'Release Group',
							parent: releaseGroup.name
						};
					},
					columns: [
						{
							label: t('Dependencies'),
							fieldname: 'dependency',
							format(value, row) {
								return row.title;
							}
						},
						{
							label: t('Version'),
							fieldname: 'version',
							suffix(row) {
								if (!row.is_custom) {
									return;
								}

								return h(
									Tooltip,
									{
										text: t('Custom Version'),
										placement: 'top',
										class: 'rounded-full bg-gray-100 p-1'
									},
									() => h(icon('alert-circle', 'w-3 h-3'), {})
								);
							}
						}
					],
					rowActions({
						row,
						listResource: dependencies,
						documentResource: releaseGroup
					}) {
						return [
							{
								label: t('Edit'),
								onClick() {
									let DependencyEditorDialog = defineAsyncComponent(() =>
										import('../components/group/DependencyEditorDialog.vue')
									);
									renderDialog(
										h(DependencyEditorDialog, {
											group: releaseGroup.pg,
											dependency: row,
											onSuccess() {
												dependencies.reload();
											}
										})
									);
								}
							}
						];
					}
				}
			},
			{
				label: t('Environment'),
				icon: icon('tool'),
				route: 'bench-environment-variable',
				type: 'list',
				list: {
					pagetype: 'Release Group Variable',
					filters: releaseGroup => {
						return {
							parenttype: 'Release Group',
							parent: releaseGroup.name
						};
					},
					orderBy: 'creation desc',
					fields: ['name'],
					columns: [
						{
							label: t('Environment Variable Name'),
							fieldname: 'key'
						},
						{
							label: t('Environment Variable Value'),
							fieldname: 'value'
						}
					],
					primaryAction({
						listResource: environmentVariables,
						documentResource: releaseGroup
					}) {
						return {
							label: t('Add Environment Variable'),
							slots: {
								prefix: icon('plus')
							},
							onClick() {
								let EnvironmentVariableEditorDialog = defineAsyncComponent(() =>
									import('../components/EnvironmentVariableEditorDialog.vue')
								);
								renderDialog(
									h(EnvironmentVariableEditorDialog, {
										group: releaseGroup.pg.name,
										onSuccess() {
											environmentVariables.reload();
										}
									})
								);
							}
						};
					},
					rowActions({
						row,
						listResource: environmentVariables,
						documentResource: releaseGroup
					}) {
						return [
							{
								label: t('Edit'),
								onClick() {
									let ConfigEditorDialog = defineAsyncComponent(() =>
										import('../components/EnvironmentVariableEditorDialog.vue')
									);
									renderDialog(
										h(ConfigEditorDialog, {
											group: releaseGroup.pg.name,
											environment_variable: row,
											onSuccess() {
												environmentVariables.reload();
											}
										})
									);
								}
							},
							{
								label: t('Delete'),
								onClick() {
									confirmDialog({
										title: t('Delete Environment Variable'),
										message: t('Are you sure you want to delete environment variable <b>{key}</b>?', { key: row.key }),
										onSuccess({ hide }) {
											if (releaseGroup.deleteEnvironmentVariable.loading)
												return;
											toast.promise(
												releaseGroup.deleteEnvironmentVariable.submit(
													{ key: row.key },
													{
														onSuccess: () => {
															environmentVariables.reload();
															hide();
														}
													}
												),
												{
													loading: t('Deleting environment variable...'),
													success: () =>
														t('Environment variable {key} deleted', { key: row.key }),
													error: e => getToastErrorMessage(e)
												}
											);
										}
									});
								}
							}
						];
					}
				}
			},
			tagTab()
		],
		actions(context) {
			let { documentResource: group } = context;
			let team = getTeam();

			return [
				{
					label: t('Impersonate Group Owner'),
					title: t('Impersonate Group Owner'),
					slots: {
						icon: defineAsyncComponent(() =>
							import('~icons/lucide/venetian-mask')
						)
					},
					condition: () =>
						team.pg?.is_desk_user && group.pg.team !== team.name,
					onClick() {
						switchToTeam(group.pg.team);
					}
				},
				{
					label: group.pg?.deploy_information?.last_deploy
						? t('Update Available')
						: t('Deploy Now'),
					slots: {
						prefix: group.pg?.deploy_information?.last_deploy
							? icon(LucideHardDriveDownload)
							: icon(LucideRocket)
					},
					variant: 'solid',
					condition: () =>
						!group.pg.deploy_information.deploy_in_progress &&
						group.pg.deploy_information.update_available &&
						['Awaiting Deploy', 'Active'].includes(group.pg.status),
					onClick() {
						if (group.pg?.deploy_information?.last_deploy) {
							let UpdateReleaseGroupDialog = defineAsyncComponent(() =>
								import('../components/group/UpdateReleaseGroupDialog.vue')
							);
							renderDialog(
								h(UpdateReleaseGroupDialog, {
									bench: group.name,
									onSuccess(candidate) {
										group.pg.deploy_information.deploy_in_progress = true;
										if (candidate) {
											group.pg.deploy_information.last_deploy.name = candidate;
										}
									}
								})
							);
						} else {
							confirmDialog({
								title: t('Deploy'),
								message: t("Deploy now?"),
								onSuccess({ hide }) {
									toast.promise(
										group.initialDeploy.submit(null, {
											onSuccess: () => {
												group.reload();
												hide();
											}
										}),
										{
											success: t('Deployment scheduled successfully'),
											error: t('Deployment scheduling failed'),
											loading: t('Scheduling deployment...')
										}
									);
								}
							});
						}
					}
				},
				{
					label: t('Deployment in Progress'),
					slots: {
						prefix: () => h(LoadingIndicator, { class: 'w-4 h-4' })
					},
					theme: 'green',
					condition: () => group.pg.deploy_information.deploy_in_progress,
					route: {
						name: 'Deploy Candidate',
						params: { id: group.pg?.deploy_information?.last_deploy?.name }
					}
				},
				{
					label: t('Options'),
					condition: () => team.pg?.is_desk_user,
					options: [
						{
							label: t('View in Desk'),
							icon: icon('external-link'),
							condition: () => team.pg?.is_desk_user,
							onClick() {
								window.open(
									`${window.location.protocol}//${window.location.host}/app/release-group/${group.name}`,
									'_blank'
								);
							}
						}
					]
				}
			];
		}
	},
	routes: [
		{
			name: 'Deploy Candidate',
			path: 'deploys/:id',
			component: () => import('../pages/DeployCandidate.vue')
		},
		{
			name: 'Release Group Job',
			path: 'jobs/:id',
			component: () => import('../pages/JobPage.vue')
		}
	]
};