"use client";

import React, { useEffect, useMemo, useState } from "react";
import { useForm, useWatch } from "react-hook-form";

type PassedAway =
	| "Yes, they have passed away"
	| "Not yet, but they are close to passing"
	| "No, I am planning for the future";

type Role =
	| "Heir of Estate"
	| "Trustee"
	| "Attorney"
	| "Real Estate Agent"
	| "Other Party";

type EstateValue =
	| "Less than $50,000"
	| "$50,000 - $250,000"
	| "$250,000 - $500,000"
	| "$500,000 - $1 Million"
	| "$1 Million - $5 Million"
	| "Over $5 Million";

type FamilyConflict =
	| "Family members dispute the validity of the will or trust (e.g., forged or multiple versions exist)"
	| "Family members disagree over who should be in charge"
	| "There is disagreement about how the assets should be divided"
	| "Someone suspects that assets are hidden, misused, or missing"
	| "The executor or trustee is not acting fairly or efficiently"
	| "None of the above";

const US_STATES = [
	"Alabama","Alaska","Arizona","Arkansas","California","Colorado",
	"Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho",
	"Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana",
	"Maine","Maryland","Massachusetts","Michigan","Minnesota",
	"Mississippi","Missouri","Montana","Nebraska","Nevada",
	"New Hampshire","New Jersey","New Mexico","New York",
	"North Carolina","North Dakota","Ohio","Oklahoma","Oregon",
	"Pennsylvania","Rhode Island","South Carolina","South Dakota",
	"Tennessee","Texas","Utah","Vermont","Virginia","Washington",
	"West Virginia","Wisconsin","Wyoming"
];

type FormValues = {
	// passedAway: PassedAway;
	estateValue: EstateValue;
	roles: Role;

	fullName: string;
	estateName?: string;
	city: string;
	state: string;
	propertyAddress?: string;

	familyConflict: FamilyConflict;

	lovedOneName?: string;
	relationship: string;
	lovedOneState: string;
	yourState: string;

	helpMessage: string;

	firstName: string;
	lastName: string;
	phone: string;
	email: string;
};

const defaultValues: Partial<FormValues> = {
	// passedAway: undefined,
	estateValue: undefined,
	roles: undefined,
	fullName: "",

	phone: "",
	email: "",
	estateName: "",
	city: "",
	state: "",
	propertyAddress: "",

	familyConflict: undefined,

	lovedOneName: "",
	relationship: "",
	lovedOneState: "",
	yourState: "",

	helpMessage: "",

	firstName: "",
	lastName: "",
	// phone: "",
	// email: "",
};

