"use client";
import { useStoreState } from "@hooks/store";
import axios, { AxiosError } from "axios";
import { useRouter } from "next/navigation";
import { useEffect, useState, useRef } from "react";
import { FaUser } from "react-icons/fa6";
import { User } from "@appTypes/Prisma";
import { useStoreActions } from "@hooks/store";

function CustomRoleDropdown({
	value,
	onChange,
	disabled,
}: {
	value: string;
	onChange: (role: string) => void;
	disabled: boolean;
}) {
	const [isOpen, setIsOpen] = useState(false);
	const dropdownRef = useRef<HTMLDivElement>(null);
	const roles = ["ADMIN", "SCIENTIST", "GUEST"] as const;

	useEffect(() => {
		function handleClickOutside(event: MouseEvent) {
			if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
				setIsOpen(false);
			}
		}
		document.addEventListener("mousedown", handleClickOutside);
		return () => document.removeEventListener("mousedown", handleClickOutside);
	}, []);

	return (
		<div className="relative" ref={dropdownRef}>
			<button
				type="button"
				className={`w-full p-2 border border-neutral-300 rounded-md text-left text-sm bg-white ${
					disabled ? "opacity-50 cursor-not-allowed" : "hover:bg-neutral-100"
				}`}
				onClick={() => !disabled && setIsOpen(!isOpen)}
				disabled={disabled}
			>
				{value || "Select a role"}
			</button>
			{isOpen && (
				<div className="absolute top-full mt-1 w-40 bg-white border border-neutral-300 rounded-lg overflow-hidden shadow-lg z-40">
					<ul>
						{roles.map((role) => (
							<li key={role}>
								<button
									className={`block w-full text-left px-4 py-2 text-sm hover:bg-neutral-100 ${
										value === role ? "bg-neutral-100" : ""
									}`}
									onClick={() => {
										onChange(role);
										setIsOpen(false);
									}}
								>
									{role}
								</button>
							</li>
						))}
					</ul>
				</div>
			)}
		</div>
	);
}

