import { googleApi } from '@/admin/api/google';
import {
	googleCredentialsQuery,
	googleStatusQuery,
} from '@/admin/queries/google';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
	AlertDialog,
	AlertDialogAction,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { FileDropZone } from '@/components/ui/file-drop-zone';
import { Skeleton } from '@/components/ui/skeleton';
import { Spinner } from '@/components/ui/spinner';
import copy from '@/lib/copy-to-clipboard';
import { emitGoogleIntegration } from '@/lib/event';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { __ } from '@wordpress/i18n';
import { CalendarCheck, Copy, Info, Lock, X } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';

const GoogleMeetSettings = () => {
	const queryClient = useQueryClient();
	const [confirmOpen, setConfirmOpen] = useState(false);
	const [confirmRemoveOpen, setConfirmRemoveOpen] = useState(false);
	const isAdmin = __ALLCOACH_ADMIN__.isAdmin;

	const { data: credentials, isLoading: credentialsLoading } = useQuery({
		...googleCredentialsQuery(),
		retry: false,
		enabled: () => isAdmin,
	});

	const { data: status, isLoading: statusLoading } = useQuery({
		...googleStatusQuery(),
		retry: false,
	});

	// Handle redirect back from Google OAuth
	useEffect(() => {
		const params = new URLSearchParams(window.location.search);
		if (params.get('allcoach_google_connected') === '1') {
			queryClient.invalidateQueries({ queryKey: ['google-status'] });
			toast.success(__('Google account connected successfully.', 'allcoach'));
			const url = new URL(window.location.href);
			url.searchParams.delete('allcoach_google_connected');
			window.history.replaceState({}, '', url.toString());
		}
		const error = params.get('allcoach_google_error');
		if (error) {
			toast.error(decodeURIComponent(error));
			const url = new URL(window.location.href);
			url.searchParams.delete('allcoach_google_error');
			window.history.replaceState({}, '', url.toString());
		}
	}, []);

	const uploadCredentials = useMutation({
		mutationFn: (data: FormData) => googleApi.uploadCredentials(data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ['google-status'] });
			toast.success(__('Google credentials saved.', 'allcoach'));
			emitGoogleIntegration({ type: 'configured', value: true });
		},
		onError: () => {
			toast.error(__('Failed to save credentials.', 'allcoach'));
			emitGoogleIntegration({ type: 'configured', value: false });
		},
	});

	const removeCredentials = useMutation({
		mutationFn: () => googleApi.deleteCredentials(),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ['settings'] });
			queryClient.invalidateQueries({ queryKey: ['google-status'] });
			emitGoogleIntegration({ type: 'configured', value: false });
		},
	});

	const connect = useMutation({
		mutationFn: googleApi.getAuthUrl,
		onSuccess: ({ url }) => {
			window.location.href = url;
			emitGoogleIntegration({ type: 'connected', value: true });
		},
		onError: () => {
			toast.error(__('Failed to get Google authorization URL.', 'allcoach'));
			emitGoogleIntegration({ type: 'connected', value: false });
		},
	});

	const disconnect = useMutation({
		mutationFn: googleApi.disconnect,
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ['google-status'] });
			toast.success(__('Google account disconnected.', 'allcoach'));
			emitGoogleIntegration({ type: 'connected', value: false });
		},
		onError: () => {
			toast.error(__('Failed to disconnect Google account.', 'allcoach'));
		},
	});

	const handleFile = useCallback(
		(file: File) => {
			if (!file.name.endsWith('.json')) {
				toast.error(__('Please drop a valid JSON file.', 'allcoach'));
				return;
			}
			const formData = new FormData();
			formData.append('credentials_file', file);
			uploadCredentials.mutate(formData);
		},
		[uploadCredentials],
	);

	const hasCredentials = status?.configured ?? false;
	const connected = status?.connected ?? false;

	const handleCopy = useCallback(async () => {
		try {
			await copy(__ALLCOACH_ADMIN__.googleCallbackUrl);
			toast.success(__('Redirect URL copied to clipboard.', 'allcoach'));
		} catch {
			toast.error(__('Failed to copy URL.', '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">
					<CalendarCheck className="size-4 text-teal-600" />
					<h2 className="text-[15px] font-semibold text-gray-900">
						{__('Google Meet / Calendar', 'allcoach')}
					</h2>
				</div>

				<div className="flex flex-col gap-4 px-5 py-6 md:px-8">
					{/* Step 1 — Credentials */}
					{isAdmin ? (
						<>
							<div className="rounded-lg border border-gray-200 px-6 py-5">
								<div className="mb-4 flex items-center justify-between">
									<div>
										<p className="text-[13px] font-semibold text-gray-900">
											{__('Step 1 — OAuth Credentials', 'allcoach')}
										</p>
										<p className="mt-0.5 text-[12px] text-gray-400">
											{__(
												'Download the OAuth 2.0 Client ID JSON from',
												'allcoach',
											)}{' '}
											<a
												href="https://console.cloud.google.com/apis/credentials"
												target="_blank"
												rel="noopener noreferrer"
												className="!text-teal-600 !underline underline-offset-2 hover:!text-teal-700"
											>
												{__('Google Cloud Console', 'allcoach')}
											</a>{' '}
											{__('and drop it below.', 'allcoach')}
										</p>
									</div>
									{hasCredentials && (
										<button
											type="button"
											className="flex cursor-pointer items-center gap-1 rounded-md border border-gray-200 px-2 py-1 text-[11px] text-gray-500 hover:border-red-200 hover:text-red-500"
											onClick={() => setConfirmRemoveOpen(true)}
										>
											<X className="size-3" />
											{__('Remove', 'allcoach')}
										</button>
									)}
								</div>

								{credentialsLoading ? (
									<Skeleton className="h-11 w-full rounded-md" />
								) : hasCredentials ? (
									<div className="flex items-center gap-2 rounded-md bg-teal-50 px-4 py-3">
										<span className="inline-block size-1.5 shrink-0 rounded-full bg-teal-500" />
										<span className="text-[12px] text-teal-700">
											{__('Credentials configured', 'allcoach')}
										</span>
										<span className="ms-auto max-w-[260px] truncate text-[11px] text-gray-400">
											{credentials?.client_id}
										</span>
									</div>
								) : (
									<FileDropZone
										id="google-creds-input"
										accept=".json"
										isLoading={uploadCredentials.isPending}
										label={__('Drop credentials JSON here', 'allcoach')}
										hint={__('or click to browse', 'allcoach')}
										onFile={handleFile}
									/>
								)}
							</div>
							{/* Step 2 — Authorized redirect URI */}
							<div className="rounded-lg border border-gray-200 px-6 py-5">
								<p className="text-[13px] font-semibold text-gray-900">
									{__('Step 2 — Authorized Redirect URI', 'allcoach')}
								</p>
								<Alert>
									<Info />
									<AlertDescription>
										{__(
											'Add this URI to your Google Cloud Console under',
											'allcoach',
										)}{' '}
										<strong>
											{__(
												'OAuth 2.0 Client → Authorized redirect URIs',
												'allcoach',
											)}
										</strong>
										{__(', then save the client.', 'allcoach')}
									</AlertDescription>
								</Alert>
								<p className="mt-2.5 text-[12px] text-gray-400">
									{__(
										'Copy the URI below and paste it into your Google app credentials before connecting your account.',
										'allcoach',
									)}
								</p>
								<div className="mt-2.5 flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2">
									<span className="flex-1 truncate font-mono text-[11px] text-gray-600">
										{__ALLCOACH_ADMIN__.googleCallbackUrl}
									</span>
									<button
										type="button"
										onClick={handleCopy}
										className="flex shrink-0 cursor-pointer items-center gap-1 rounded px-2 py-1 text-[11px] text-gray-500 hover:bg-gray-100 hover:text-gray-700"
									>
										<Copy className="size-3" />
										{__('Copy', 'allcoach')}
									</button>
								</div>
							</div>
						</>
					) : (
						<div className="pointer-events-none relative rounded-lg border border-gray-200 px-6 py-5 opacity-50 select-none">
							<div className="flex items-center gap-2">
								<Lock className="size-3.5 text-gray-400" />
								<p className="text-[13px] font-semibold text-gray-900">
									{__('Step 1 — OAuth Credentials', 'allcoach')}
								</p>
							</div>
							<p className="mt-1 text-[12px] text-gray-400">
								{__('Configured by your administrator.', 'allcoach')}
							</p>
						</div>
					)}

					{/* Step 3 — Connect Account */}
					{hasCredentials && (
						<div className="rounded-lg border border-gray-200 px-6 py-5">
							<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between sm:gap-6">
								<div>
									<p className="text-[13px] font-semibold text-gray-900">
										{__('Step 3 — Connect Google Account', 'allcoach')}
									</p>
									<p className="mt-0.5 text-[12px] text-gray-400">
										{__(
											'Authorize access to Google Calendar to enable Meet links for appointments.',
											'allcoach',
										)}
									</p>
									<div className="mt-3 flex items-center gap-1.5">
										{statusLoading ? (
											<Spinner className="size-3" />
										) : connected ? (
											<>
												<span className="inline-block size-1.5 rounded-full bg-teal-500" />
												<span className="text-[12px] text-teal-600">
													{__('Connected', 'allcoach')}
													{status?.email ? ` · ${status.email}` : ''}
												</span>
											</>
										) : (
											<>
												<span className="inline-block size-1.5 rounded-full bg-gray-400" />
												<span className="text-[12px] text-gray-500">
													{__('Not connected', 'allcoach')}
												</span>
											</>
										)}
									</div>
								</div>

								{!statusLoading &&
									(connected ? (
										<Button
											type="button"
											size="sm"
											variant="outline"
											className="shrink-0 cursor-pointer text-[13px] text-red-600 hover:border-red-300 hover:text-red-600"
											disabled={disconnect.isPending}
											onClick={() => setConfirmOpen(true)}
										>
											{disconnect.isPending ? (
												<Spinner className="size-3" />
											) : null}
											{__('Disconnect', 'allcoach')}
										</Button>
									) : (
										<Button
											type="button"
											size="sm"
											variant="outline"
											className="shrink-0 cursor-pointer text-[13px]"
											disabled={connect.isPending}
											onClick={() => connect.mutate()}
										>
											{connect.isPending ? (
												<Spinner className="size-3" />
											) : null}
											{__('Connect Google Account', 'allcoach')}
										</Button>
									))}
							</div>
						</div>
					)}
				</div>
			</div>

			<AlertDialog open={confirmRemoveOpen} onOpenChange={setConfirmRemoveOpen}>
				<AlertDialogContent>
					<AlertDialogHeader>
						<AlertDialogTitle>
							{__('Remove OAuth Credentials', 'allcoach')}
						</AlertDialogTitle>
						<AlertDialogDescription>
							{__(
								'Are you sure you want to remove the OAuth credentials? Google Meet and Calendar integration will stop working.',
								'allcoach',
							)}
						</AlertDialogDescription>
					</AlertDialogHeader>
					<AlertDialogFooter>
						<AlertDialogCancel className="cursor-pointer">
							{__('Cancel', 'allcoach')}
						</AlertDialogCancel>
						<AlertDialogAction
							className="cursor-pointer bg-red-600 hover:bg-red-700"
							onClick={() => removeCredentials.mutate()}
						>
							{__('Remove', 'allcoach')}
						</AlertDialogAction>
					</AlertDialogFooter>
				</AlertDialogContent>
			</AlertDialog>

			<AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
				<AlertDialogContent>
					<AlertDialogHeader>
						<AlertDialogTitle>
							{__('Disconnect Google Account', 'allcoach')}
						</AlertDialogTitle>
						<AlertDialogDescription>
							{__(
								'Are you sure you want to disconnect your Google account? Calendar sync and Meet links will stop working for new appointments.',
								'allcoach',
							)}
						</AlertDialogDescription>
					</AlertDialogHeader>
					<AlertDialogFooter>
						<AlertDialogCancel className="cursor-pointer">
							{__('Cancel', 'allcoach')}
						</AlertDialogCancel>
						<AlertDialogAction
							className="cursor-pointer bg-red-600 hover:bg-red-700"
							onClick={() => disconnect.mutate()}
						>
							{__('Disconnect', 'allcoach')}
						</AlertDialogAction>
					</AlertDialogFooter>
				</AlertDialogContent>
			</AlertDialog>
		</>
	);
};

export default GoogleMeetSettings;