export function ContactForm({
	open,
	onClose,
}: {
	open: boolean;
	onClose: () => void;
}) {
	const [step, setStep] = useState<1 | 2 | 3 | 4 | 5 | 6>(1);
	const [status, setStatus] = useState<
		"idle" | "loading" | "success" | "error"
	>("idle");
	const [errorMsg, setErrorMsg] = useState("");

	const {
		register,
		handleSubmit,
		trigger,
		reset,
		formState: { errors },
		control,
		setValue,
	} = useForm<FormValues>({
		defaultValues: defaultValues as FormValues,
		mode: "onTouched",
	});

	// reset when opened
	useEffect(() => {
		if (!open) return;
		setStatus("idle");
		setErrorMsg("");
		setStep(1);
	}, [open]);

	// ESC to close
	useEffect(() => {
		function onEsc(e: KeyboardEvent) {
			if (e.key === "Escape") onClose();
		}
		if (open) document.addEventListener("keydown", onEsc);
		return () => document.removeEventListener("keydown", onEsc);
	}, [open, onClose]);

	const passedAway = useWatch({ control, name: "passedAway" });
	const estateValue = useWatch({ control, name: "estateValue" });
	const familyConflict = useWatch({ control, name: "familyConflict" });

	const stepFields = useMemo(() => {
		return {
			1: ["role","fullName","phone","email","city","state"],
			// 2: ["familyConflict"],
			// 1: ["passedAway"] as const,
			2: ["estateValue"] as const,
			3: ["familyConflict"] as const,
			4: ["relationship", "lovedOneState", "yourState"] as const, // lovedOneName optional
			5: ["helpMessage"] as const,
			6: ["firstName", "lastName", "phone", "email"] as const,
		};
	}, []);

	const nextStep = async () => {
		const fields = stepFields[step];
		const ok = await trigger(fields as any);
		if (!ok) return;
		setStep(prev => (prev === 6 ? 6 : ((prev + 1) as any)));
	};

	const prevStep = () => {
		setStep(prev => (prev === 1 ? 1 : ((prev - 1) as any)));
	};

	const onSubmit = async (data: FormValues) => {
		setStatus("loading");
		setErrorMsg("");

		// final validation
		const allOk = await trigger(
			[
				"passedAway",
				"estateValue",
				"familyConflict",
				"relationship",
				"lovedOneState",
				"yourState",
				"helpMessage",
				"firstName",
				"lastName",
				"phone",
				"email",
			] as any,
			{ shouldFocus: true },
		);

		if (!allOk) {
			setStatus("error");
			setErrorMsg("Please fix the highlighted fields.");
			return;
		}

		try {
			const res = await fetch("/api/lead", {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(data),
			});

			if (!res.ok) {
				const j = await res.json().catch(() => ({}));
				throw new Error(j?.error || "Submission failed.");
			}

			setStatus("success");
			reset(defaultValues as FormValues);
			setStep(1);
		} catch (e: any) {
			setStatus("error");
			setErrorMsg(e?.message || "Something went wrong.");
		}
	};

	const role = useWatch({ control, name: "role" });

	if (!open) return null;

	return (
		<div className="fixed inset-0 z-50">
			{/* Backdrop */}
			<button
				type="button"
				aria-label="Close overlay"
				onClick={onClose}
				className="absolute inset-0 h-full w-full bg-black/50"
			/>

			{/* Dialog */}
			<div className="relative mx-auto flex min-h-full max-w-2xl items-center justify-center px-4 py-10">
				<div className="relative w-full rounded-2xl bg-primary shadow-xl ring-1 ring-black/5">
					{/* Header */}
					<div className="flex items-start justify-between gap-4 border-b border-accent/30 px-6 py-5">
						<div>
							<h3 className="text-lg font-semibold text-slate-900">
								Estate Settlement
							</h3>
							<p className="mt-1 text-sm text-black">Step {step} of 6</p>
						</div>

						<button
							type="button"
							onClick={onClose}
							className="rounded-lg p-1 border border-transparent hover:border-accent focus:border-accent text-slate-500 hover:text-accent  focus:text-accent"
							aria-label="Close"
						>
							<svg
								className="w-6 h-6 fill-current"
								xmlns="http://www.w3.org/2000/svg"
								viewBox="0 0 24 24"
							>
								<path
									fillRule="evenodd"
									clipRule="evenodd"
									d="M18.278 16.864a1 1 0 0 1-1.414 1.414l-4.829-4.828-4.828 4.828a1 1 0 0 1-1.414-1.414l4.828-4.829-4.828-4.828a1 1 0 0 1 1.414-1.414l4.829 4.828 4.828-4.828a1 1 0 1 1 1.414 1.414l-4.828 4.829 4.828 4.828z"
								/>
							</svg>
						</button>
					</div>

					{/* Progress */}
					<div className="px-6 pt-5">
						<div className="flex items-center gap-2">
							{Array.from({ length: 6 }).map((_, i) => {
								const n = i + 1;
								return (
									<span
										key={n}
										className={[
											"h-2 w-full rounded-full",
											step >= n ? "bg-accent" : "bg-white",
										].join(" ")}
									/>
								);
							})}
						</div>
					</div>

					{/* Body */}
					<form onSubmit={handleSubmit(onSubmit)} className="px-6 pb-6 pt-5">
						{status === "success" && (
							<div className="mb-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">
								Thanks — we received your request. We’ll contact you soon.
							</div>
						)}

						{status === "error" && (
							<div className="mb-4 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-800">
								{errorMsg}
							</div>
						)}

						{/*/!* STEP 1 *!/*/}
						{/*{step === 1 && (*/}
						{/*	<div className="space-y-4">*/}
						{/*		<h4 className="text-base font-semibold text-slate-900">*/}
						{/*			Has the person passed away?{" "}*/}
						{/*			<span className="text-rose-600">*</span>*/}
						{/*		</h4>*/}

						{/*		<RadioCardGroup*/}
						{/*			value={passedAway}*/}
						{/*			onChange={v =>*/}
						{/*				setValue("passedAway", v as PassedAway, {*/}
						{/*					shouldValidate: true,*/}
						{/*				})*/}
						{/*			}*/}
						{/*			options={[*/}
						{/*				"Yes, they have passed away",*/}
						{/*				"Not yet, but they are close to passing",*/}
						{/*				"No, I am planning for the future",*/}
						{/*			]}*/}
						{/*			error={errors.passedAway?.message}*/}
						{/*		/>*/}

						{/*		{errors.passedAway?.message && (*/}
						{/*			<p className="text-xs text-rose-700">*/}
						{/*				{errors.passedAway.message}*/}
						{/*			</p>*/}
						{/*		)}*/}
						{/*	</div>*/}
						{/*)}*/}


						{/* STEP 1 */}
						{step === 1 && (
							<div className="space-y-6">

								<h4 className="text-base font-semibold text-slate-900">
									Are You? <span className="text-rose-600">*</span>
								</h4>

								{/* Checkbox Roles */}
								<div className="">
									<RadioCardGroup
										value={role}
										onChange={(v) =>
											setValue("role", v as Role, {
												shouldValidate: true,
												shouldDirty: true,
											})
										}
										options={[
											"Heir of Estate",
											"Trustee",
											"Attorney",
											"Real Estate Agent",
											"Other Party",
										]}
										error={errors.role?.message}
										columns={2}
									/>
								</div>

								{/* Contact Info */}
								<div className="grid sm:grid-cols-2 gap-4">
									<Field label="Full Name" required error={errors.fullName?.message}>
										<input
											{...register("fullName",{ required:"Full name required"})}
											className={inputClass(!!errors.fullName)}
										/>
									</Field>

									<Field label="Phone" required error={errors.phone?.message}>
										<input
											type="tel"
											{...register("phone",{ required:"Phone required"})}
											className={inputClass(!!errors.phone)}
										/>
									</Field>
								</div>

								<div className="grid sm:grid-cols-2 gap-4">

									<Field label="Email" required error={errors.email?.message}>
										<input
											type="email"
											{...register("email",{ required:"Email required"})}
											className={inputClass(!!errors.email)}
										/>
									</Field>

									<Field label="Estate Name (optional)">
										<input {...register("estateName")} className={inputClass(false)} />
									</Field>

								</div>

								{/* City / State */}
								<div className="grid sm:grid-cols-2 gap-4">

									<Field label="City" required error={errors.city?.message}>
										<input
											{...register("city",{ required:"City required"})}
											className={inputClass(!!errors.city)}
										/>
									</Field>

									<Field label="State" required error={errors.state?.message}>
										<select
											{...register("state",{ required:"Select state"})}
											className={inputClass(!!errors.state)}
										>
											<option value="">Select State</option>
											{US_STATES.map(s => (
												<option key={s} value={s}>{s}</option>
											))}
										</select>
									</Field>
								</div>

								<Field label="Property Address (optional)">
									<input
										{...register("propertyAddress")}
										className={inputClass(false)}
									/>
								</Field>

							</div>
						)}

						{/* STEP 2 */}
						{step === 2 && (
							<div className="space-y-4">
								<h4 className="text-base font-semibold text-slate-900">
									What is the total estimated value of the estate?{" "}
									<span className="text-rose-600">*</span>
								</h4>

								<RadioCardGroup
									value={estateValue}
									onChange={v =>
										setValue("estateValue", v as EstateValue, {
											shouldValidate: true,
										})
									}
									options={[
										"Less than $50,000",
										"$50,000 - $250,000",
										"$250,000 - $500,000",
										"$500,000 - $1 Million",
										"$1 Million - $5 Million",
										"Over $5 Million",
									]}
									error={errors.estateValue?.message}
								/>

								{errors.estateValue?.message && (
									<p className="text-xs text-rose-700">
										{errors.estateValue.message}
									</p>
								)}
							</div>
						)}

						{/* STEP 3 */}
						{step === 3 && (
							<div className="space-y-4">
								<h4 className="text-base font-semibold text-slate-900">
									Are you experiencing any family conflicts in settling the
									estate? <span className="text-rose-600">*</span>
								</h4>

								<RadioCardGroup
									value={familyConflict}
									onChange={v =>
										setValue("familyConflict", v as FamilyConflict, {
											shouldValidate: true,
										})
									}
									options={[
										"Family members dispute the validity of the will or trust (e.g., forged or multiple versions exist)",
										"Family members disagree over who should be in charge",
										"There is disagreement about how the assets should be divided",
										"Someone suspects that assets are hidden, misused, or missing",
										"The executor or trustee is not acting fairly or efficiently",
										"None of the above",
									]}
									error={errors.familyConflict?.message}
								/>

								{errors.familyConflict?.message && (
									<p className="text-xs text-rose-700">
										{errors.familyConflict.message}
									</p>
								)}
							</div>
						)}

						{/* STEP 4 */}
						{step === 4 && (
							<div className="space-y-4">
								<h4 className="text-base font-semibold text-slate-900">
									About your situation
								</h4>

								<Field
									label="What is your loved one's name? (optional)"
									error={errors.lovedOneName?.message}
								>
									<input
										{...register("lovedOneName")}
										className={inputClass(!!errors.lovedOneName)}
										placeholder="Optional"
									/>
								</Field>

								<Field
									label="What is your relationship to the loved one?"
									error={errors.relationship?.message}
									required
								>
									<input
										{...register("relationship", {
											required: "Relationship is required.",
										})}
										className={inputClass(!!errors.relationship)}
										placeholder="e.g., spouse, child, sibling"
									/>
								</Field>

								<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
									<Field
										label="What state did your loved one live in?"
										error={errors.lovedOneState?.message}
										required
									>
										<input
											{...register("lovedOneState", {
												required: "This is required.",
											})}
											className={inputClass(!!errors.lovedOneState)}
											placeholder="e.g., Texas"
										/>
									</Field>

									<Field
										label="What state do you live in?"
										error={errors.yourState?.message}
										required
									>
										<input
											{...register("yourState", {
												required: "This is required.",
											})}
											className={inputClass(!!errors.yourState)}
											placeholder="e.g., California"
										/>
									</Field>
								</div>
							</div>
						)}

						{/* STEP 5 */}
						{step === 5 && (
							<div className="space-y-4">
								<h4 className="text-base font-semibold text-slate-900">
									How can we help you? <span className="text-rose-600">*</span>
								</h4>

								<Field
									label="Describe your situation"
									error={errors.helpMessage?.message}
									required
								>
									<textarea
										{...register("helpMessage", {
											required: "Please tell us how we can help.",
										})}
										className={textareaClass(!!errors.helpMessage)}
										rows={5}
										placeholder="Briefly explain what you need help with…"
									/>
								</Field>
							</div>
						)}

						{/* STEP 6 */}
						{step === 6 && (
							<div className="space-y-4">
								<h4 className="text-base font-semibold text-slate-900">
									Your contact details
								</h4>

								<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
									<Field
										label="First Name"
										error={errors.firstName?.message}
										required
									>
										<input
											{...register("firstName", {
												required: "First name is required.",
											})}
											className={inputClass(!!errors.firstName)}
											placeholder="John"
										/>
									</Field>

									<Field
										label="Last Name"
										error={errors.lastName?.message}
										required
									>
										<input
											{...register("lastName", {
												required: "Last name is required.",
											})}
											className={inputClass(!!errors.lastName)}
											placeholder="Smith"
										/>
									</Field>
								</div>

								<Field
									label="Phone Number"
									error={errors.phone?.message}
									required
								>
									<input
										{...register("phone", {
											required: "Phone number is required.",
											minLength: {
												value: 7,
												message: "Enter a valid phone number.",
											},
										})}
										className={inputClass(!!errors.phone)}
										placeholder="+1 (555) 123-4567"
										type="tel"
									/>
								</Field>

								<Field label="Email" error={errors.email?.message} required>
									<input
										{...register("email", {
											required: "Email is required.",
											pattern: {
												value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
												message: "Enter a valid email.",
											},
										})}
										className={inputClass(!!errors.email)}
										placeholder="you@example.com"
										type="email"
									/>
								</Field>

								<p className="text-xs text-slate-500">
									This form does not provide legal advice. For legal guidance,
									consult an attorney.
								</p>
							</div>
						)}

						{/* Hidden required validation for radio steps */}
						<input
							type="hidden"
							{...register("passedAway", {
								required: "Please select one option.",
							})}
						/>
						<input
							type="hidden"
							{...register("estateValue", {
								required: "Please select one option.",
							})}
						/>
						<input
							type="hidden"
							{...register("familyConflict", {
								required: "Please select one option.",
							})}
						/>

						{/* Footer buttons */}
						<div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-between">
							<button
								type="button"
								onClick={prevStep}
								disabled={step === 1 || status === "loading"}
								className="inline-flex w-full items-center justify-center rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-900 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
							>
								Back
							</button>

							<div className="flex w-full gap-3 sm:w-auto">
								{step < 6 ? (
									<button
										type="button"
										onClick={nextStep}
										disabled={status === "loading"}
										className="inline-flex w-full items-center justify-center rounded-xl bg-accent px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
									>
										Next
									</button>
								) : (
									<button
										type="submit"
										disabled={status === "loading"}
										className="inline-flex w-full items-center justify-center rounded-xl bg-accent px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
									>
										{status === "loading" ? "Submitting…" : "Submit"}
									</button>
								)}
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	);
}

