import type { Client, CreateClientData } from '@/admin/api/clients';
import { clientsApi } from '@/admin/api/clients';
import { Button } from '@/components/ui/button';
import {
	Dialog,
	DialogContent,
	DialogFooter,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
	Select,
	SelectContent,
	SelectGroup,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import { useForm } from '@tanstack/react-form';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { dateI18n, getSettings } from '@wordpress/date';
import { __ } from '@wordpress/i18n';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

const TIMEZONES = __ALLCOACH_ADMIN__.timezones.map((tz) => ({
	value: tz.value,
	label: tz.text,
}));

const DEFAULT_VALUES = {
	firstName: '',
	lastName: '',
	email: '',
	phone: '',
	timezone: '',
};

interface ClientDialogProps {
	trigger?: React.ReactNode;
	editTarget?: Client | null;
}

const ClientDialog = ({ trigger, editTarget = null }: ClientDialogProps) => {
	const [open, setOpen] = useState(false);
	const queryClient = useQueryClient();
	const form = useForm({ defaultValues: DEFAULT_VALUES });

	useEffect(() => {
		if (open && editTarget) {
			form.setFieldValue('firstName', editTarget.first_name);
			form.setFieldValue('lastName', editTarget.last_name);
			form.setFieldValue('email', editTarget.email);
			form.setFieldValue('phone', editTarget.phone ?? '');
			form.setFieldValue('timezone', editTarget.timezone ?? '');
		} else if (open) {
			form.reset();
		}
	}, [open, editTarget]);

	const buildPayload = (): CreateClientData => {
		const v = form.state.values;
		return {
			first_name: v.firstName.trim(),
			last_name: v.lastName.trim(),
			email: v.email.trim(),
			phone: v.phone.trim() || undefined,
			timezone: v.timezone || undefined,
		};
	};

	const saveClient = useMutation({
		mutationFn: () =>
			editTarget
				? clientsApi.update(editTarget.id, buildPayload())
				: clientsApi.create(buildPayload()),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ['clients'] });
			toast.success(
				editTarget
					? __('Client updated.', 'allcoach')
					: __('Client added.', 'allcoach'),
			);
			setOpen(false);
		},
		onError: () => {
			toast.error(__('Failed to save client. Please try again.', 'allcoach'));
		},
	});

	return (
		<Dialog open={open} onOpenChange={setOpen}>
			{trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}
			<DialogContent className="flex max-h-[90svh] flex-col overflow-hidden sm:max-w-md">
				<DialogHeader className="gap-0.5">
					<DialogTitle>
						{editTarget
							? __('Edit Client', 'allcoach')
							: __('Add Client', 'allcoach')}
					</DialogTitle>
					{editTarget && (
						<p className="text-xs text-gray-400">
							{dateI18n(getSettings().formats.date, editTarget.created_at)}{' '}
							{dateI18n(getSettings().formats.time, editTarget.created_at)}
						</p>
					)}
				</DialogHeader>

				<div className="flex flex-col gap-4 overflow-y-auto py-2 pe-0.5">
					{/* First Name + Last Name */}
					<div className="grid grid-cols-2 gap-3">
						<form.Field name="firstName">
							{(field) => (
								<div className="flex flex-col gap-1.5">
									<Label htmlFor="client-first-name">
										{__('First Name', 'allcoach')}
									</Label>
									<Input
										id="client-first-name"
										value={field.state.value}
										onChange={(e) => field.handleChange(e.target.value)}
										onBlur={field.handleBlur}
										placeholder={__('Jane', 'allcoach')}
									/>
								</div>
							)}
						</form.Field>

						<form.Field name="lastName">
							{(field) => (
								<div className="flex flex-col gap-1.5">
									<Label htmlFor="client-last-name">
										{__('Last Name', 'allcoach')}
									</Label>
									<Input
										id="client-last-name"
										value={field.state.value}
										onChange={(e) => field.handleChange(e.target.value)}
										onBlur={field.handleBlur}
										placeholder={__('Doe', 'allcoach')}
									/>
								</div>
							)}
						</form.Field>
					</div>

					{/* Email */}
					<form.Field name="email">
						{(field) => (
							<div className="flex flex-col gap-1.5">
								<Label htmlFor="client-email">
									{__('Email', 'allcoach')}{' '}
									<span className="text-red-500">*</span>
								</Label>
								<Input
									id="client-email"
									value={field.state.value}
									onChange={(e) => field.handleChange(e.target.value)}
									onBlur={field.handleBlur}
									placeholder={__('jane@example.com', 'allcoach')}
								/>
							</div>
						)}
					</form.Field>

					{/* Phone */}
					<form.Field name="phone">
						{(field) => (
							<div className="flex flex-col gap-1.5">
								<Label htmlFor="client-phone">
									{__('Phone Number', 'allcoach')}
								</Label>
								<Input
									id="client-phone"
									value={field.state.value}
									onChange={(e) => field.handleChange(e.target.value)}
									onBlur={field.handleBlur}
									placeholder={__('+ 1 555 000 0000', 'allcoach')}
								/>
							</div>
						)}
					</form.Field>

					<form.Field name="timezone">
						{(field) => (
							<div className="flex flex-col gap-1.5">
								<Label htmlFor="client-timezone">
									{__('Time Zone', 'allcoach')}
								</Label>
								<Select
									value={field.state.value}
									onValueChange={field.handleChange}
								>
									<SelectTrigger id="client-timezone" className="w-full">
										<SelectValue
											placeholder={__('Select time zone…', 'allcoach')}
										/>
									</SelectTrigger>
									<SelectContent className="!z-[999999] max-h-60">
										<SelectGroup>
											{TIMEZONES.map((tz) => (
												<SelectItem key={tz.value} value={tz.value}>
													{tz.label}
												</SelectItem>
											))}
										</SelectGroup>
									</SelectContent>
								</Select>
							</div>
						)}
					</form.Field>
				</div>

				<DialogFooter>
					<Button
						variant="outline"
						className="cursor-pointer"
						onClick={() => setOpen(false)}
					>
						{__('Cancel', 'allcoach')}
					</Button>
					<form.Subscribe selector={(s) => s.values}>
						{(values) => (
							<Button
								className="cursor-pointer"
								disabled={
									!values.firstName.trim() ||
									!values.email.trim() ||
									saveClient.isPending
								}
								onClick={() => saveClient.mutate()}
							>
								{saveClient.isPending && <Spinner />}
								{editTarget
									? __('Save Changes', 'allcoach')
									: __('Add Client', 'allcoach')}
							</Button>
						)}
					</form.Subscribe>
				</DialogFooter>
			</DialogContent>
		</Dialog>
	);
};

export default ClientDialog;
