import { settingsApi } from '@/admin/api/settings';
import { settingsQuery } from '@/admin/queries/settings';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { __ } from '@wordpress/i18n';
import { Mail } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';

type Settings = Awaited<ReturnType<typeof settingsApi.get>>;
type TabFilter = 'client' | 'coach';

type NotificationRow =
	| {
			kind: 'field';
			fieldName: keyof typeof DEFAULT_NOTIFICATIONS;
			label: string;
			description: string;
	  }
	| {
			kind: 'soon';
			label: string;
			description: string;
	  };

const DEFAULT_NOTIFICATIONS = {
	welcome_client: false,
	new_booking_client: false,
	order_confirmed_client: false,
	order_cancelled_client: false,
	cancellation_notice_client: false,
	reminder_24h_client: false,
	session_booking_confirmation_client: false,
	session_completed_follow_up_client: false,
	new_booking_admin: false,
	session_cancelled_alert_admin: false,
};

const CLIENT_ROWS: NotificationRow[] = [
	{
		kind: 'field',
		fieldName: 'welcome_client',
		label: __('Welcome email', 'allcoach'),
		description: __(
			'Sent to client when their account is created.',
			'allcoach',
		),
	},
	{
		kind: 'field',
		fieldName: 'new_booking_client',
		label: __('New booking confirmation', 'allcoach'),
		description: __('Sent to client when a booking is received.', 'allcoach'),
	},
	{
		kind: 'field',
		fieldName: 'order_confirmed_client',
		label: __('Order confirmed', 'allcoach'),
		description: __(
			'Sent to client when their payment is verified.',
			'allcoach',
		),
	},
	{
		kind: 'field',
		fieldName: 'order_cancelled_client',
		label: __('Order cancelled', 'allcoach'),
		description: __(
			'Sent to client when their order is cancelled.',
			'allcoach',
		),
	},
	{
		kind: 'field',
		fieldName: 'cancellation_notice_client',
		label: __('Session cancellation notice', 'allcoach'),
		description: __('Sent to client when a session is cancelled.', 'allcoach'),
	},
	{
		kind: 'field',
		fieldName: 'reminder_24h_client',
		label: __('24-hour session reminder', 'allcoach'),
		description: __(
			'Sent to client 24 hours before a scheduled session.',
			'allcoach',
		),
	},
	{
		kind: 'field',
		fieldName: 'session_booking_confirmation_client',
		label: __('Session booking confirmation', 'allcoach'),
		description: __(
			'Sent to client immediately when a session is booked.',
			'allcoach',
		),
	},
	{
		kind: 'field',
		fieldName: 'session_completed_follow_up_client',
		label: __('Session completed follow-up', 'allcoach'),
		description: __(
			'Sent to client after a session is marked as completed.',
			'allcoach',
		),
	},
];

const COACH_ROWS: NotificationRow[] = [
	{
		kind: 'field',
		fieldName: 'new_booking_admin',
		label: __('New booking alert', 'allcoach'),
		description: __('Sent to admin when a new booking is placed.', 'allcoach'),
	},
	{
		kind: 'field',
		fieldName: 'session_cancelled_alert_admin',
		label: __('Session cancelled alert', 'allcoach'),
		description: __('Sent to admin when a session is cancelled.', 'allcoach'),
	},
];

const toFormValues = (settings: Settings) => ({
	sender_name: settings.email_sender_name ?? '',
	sender_email: settings.email_sender_email ?? '',
	notifications: {
		welcome_client: settings.notify_welcome_client ?? false,
		new_booking_client: settings.notify_new_booking_confirmation,
		order_confirmed_client: settings.notify_order_confirmed ?? false,
		order_cancelled_client: settings.notify_order_cancelled ?? false,
		cancellation_notice_client: settings.notify_cancellation_notice,
		reminder_24h_client: settings.notify_24_hour_reminder,
		session_booking_confirmation_client:
			settings.notify_session_booking_confirmation ?? false,
		session_completed_follow_up_client:
			settings.notify_session_completed_follow_up ?? false,
		new_booking_admin: settings.notify_new_booking_alert,
		session_cancelled_alert_admin:
			settings.notify_session_cancelled_alert ?? false,
	},
});