export default function Profile() {
	const router = useRouter();
	const user = useStoreState((state) => state.user);
	const setUser = useStoreActions((actions) => actions.setUser);
	const [activeTab, setActiveTab] = useState<"profile" | "orders" | "account">("profile");

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

	useEffect(() => {
		!user && router.push("/");
	}, []);

	function ProfileTab() {
		if (!user) return <p className="text-neutral-600">No user data available</p>;

		const isScientistOrAdmin = user.role === "SCIENTIST" || user.role === "ADMIN";

		const stats = [
			...(isScientistOrAdmin
				? [
						{ label: "Earthquakes Logged", value: user.earthquakes.length },
						{ label: "Observatories Logged", value: user.observatories.length },
						{ label: "Artefacts Logged", value: user.artefacts.length },
				  ]
				: []),
			{ label: "Orders Placed", value: user.purchasedOrders.length },
		];

		return (
			<div className="bg-neutral-100 rounded-md border border-neutral-200 p-8">
				<div className="flex justify-between items-center mb-6">
					<h3 className="text-xl font-semibold text-neutral-800">Profile Overview</h3>
					{user.role !== "GUEST" && <p className="text-sm text-neutral-600">{user.role}</p>}
				</div>
				<div className="space-y-6">
					<p>User since {new Date(user.createdAt).toLocaleDateString("en-GB")}</p>
					<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
						{stats.map((stat) => (
							<div key={stat.label} className="bg-white border border-neutral-200 rounded-md p-4 text-center shadow-sm">
								<p className="text-xs text-neutral-600">{stat.label}</p>
								<p className="text-lg font-semibold text-neutral-800">{stat.value}</p>
							</div>
						))}
					</div>
					{user.scientist && (
						<div className="mt-4 border-t pt-4">
							<h4 className="font-semibold text-neutral-700 mb-4">Scientist Details</h4>
							<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
								<div className="bg-white border border-neutral-200 rounded-md p-4 text-center shadow-sm">
									<p className="text-sm text-neutral-600">Level</p>
									<p className="text-lg font-semibold text-neutral-800">{user.scientist.level}</p>
								</div>
								<div className="bg-white border border-neutral-200 rounded-md p-4 text-center shadow-sm">
									<p className="text-sm text-neutral-600">Superior</p>
									<p className="text-lg font-semibold text-neutral-800">{user.scientist.superior?.name || "None"}</p>
								</div>
								<div className="bg-white border border-neutral-200 rounded-md p-4 text-center shadow-sm">
									<p className="text-sm text-neutral-600">Subordinates</p>
									<p className="text-lg font-semibold text-neutral-800">{user.scientist.subordinates.length}</p>
								</div>
							</div>
						</div>
					)}
				</div>
			</div>
		);
	}

	function OrdersTab() {
		return (
			<div className="bg-neutral-100 rounded-md border border-neutral-200 p-8">
				<h3 className="text-xl font-semibold text-neutral-800 mb-6">Previous Orders</h3>
				{user!.purchasedOrders.length === 0 ? (
					<p className="text-neutral-600">No previous orders.</p>
				) : (
					<ul className="space-y-2">
						{user!.purchasedOrders.map((order) => (
							<li key={order.id} className="text-neutral-700">
								Order #{order.id}
							</li>
						))}
					</ul>
				)}
			</div>
		);
	}

	function AccountTab() {
		const [name, setName] = useState("");
		const [email, setEmail] = useState("");
		const [password, setPassword] = useState("");
		const [confirmPassword, setConfirmPassword] = useState("");
		const [requestedRole, setRequestedRole] = useState("");
		const [isSubmitting, setIsSubmitting] = useState(false);
		const [isDeleting, setIsDeleting] = useState(false);
		const [error, setError] = useState("");
		const [successMessage, setSuccessMessage] = useState("");
		const router = useRouter();

		useEffect(() => {
			if (user) {
				setName(user.name);
				setEmail(user.email);
			}
		}, [user]);

		async function handleSave() {
			setError("");
			setSuccessMessage("");
			if (!name || !email) {
				setError("Name and email are required.");
				return;
			}
			if (password && password !== confirmPassword) {
				setError("Passwords do not match.");
				return;
			}
			setIsSubmitting(true);
			try {
				const res = await axios.post(
					"/api/update-user",
					{ name, email, password, requestedRole },
					{ headers: { "Content-Type": "application/json" } }
				);
				if (res.status === 200) {
					setUser(res.data.user);
					setSuccessMessage("Account updated successfully.");
					if (requestedRole) {
						setSuccessMessage("Account updated and role change request submitted.");
						setRequestedRole("");
					}
				} else {
					setError("Unexpected error occurred");
				}
			} catch (error) {
				const axiosError = error as AxiosError<{ message: string }>;
				setError(axiosError.response?.data?.message || "Network error occurred");
			} finally {
				setIsSubmitting(false);
			}
		}

		async function handleDeleteAccount() {
			if (!confirm("Are you sure you want to delete your account? This action cannot be undone.")) {
				return;
			}
			setIsDeleting(true);
			try {
				const res = await axios.post(
					"/api/delete-user",
					{ userId: user!.id },
					{ headers: { "Content-Type": "application/json" } }
				);
				if (res.status === 200) {
					setUser(null);
					router.push("/");
				} else {
					setError("Failed to delete account");
				}
			} catch (error) {
				setError("Error deleting account");
			} finally {
				setIsDeleting(false);
			}
		}

		function handleClear() {
			setName(user?.name || "");
			setEmail(user?.email || "");
			setPassword("");
			setConfirmPassword("");
			setRequestedRole("");
			setError("");
			setSuccessMessage("");
		}

		return (
			<div className="bg-neutral-100 rounded-md border border-neutral-200 p-8">
				<h3 className="text-xl font-semibold text-neutral-800 mb-6">Account Settings</h3>
				{successMessage && <p className="text-green-600 text-sm mb-4">{successMessage}</p>}
				{error && <p className="text-red-600 text-sm mb-4">{error}</p>}
				<div className="space-y-8">
					<div className="space-y-4 mx-auto max-w-md">
						<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 focus:ring-2 focus:ring-blue-500 text-sm"
								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 focus:ring-2 focus:ring-blue-500 text-sm"
								disabled={isSubmitting}
							/>
						</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 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 focus:ring-2 focus:ring-blue-500 text-sm"
								disabled={isSubmitting}
							/>
						</div>
						<div>
							<label className="text-sm text-neutral-600 block mb-1">Request Role Change</label>
							<CustomRoleDropdown value={requestedRole} onChange={setRequestedRole} disabled={isSubmitting} />
						</div>
					</div>
					<div className="flex justify-end gap-4">
						<button
							onClick={handleClear}
							className={`py-2 px-4 bg-neutral-300 text-neutral-800 rounded-md hover:bg-neutral-400 font-medium ${
								isSubmitting ? "opacity-50 cursor-not-allowed" : ""
							}`}
							disabled={isSubmitting}
						>
							Clear Changes
						</button>
						<button
							onClick={handleSave}
							className={`py-2 px-4 bg-blue-600 text-white rounded-md font-medium ${
								isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
							}`}
							disabled={isSubmitting}
						>
							{isSubmitting ? "Saving..." : "Save Changes"}
						</button>
					</div>
					<div className="border-t border-neutral-300 pt-6">
						<button
							onClick={handleDeleteAccount}
							className={`w-40 py-2 px-4 bg-red-500 text-white rounded-md font-medium ${
								isDeleting ? "opacity-50 cursor-not-allowed" : "hover:bg-red-700"
							}`}
							disabled={isDeleting}
						>
							{isDeleting ? "Deleting..." : "Delete Account"}
						</button>
					</div>
				</div>
			</div>
		);
	}

	return (
		<div className="relative min-h-full bg-neutral-50">
			<div className="absolute top-4 right-4">
				<button
					onClick={handleLogout}
					className="py-2 px-4 bg-red-500 text-white rounded-md hover:bg-red-700"
					aria-label="Log out"
					title="Log out"
				>
					Log Out
				</button>
			</div>
			<div className="flex items-center justify-center min-h-full">
				<div className="max-w-4xl mx-auto flex flex-col p-4 mt-20">
					<h2 className="text-3xl font-semibold text-neutral-800 mb-10">Hello {user?.name}</h2>
					<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
						<div className="col-span-1">
							<div className="space-y-2">
								<button
									onClick={() => setActiveTab("profile")}
									className={`w-full text-left p-2 rounded-md ${
										activeTab === "profile" ? "bg-blue-100 text-blue-700" : "text-neutral-600 hover:bg-neutral-200"
									}`}
								>
									Profile
								</button>
								<button
									onClick={() => setActiveTab("orders")}
									className={`w-full text-left p-2 rounded-md ${
										activeTab === "orders" ? "bg-blue-100 text-blue-700" : "text-neutral-600 hover:bg-neutral-200"
									}`}
								>
									Orders
								</button>
								<button
									onClick={() => setActiveTab("account")}
									className={`w-full text-left p-2 rounded-md ${
										activeTab === "account" ? "bg-blue-100 text-blue-700" : "text-neutral-600 hover:bg-neutral-200"
									}`}
								>
									Account
								</button>
							</div>
						</div>
						<div className="col-span-3">
							{activeTab === "profile" && <ProfileTab />}
							{activeTab === "orders" && <OrdersTab />}
							{activeTab === "account" && <AccountTab />}
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
