"use client";
import axios, { AxiosError } from 'axios';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { FaSignOutAlt } from 'react-icons/fa';
import { FaUser } from 'react-icons/fa6';

import { User } from '@appTypes/Prisma';
import { useStoreActions } from '@hooks/store';

export default function Profile() {
	const router = useRouter();
	const setUser = useStoreActions((actions) => actions.setUser) as (user: User | null) => void;
	const [user, setUserState] = useState<User | null>(null);
	const [name, setName] = useState("");
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [confirmPassword, setConfirmPassword] = useState("");
	const [role, setRole] = useState("");
	const [error, setError] = useState("");
	const [isSubmitting, setIsSubmitting] = useState(false);

	useEffect(() => {
		const fetchUser = async () => {
			try {
				const userData: User = {
					id: 1,
					createdAt: new Date(),
					name: "John Doe",
					email: "john.doe@example.com",
					passwordHash: "hashed_password",
					role: "SCIENTIST",
					scientist: undefined,
					purchasedArtefacts: [],
				};
				setUserState(userData);
				setName(userData.name);
				setEmail(userData.email);
				setRole(userData.role);
			} catch {
				setError("Failed to load user data.");
			}
		};
		fetchUser();
	}, []);

	const handleSave = async () => {
		if (!name || !email) {
			setError("Name and email are required.");
			return;
		}
		setIsSubmitting(true);
		try {
			// todo create receiving api route
			// todo handle sending fields to api route
			await new Promise((resolve) => setTimeout(resolve, 500));
			setUserState({ ...user!, name, email, role });
			alert("Profile updated successfully.");
			setError("");
		} catch {
			setError("Failed to update profile. Please try again.");
		} finally {
			setIsSubmitting(false);
		}
	};

	const handleLogout = async () => {
		try {
			const res = await axios.get("/api/logout");
			if (res.status === 200) {
				setUser(null);
				router.push("/");
			} else {
				console.error("Failed to logout", res.data);
			}
		} catch (error) {
			const axiosError = error as AxiosError<{ message: string }>;
			if (axiosError.response && axiosError.response.status === 400) {
				setUser(null);
				router.push("/");
			} else {
				console.error("Error during logout", axiosError);
			}
		}
	};

	return (
		<div className="flex h-full justify-center bg-neutral-50">
			<div className="w-1/2 flex flex-col">
				<div className="mt-4">
					<button
						onClick={handleLogout}
						className="float-right py-2 px-4 bg-red-500 text-white rounded-md hover:bg-red-700 transition-colors duration-200"
						aria-label="Log out"
						title="Log out"
					>
						{/* <FaSignOutAlt className="h-5 w-5" /> */}
						Log Out
					</button>
				</div>
				<h2 className="mt-10 text-2xl font-semibold text-neutral-800">User Profile</h2>
				<div className="w-full mt-4 bg-neutral-100 rounded-md border border-neutral-200">
					<div className="p-8 justify-center flex">
						{error && <p className="text-red-600 text-sm mb-2 text-center">{error}</p>}
						<div className="flex flex-col py-6 justify-center w-full max-w-md">
							<div className="flex justify-center items-center h-20 w-20 rounded-full bg-neutral-200">
								<FaUser className="h-10 w-10"></FaUser>
							</div>
							<div className="mt-8 space-y-3 w-full">
								<div>
									<label className="text-sm text-neutral-600 block mb-1">Name</label>
									<input
										type="text"
										value={name}
										onChange={(e) => setName(e.target.value)}
										className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
										aria-label="User Name"
										disabled={isSubmitting}
									/>
								</div>
								<div>
									<label className="text-sm text-neutral-600 block mb-1">Email</label>
									<input
										type="email"
										value={email}
										onChange={(e) => setEmail(e.target.value)}
										className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
										aria-label="User Email"
										disabled={isSubmitting}
									/>
								</div>
								<div>
									<label className="text-sm text-neutral-600 block mb-1">Role</label>
									<input
										type="text"
										value={role}
										className="w-full p-2 border border-neutral-300 rounded-md bg-neutral-100 text-sm text-neutral-600 cursor-not-allowed"
										aria-label="User Role"
										disabled
									/>
								</div>
								<div>
									<label className="text-sm text-neutral-600 block mb-1">New Password</label>
									<input
										type="password"
										value={password}
										onChange={(e) => setPassword(e.target.value)}
										className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
										disabled={isSubmitting}
									/>
								</div>
								<div>
									<label className="text-sm text-neutral-600 block mb-1">Confirm Password</label>
									<input
										type="password"
										value={confirmPassword}
										onChange={(e) => setConfirmPassword(e.target.value)}
										className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
										disabled={isSubmitting}
									/>
								</div>
							</div>
							<div className="mt-10">
								<div className="float-right flex">
									<button
										// onClick={handleSave}
										className={`mr-4 px-4 py-2  bg-neutral-300 text-neutral-800 rounded-md hover:bg-neutral-400 flex items-center gap-2 font-medium ${
											isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
										}`}
										disabled={isSubmitting}
									>
										Clear Changes
									</button>
									<button
										onClick={handleSave}
										className={`px-4 py-2 bg-blue-600 text-white rounded-md font-medium flex items-center gap-2 ${
											isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
										}`}
										disabled={isSubmitting}
									>
										{isSubmitting ? (
											<>
												<svg
													className="animate-spin h-5 w-5 text-white"
													xmlns="http://www.w3.org/2000/svg"
													fill="none"
													viewBox="0 0 24 24"
												>
													<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
													<path
														className="opacity-75"
														fill="currentColor"
														d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
													></path>
												</svg>
												Saving...
											</>
										) : (
											"Save Changes"
										)}
									</button>
								</div>
							</div>
						</div>
						<div className="flex justify-end mt-4"></div>
					</div>
				</div>
			</div>
		</div>
	);
}
