// Path: Frontend/src/components/dashboard/settings/dashboard-settings-focus.tsx

import { createEffect, createMemo, createSignal, For, Show, type Component } from "solid-js";
import { createStore } from "solid-js/store";
import { useAuth, type UpdateProfileInput } from "~/context/auth/context";
import styles from "./dashboard-settings-focus.module.scss";

const emptyForm: UpdateProfileInput = {
	fullName: "",
	preferredName: "",
	profileIconUrl: "",
	headline: "",
	bio: "",
	timezone: "",
	locale: "",
	gradeLevel: "",
	learningGoal: "",
};

const initialsFor = (value: string) => {
	const cleaned = value.trim();
	if (!cleaned) return "U";

	const parts = cleaned.split(/\s+/).filter(Boolean);
	if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();

	return `${parts[0]?.[0] ?? ""}${parts[1]?.[0] ?? ""}`.toUpperCase();
};

const roleLabel = (role?: "student" | "teacher") => {
	if (role === "teacher") return "Teacher";
	if (role === "student") return "Student";
	return "Member";
};

const formatJoinedDate = (value?: string) => {
	if (!value) return "Recently";

	const date = new Date(value);
	if (Number.isNaN(date.getTime())) return "Recently";

	return date.toLocaleDateString(undefined, {
		month: "short",
		day: "numeric",
		year: "numeric",
	});
};

