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 {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from '@/components/ui/select';
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 { Textarea } from '@/components/ui/textarea';
import { useForm } from '@tanstack/react-form';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { __ } from '@wordpress/i18n';
import { CreditCard } from 'lucide-react';
import { useEffect } from 'react';
import { toast } from 'sonner';

const CURRENCIES = __ALLCOACH_ADMIN__.currencies.map((c) => ({
	value: c.code,
	label: `${c.code} – ${c.name} (${c.symbol})`,
}));

const FUTURE_METHODS = [
	{
		name: 'Stripe',
		description: __('Online card payments via Stripe.', 'allcoach'),
	},
];

const PaymentSettings = () => {
	const queryClient = useQueryClient();

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

	const form = useForm({
		defaultValues: {
			currency: 'USD',
			offline_payment: {
				enabled: true,
				title: 'Pay in person',
				description: 'Pay at the time of your session.',
			},
		},
	});

	useEffect(() => {
		if (!settings) return;
		form.reset({
			currency: settings.currency ?? 'USD',
			offline_payment: {
				enabled: settings.payment_offline_enabled ?? true,
				title: settings.payment_offline_title ?? 'Pay in person',
				description:
					settings.payment_offline_description ??
					'Pay at the time of your session.',
			},
		});
	}, [settings]);

	const save = useMutation({
		mutationFn: (values: typeof form.state.values) =>
			settingsApi.update({
				...settings,
				currency: values.currency,
				payment_offline_enabled: values.offline_payment.enabled,
				payment_offline_title: values.offline_payment.title,
				payment_offline_description: values.offline_payment.description,
			}),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ['settings'] });
			toast.success(__('Payment 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">
				<CreditCard className="size-4 text-teal-600" />
				<h2 className="text-[15px] font-semibold text-gray-900">
					{__('Payment', 'allcoach')}
				</h2>
			</div>

			{isLoading ? (
				<div className="space-y-6 px-5 py-6 md:px-8">
					<div>
						<Skeleton className="mb-1.5 h-4 w-20" />
						<Skeleton className="h-9 w-full sm:w-64" />
					</div>
					<Separator />
					<div>
						<Skeleton className="mb-1 h-4 w-32" />
						<Skeleton className="mb-5 h-3 w-64" />
						<div className="overflow-hidden rounded-lg border border-gray-200">
							<div className="flex items-center justify-between px-5 py-4">
								<div>
									<Skeleton className="mb-1 h-4 w-32" />
									<Skeleton className="h-3 w-56" />
								</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">
						{/* Currency */}
						<div>
							<Label className="mb-1.5 block text-[13px] font-semibold text-gray-900">
								{__('Currency', 'allcoach')}
							</Label>
							<form.Field name="currency">
								{(field) => (
									<Select
										value={field.state.value}
										onValueChange={field.handleChange}
									>
										<SelectTrigger className="w-full text-[13px] sm:w-64">
											<SelectValue />
										</SelectTrigger>
										<SelectContent className="!z-[999999]">
											{CURRENCIES.map((c) => (
												<SelectItem
													key={c.value}
													value={c.value}
													className="text-[13px]"
												>
													{c.label}
												</SelectItem>
											))}
										</SelectContent>
									</Select>
								)}
							</form.Field>
						</div>

						<Separator />

						{/* Payment methods */}
						<div>
							<p className="mb-1 text-[13px] font-semibold text-gray-900">
								{__('Payment methods', 'allcoach')}
							</p>
							<p className="mb-5 text-[12px] text-gray-400">
								{__(
									'Choose which payment methods clients can use.',
									'allcoach',
								)}
							</p>

							{/* Offline payment */}
							<div className="overflow-hidden rounded-lg border border-gray-200">
								<div className="flex items-center justify-between px-5 py-4">
									<div>
										<p className="text-[13px] font-semibold text-gray-900">
											{__('Offline payment', 'allcoach')}
										</p>
										<p className="text-[12px] text-gray-400">
											{__('Accept payment outside the platform.', 'allcoach')}
										</p>
									</div>
									<form.Field name="offline_payment.enabled">
										{(field) => (
											<Switch
												checked={field.state.value}
												onCheckedChange={field.handleChange}
												className="cursor-pointer data-[state=checked]:!bg-teal-600"
											/>
										)}
									</form.Field>
								</div>

								<form.Subscribe
									selector={(s) => s.values.offline_payment.enabled}
								>
									{(enabled) =>
										enabled && (
											<div className="space-y-4 border-t border-gray-100 bg-gray-50 px-5 py-4">
												<form.Field name="offline_payment.title">
													{(field) => (
														<div>
															<Label className="mb-1.5 block text-[13px] font-medium text-gray-700">
																{__('Title', 'allcoach')}
															</Label>
															<Input
																placeholder={__(
																	'e.g. Pay in person',
																	'allcoach',
																)}
																value={field.state.value}
																onChange={(e) =>
																	field.handleChange(e.target.value)
																}
																onBlur={field.handleBlur}
																className="bg-white text-[13px]"
															/>
														</div>
													)}
												</form.Field>
												<form.Field name="offline_payment.description">
													{(field) => (
														<div>
															<Label className="mb-1.5 block text-[13px] font-medium text-gray-700">
																{__('Description', 'allcoach')}
															</Label>
															<Textarea
																placeholder={__(
																	'Instructions shown to the client at checkout.',
																	'allcoach',
																)}
																value={field.state.value}
																onChange={(e) =>
																	field.handleChange(e.target.value)
																}
																onBlur={field.handleBlur}
																rows={3}
																className="resize-none bg-white text-[13px]"
															/>
														</div>
													)}
												</form.Field>
											</div>
										)
									}
								</form.Subscribe>
							</div>

							{/* Future methods */}
							{FUTURE_METHODS.map(({ name, description }) => (
								<div
									key={name}
									className="mt-3 flex items-center justify-between rounded-lg border border-dashed border-gray-200 px-5 py-4"
								>
									<div>
										<div className="flex items-center gap-2">
											<p className="text-[13px] font-semibold text-gray-400">
												{name}
											</p>
											<span className="rounded-full bg-gray-100 px-1.5 py-0.5 text-[10px] leading-none font-semibold tracking-wider text-gray-400 uppercase">
												Coming soon
											</span>
										</div>
										<p className="text-[12px] text-gray-300">{description}</p>
									</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 bg-teal-600 text-[13px] hover:bg-teal-700"
							disabled={save.isPending}
							onClick={() => save.mutate(form.state.values)}
						>
							{save.isPending ? <Spinner className="size-3" /> : null}
							{__('Save', 'allcoach')}
						</Button>
					</div>
				</>
			)}
		</div>
	);
};

export default PaymentSettings;