function RadioCardGroup({
	value,
	onChange,
	options,
	error,
	columns = 1,
}: {
	value: string | undefined;
	onChange: (v: string) => void;
	options: string[];
	error?: string;
	columns?: number;
}) {
	return (
		<div
			className={`grid gap-2 ${
				columns > 1 ? `grid-cols-1 sm:grid-cols-${columns}` : ""
			}`}
		>
				{options.map(opt => {
					const selected = value === opt;
					return (
						<button
							key={opt}
							type="button"
							onClick={() => onChange(opt)}
							className={[
								"w-full rounded-2xl border p-4 text-left text-sm transition",
								selected
									? "bg-accent text-white"
									: "border-slate-200 bg-white text-slate-900 hover:bg-slate-50",
								error && !value ? "ring-2 ring-rose-200" : "",
							].join(" ")}
						>
							{opt}
						</button>
					);
				})}
		</div>
	);
}

function Field({
	label,
	error,
	required,
	children,
}: {
	label: string;
	error?: string;
	required?: boolean;
	children: React.ReactNode;
}) {
	return (
		<div>
			<label className="mb-1 block text-sm font-medium text-slate-700">
				{label} {required ? <span className="text-rose-600">*</span> : null}
			</label>
			{children}
			{error ? <p className="mt-1 text-xs text-rose-700">{error}</p> : null}
		</div>
	);
}

function inputClass(hasError: boolean) {
	return [
		"w-full rounded-xl border bg-white px-3 py-2 text-slate-900 outline-none placeholder:text-slate-400 focus:ring-2",
		hasError
			? "border-rose-300 focus:ring-rose-200"
			: "border-slate-300 focus:border-slate-400 focus:ring-slate-200",
	].join(" ");
}

function textareaClass(hasError: boolean) {
	return [
		"w-full rounded-xl border bg-white px-3 py-2 text-slate-900 outline-none placeholder:text-slate-400 focus:ring-2",
		hasError
			? "border-rose-300 focus:ring-rose-200"
			: "border-slate-300 focus:border-slate-400 focus:ring-slate-200",
	].join(" ");
}