const DashboardSettingsFocus: Component = () => {
	const auth = useAuth();
	const [form, setForm] = createStore<UpdateProfileInput>(emptyForm);
	const [isSaving, setIsSaving] = createSignal(false);
	const [errorMessage, setErrorMessage] = createSignal<string | null>(null);
	const [successMessage, setSuccessMessage] = createSignal<string | null>(null);

	createEffect(() => {
		const user = auth.user();
		if (!user) return;

		setForm({
			fullName: user.full_name ?? "",
			preferredName: user.profile.preferred_name ?? "",
			profileIconUrl: user.profile.profile_icon_url ?? "",
			headline: user.profile.headline ?? "",
			bio: user.profile.bio ?? "",
			timezone: user.profile.timezone ?? "",
			locale: user.profile.locale ?? "",
			gradeLevel: user.profile.grade_level ?? "",
			learningGoal: user.profile.learning_goal ?? "",
		});
	});

	const displayName = createMemo(() => form.preferredName.trim() || form.fullName.trim() || "Your profile");
	const displaySubtitle = createMemo(() => form.headline.trim() || `${roleLabel(auth.user()?.role)} account`);
	const stats = createMemo(() => {
		const user = auth.user();
		return [
			{ label: "Role", value: roleLabel(user?.role) },
			{ label: "Email", value: user?.email ?? "Not available" },
			{ label: "Timezone", value: form.timezone.trim() || "Not set" },
			{ label: "Goal", value: form.learningGoal.trim() || "Add a learning goal" },
		];
	});

	const handleInput = (field: keyof UpdateProfileInput) => (event: Event) => {
		const target = event.currentTarget as HTMLInputElement | HTMLTextAreaElement;
		setForm(field, target.value);
		setSuccessMessage(null);
	};

	const handleSubmit = async (event: Event) => {
		event.preventDefault();
		setIsSaving(true);
		setErrorMessage(null);
		setSuccessMessage(null);

		try {
			await auth.updateProfile({ ...form });
			setSuccessMessage("Profile updated.");
		} catch (error) {
			setErrorMessage(error instanceof Error ? error.message : "Unable to save your profile right now.");
		} finally {
			setIsSaving(false);
		}
	};

	return (
		<section class={styles.section}>
			<article class={styles.heroCard}>
				<div class={styles.heroCopy}>
					<p class={styles.eyebrow}>Settings</p>
					<h1>Your profile and study settings</h1>
					<p>Keep your preferred name, profile photo, and learning setup in sync so the dashboard feels like your own workspace.</p>
				</div>

				<div class={styles.profileChip}>
					<Show when={form.profileIconUrl.trim()} fallback={<span class={styles.avatar}>{initialsFor(displayName())}</span>}>
						{(iconUrl) => <img src={iconUrl()} alt="" class={`${styles.avatar} ${styles.avatarImage}`} />}
					</Show>
					<div>
						<strong>{displayName()}</strong>
						<span>{displaySubtitle()}</span>
					</div>
				</div>

				<div class={styles.statGrid}>
					<For each={stats()}>
						{(stat) => (
							<div class={styles.statCard}>
								<strong>{stat.value}</strong>
								<span>{stat.label}</span>
							</div>
						)}
					</For>
				</div>
			</article>

			<form class={styles.panelGrid} onSubmit={(event) => void handleSubmit(event)}>
				<article class={styles.panelCard}>
					<div class={styles.panelBody}>
						<div class={styles.panelCopy}>
							<h2>Profile details</h2>
							<p>These fields shape how your name and identity show up across the dashboard.</p>
						</div>

						<div class={styles.fieldGrid}>
							<label class={styles.fieldLabel}>
								<span>Preferred name</span>
								<input class={styles.textInput} value={form.preferredName} onInput={handleInput("preferredName")} placeholder="What should the dashboard call you?" />
							</label>

							<label class={styles.fieldLabel}>
								<span>Full name</span>
								<input class={styles.textInput} value={form.fullName} onInput={handleInput("fullName")} placeholder="Your full name" />
							</label>

							<label class={styles.fieldLabel}>
								<span>Headline</span>
								<input class={styles.textInput} value={form.headline} onInput={handleInput("headline")} placeholder="Short label under your name" />
							</label>

							<label class={styles.fieldLabel}>
								<span>Profile icon URL</span>
								<input class={styles.textInput} value={form.profileIconUrl} onInput={handleInput("profileIconUrl")} placeholder="https://..." />
							</label>

							<label class={`${styles.fieldLabel} ${styles.fieldLabelFull}`}>
								<span>Bio</span>
								<textarea class={styles.textArea} value={form.bio} onInput={handleInput("bio")} rows={4} placeholder="A short note about you or how you like to work" />
							</label>
						</div>
					</div>
				</article>

				<article class={styles.panelCard}>
					<div class={styles.panelBody}>
						<div class={styles.panelCopy}>
							<h2>Learning setup</h2>
							<p>Use these profile fields to shape future reminders, dashboards, and classroom context.</p>
						</div>

						<div class={styles.fieldGrid}>
							<label class={styles.fieldLabel}>
								<span>Timezone</span>
								<input class={styles.textInput} value={form.timezone} onInput={handleInput("timezone")} placeholder="Asia/Kuala_Lumpur" />
							</label>

							<label class={styles.fieldLabel}>
								<span>Locale</span>
								<input class={styles.textInput} value={form.locale} onInput={handleInput("locale")} placeholder="en-MY" />
							</label>

							<label class={styles.fieldLabel}>
								<span>Grade level</span>
								<input class={styles.textInput} value={form.gradeLevel} onInput={handleInput("gradeLevel")} placeholder="Year 6" />
							</label>

							<label class={`${styles.fieldLabel} ${styles.fieldLabelFull}`}>
								<span>Learning goal</span>
								<textarea class={styles.textArea} value={form.learningGoal} onInput={handleInput("learningGoal")} rows={4} placeholder="What are you working toward right now?" />
							</label>
						</div>
					</div>
				</article>

				<article class={styles.panelCard}>
					<div class={styles.panelBody}>
						<div class={styles.panelCopy}>
							<h2>Account snapshot</h2>
							<p>Core account details still come from your signed-in user record.</p>
						</div>

						<div class={styles.rowList}>
							<div class={styles.rowItem}>
								<span>Email</span>
								<strong>{auth.user()?.email ?? "Not available"}</strong>
							</div>
							<div class={styles.rowItem}>
								<span>Role</span>
								<strong>{roleLabel(auth.user()?.role)}</strong>
							</div>
							<div class={styles.rowItem}>
								<span>Status</span>
								<strong>{auth.user()?.is_active ? "Active" : "Inactive"}</strong>
							</div>
							<div class={styles.rowItem}>
								<span>Member since</span>
								<strong>{formatJoinedDate(auth.user()?.created_at)}</strong>
							</div>
						</div>

						<div class={styles.formActions}>
							<button type="submit" class={styles.primaryAction} disabled={isSaving()}>
								{isSaving() ? "Saving…" : "Save profile"}
							</button>
							<button type="button" class={styles.secondaryAction} onClick={() => void auth.refresh()}>
								Refresh from server
							</button>
						</div>

						<Show when={errorMessage()}>
							<p class={`${styles.feedbackMessage} ${styles.feedbackError}`}>{errorMessage()}</p>
						</Show>

						<Show when={successMessage()}>
							<p class={`${styles.feedbackMessage} ${styles.feedbackSuccess}`}>{successMessage()}</p>
						</Show>
					</div>
				</article>
			</form>
		</section>
	);
};

export default DashboardSettingsFocus;
