import { Collapse, FormLabel, Skeleton, Stack, Switch } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { __ } from '@wordpress/i18n';
import React from 'react';
import { Controller, useFormContext, useWatch } from 'react-hook-form';
import AsyncSelect from '../../../../../assets/js/back-end/components/common/AsyncSelect';
import FormControlTwoCol from '../../../../../assets/js/back-end/components/common/FormControlTwoCol';
import { ProCheckboxForSettings } from '../../../../../assets/js/back-end/components/common/pro/ProShowcaseComponent';
import { reactSelectStyles } from '../../../../../assets/js/back-end/config/styles';
import ToolTip from '../../../../../assets/js/back-end/screens/settings/components/ToolTip';
import { CourseDataMap } from '../../../../../assets/js/back-end/types/course';
import { isEmpty } from '../../../../../assets/js/back-end/utils/utils';
import { getAllCertificates } from '../utils/certificates';
import { CertificateStatus } from '../utils/enums';

function groupCertificateOptions(certs: any[]) {
	const builder = certs.filter((c) => c.content_format === 'pdfdraft');
	const classic = certs.filter(
		(c) => !c.content_format || c.content_format === 'gutenberg',
	);
	const groups: any[] = [];
	if (builder.length) {
		groups.push({
			label: __('Certificate V2', 'learning-management-system'),
			options: builder.map((c) => ({ value: c.id, label: c.name })),
		});
	}
	if (classic.length) {
		groups.push({
			label: __('Classic Certificates', 'learning-management-system'),
			options: classic.map((c) => ({ value: c.id, label: c.name })),
		});
	}
	if (groups.length === 1) {
		return groups[0].options;
	}
	return groups;
}

interface Props {
	courseData?: CourseDataMap;
}

const CertificateCourseSettings: React.FC<Props> = (props) => {
	const { courseData } = props;
	const { register, control } = useFormContext();

	const isCertificateEnabled = useWatch({
		name: 'certificate_enabled',
		defaultValue: courseData?.certificate?.enabled,
		control,
	});

	const certificatesQuery = useQuery({
		queryKey: ['certificatesList'],
		queryFn: () =>
			getAllCertificates({
				order: 'desc',
				orderby: 'date',
				status: CertificateStatus.Publish,
				per_page: 10,
			}),
		...{
			enabled: isCertificateEnabled,
		},
	});

	return (
		<Stack direction="column" spacing={8}>
			<FormControlTwoCol>
				<FormLabel minW="160px">
					{__('Enable Certificate', 'learning-management-system')}
					<ToolTip
						label={__(
							'Allow students to get certificate after course completion.',
							'learning-management-system',
						)}
					/>
				</FormLabel>
				<Switch
					{...register('certificate_enabled')}
					defaultChecked={courseData?.certificate?.enabled}
				/>
			</FormControlTwoCol>

			{isCertificateEnabled && certificatesQuery.isLoading ? (
				<Skeleton height="40px" />
			) : null}
			{isCertificateEnabled && certificatesQuery.isSuccess ? (
				<Collapse in={isCertificateEnabled}>
					<Stack direction={'column'} gap={8}>
						<FormControlTwoCol>
							<FormLabel minW="160px" mb={0}>
								{__('Select Certificate', 'learning-management-system')}
								<ToolTip
									label={__(
										'Select which certificate to use for this course.',
										'learning-management-system',
									)}
								/>
							</FormLabel>
							<Controller
								name="certificate_id"
								control={control}
								defaultValue={
									courseData?.certificate?.id
										? {
												value: courseData.certificate.id,
												label: courseData.certificate.name,
											}
										: undefined
								}
								render={({ field: { onChange, value } }) => (
									<AsyncSelect
										styles={{
											...reactSelectStyles,
										}}
										cacheOptions={true}
										loadingMessage={() =>
											__('Searching...', 'learning-management-system')
										}
										noOptionsMessage={({ inputValue }) =>
											!isEmpty(inputValue)
												? __(
														'Certificate not found.',
														'learning-management-system',
													)
												: __(
														'Please enter one or more characters.',
														'learning-management-system',
													)
										}
										isClearable={true}
										placeholder={__(
											'Search certificate...',
											'learning-management-system',
										)}
										value={value}
										onChange={onChange}
										defaultOptions={
											certificatesQuery.isSuccess
												? groupCertificateOptions(
														certificatesQuery.data?.data ?? [],
													)
												: []
										}
										loadOptions={(searchValue, callback) => {
											if (isEmpty(searchValue)) {
												return callback([]);
											}
											getAllCertificates({
												search: searchValue,
												order: 'desc',
												orderby: 'date',
												status: CertificateStatus.Publish,
												per_page: -1,
											}).then((data) => {
												callback(groupCertificateOptions(data.data));
											});
										}}
									/>
								)}
							/>
						</FormControlTwoCol>

						<ProCheckboxForSettings
							label={__(
								'Send Certificate via Email',
								'learning-management-system',
							)}
						/>

						<FormControlTwoCol>
							<Stack direction="row">
								<FormLabel minW="160px">
									{__(
										'Allow Certificate Sharing',
										'learning-management-system',
									)}
									<ToolTip
										label={__(
											'Allow students to view/share certificate from single course page after course completion.',
											'learning-management-system',
										)}
									/>
								</FormLabel>
								<Switch
									{...register('certificate_single_course_enabled')}
									defaultChecked={
										courseData?.certificate?.single_course_enabled
									}
								/>
							</Stack>
						</FormControlTwoCol>
					</Stack>
				</Collapse>
			) : null}
			{isCertificateEnabled && certificatesQuery.isLoading ? (
				<Skeleton height="40px" />
			) : null}
		</Stack>
	);
};

export default CertificateCourseSettings;