const EmailSettings = () => {
	const queryClient = useQueryClient();
	const [tab, setTab] = useState<TabFilter>('client');

	const { data: settings, isLoading } = useQuery({
		...settingsQuery(),
		retry: false,
	});

	const [senderName, setSenderName] = useState('');
	const [senderEmail, setSenderEmail] = useState('');
	const [notifications, setNotifications] = useState({
		...DEFAULT_NOTIFICATIONS,
	});

	const initialized = useRef(false);
	useEffect(() => {
		if (!settings || initialized.current) return;
		initialized.current = true;
		const values = toFormValues(settings);
		setSenderName(values.sender_name);
		setSenderEmail(values.sender_email);
		setNotifications(values.notifications);
	}, [settings]);

	const save = useMutation({
		mutationFn: () =>
			settingsApi.update({
				...settings,
				email_sender_name: senderName,
				email_sender_email: senderEmail,
				notify_welcome_client: notifications.welcome_client,
				notify_new_booking_confirmation: notifications.new_booking_client,
				notify_new_booking_alert: notifications.new_booking_admin,
				notify_cancellation_notice: notifications.cancellation_notice_client,
				notify_24_hour_reminder: notifications.reminder_24h_client,
				notify_order_confirmed: notifications.order_confirmed_client,
				notify_order_cancelled: notifications.order_cancelled_client,
				notify_session_booking_confirmation:
					notifications.session_booking_confirmation_client,
				notify_session_completed_follow_up:
					notifications.session_completed_follow_up_client,
				notify_session_cancelled_alert:
					notifications.session_cancelled_alert_admin,
			}),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ['settings'] });
			toast.success(__('Email settings saved.', 'allcoach'));
		},
		onError: () => {
			toast.error(__('Failed to save settings.', 'allcoach'));
		},
	});

	return (
		<div className="flex flex-col">
			{/* Header */}
			<div className="flex items-center gap-2 border-b border-gray-100 px-5 py-5 md:px-8">
				<Mail className="size-4 text-teal-600" />
				<h2 className="text-[15px] font-semibold text-gray-900">
					{__('Email', 'allcoach')}
				</h2>
			</div>

			{isLoading ? (
				<div className="space-y-6 px-5 py-6 md:px-8">
					<div>
						<Skeleton className="mb-4 h-4 w-16" />
						<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
							<div>
								<Skeleton className="mb-1.5 h-4 w-24" />
								<Skeleton className="h-9 w-full" />
							</div>
							<div>
								<Skeleton className="mb-1.5 h-4 w-24" />
								<Skeleton className="h-9 w-full" />
							</div>
						</div>
					</div>
					<Separator />
					<div>
						<Skeleton className="mb-1 h-4 w-24" />
						<Skeleton className="mb-3 h-3 w-56" />
						<Skeleton className="mb-4 h-8 w-40" />
						<div className="space-y-0 overflow-hidden rounded-lg border border-gray-200">
							{Array.from({ length: 4 }).map((_, i) => (
								<div
									key={i}
									className="flex items-center justify-between gap-4 border-b border-gray-100 px-5 py-3 last:border-0"
								>
									<div className="flex-1">
										<Skeleton className="mb-1 h-4 w-40" />
										<Skeleton className="h-3 w-64" />
									</div>
									<Skeleton className="h-5 w-9 shrink-0 rounded-full" />
								</div>
							))}
						</div>
					</div>
				</div>
			) : (
				<>
					<div className="space-y-6 px-5 py-6 md:px-8">
						{/* Sender */}
						<div>
							<p className="mb-4 text-[13px] font-semibold text-gray-900">
								{__('Sender', 'allcoach')}
							</p>
							<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
								<div>
									<Label className="mb-1.5 block text-[13px] font-medium text-gray-700">
										{__('Sender name', 'allcoach')}
									</Label>
									<Input
										placeholder={__('e.g. John Coach', 'allcoach')}
										value={senderName}
										onChange={(e) => setSenderName(e.target.value)}
										className="text-[13px]"
									/>
								</div>
								<div>
									<Label className="mb-1.5 block text-[13px] font-medium text-gray-700">
										{__('Sender email', 'allcoach')}
									</Label>
									<Input
										type="email"
										placeholder={__('e.g. hello@example.com', 'allcoach')}
										value={senderEmail}
										onChange={(e) => setSenderEmail(e.target.value)}
										className="text-[13px]"
									/>
								</div>
							</div>
						</div>

						<Separator />

						{/* Notifications */}
						<div>
							<p className="mb-0.5 text-[13px] font-semibold text-gray-900">
								{__('Notifications', 'allcoach')}
							</p>
							<p className="mb-3 text-[12px] text-gray-400">
								{__('Choose which automated emails are sent.', 'allcoach')}
							</p>

							{/* Client / Coach filter tabs */}
							<div className="mb-4 flex w-fit gap-1 rounded-lg border border-gray-200 bg-gray-50 p-1">
								{(['client', 'coach'] as const).map((t) => (
									<button
										key={t}
										type="button"
										onClick={() => setTab(t)}
										className={cn(
											'cursor-pointer rounded-md px-3 py-1 text-[12px] font-medium transition-colors',
											tab === t
												? 'bg-white text-gray-900 shadow-sm'
												: 'text-gray-500 hover:text-gray-700',
										)}
									>
										{t === 'client'
											? __('Client', 'allcoach')
											: __('Coach / Admin', 'allcoach')}
									</button>
								))}
							</div>

							<div className="divide-y divide-gray-100 overflow-hidden rounded-lg border border-gray-200">
								{CLIENT_ROWS.map((row, i) =>
									row.kind === 'field' ? (
										<div
											key={row.fieldName}
											className={cn(
												'flex items-center justify-between gap-4 px-5 py-3',
												tab !== 'client' && 'hidden',
											)}
										>
											<div>
												<p className="text-[13px] font-medium text-gray-800">
													{row.label}
												</p>
												<p className="text-[12px] text-gray-400">
													{row.description}
												</p>
											</div>
											<Switch
												checked={notifications[row.fieldName]}
												onCheckedChange={(checked) =>
													setNotifications((prev) => ({
														...prev,
														[row.fieldName]: checked,
													}))
												}
												className="shrink-0 cursor-pointer data-[state=checked]:!bg-teal-600"
											/>
										</div>
									) : (
										<div
											key={i}
											className={cn(
												'flex items-center justify-between gap-4 px-5 py-3',
												tab !== 'client' && 'hidden',
											)}
										>
											<div>
												<p className="text-[13px] font-medium text-gray-800">
													{row.label}
												</p>
												<p className="text-[12px] text-gray-400">
													{row.description}
												</p>
											</div>
											<Switch className="shrink-0 cursor-pointer data-[state=checked]:!bg-teal-600" />
										</div>
									),
								)}
								{COACH_ROWS.map((row, i) =>
									row.kind === 'field' ? (
										<div
											key={row.fieldName}
											className={cn(
												'flex items-center justify-between gap-4 px-5 py-3',
												tab !== 'coach' && 'hidden',
											)}
										>
											<div>
												<p className="text-[13px] font-medium text-gray-800">
													{row.label}
												</p>
												<p className="text-[12px] text-gray-400">
													{row.description}
												</p>
											</div>
											<Switch
												checked={notifications[row.fieldName]}
												onCheckedChange={(checked) =>
													setNotifications((prev) => ({
														...prev,
														[row.fieldName]: checked,
													}))
												}
												className="shrink-0 cursor-pointer data-[state=checked]:!bg-teal-600"
											/>
										</div>
									) : (
										<div
											key={i}
											className={cn(
												'flex items-center justify-between gap-4 px-5 py-3',
												tab !== 'coach' && 'hidden',
											)}
										>
											<div>
												<p className="text-[13px] font-medium text-gray-800">
													{row.label}
												</p>
												<p className="text-[12px] text-gray-400">
													{row.description}
												</p>
											</div>
											<Switch className="shrink-0 cursor-pointer data-[state=checked]:!bg-teal-600" />
										</div>
									),
								)}
							</div>
						</div>
					</div>

					{/* Footer */}
					<div className="flex justify-end gap-2 border-t border-gray-100 px-5 py-4 md:px-8">
						<Button
							type="button"
							size="sm"
							className="cursor-pointer text-[13px]"
							disabled={save.isPending}
							onClick={() => save.mutate()}
						>
							{save.isPending ? <Spinner className="size-3" /> : null}
							{__('Save', 'allcoach')}
						</Button>
					</div>
				</>
			)}
		</div>
	);
};

export default EmailSettings;
