"use client";
import {
	Dialog,
	DialogBody,
	DialogClose,
	DialogContent,
	DialogDescription,
	DialogFooter,
	DialogHeader,
	DialogTitle,
} from "@giselle-internal/ui/dialog";
import { Select } from "@giselle-internal/ui/select";
import { useToasts } from "@giselle-internal/ui/toast";
import { useState } from "react";
import type { TeamRole } from "@/db";
import { AvatarImage } from "@/services/accounts/components/user-button/avatar-image";
import { Button } from "../components/button";
import { deleteTeamMember, updateTeamMemberRole } from "./actions";

type TeamMemberListItemProps = {
	userId: string;
	displayName: string | null;
	email: string | null;
	avatarUrl: string | null;
	role: TeamRole;
	canManageMembers: boolean;
	currentUserId: string;
};

export function TeamMemberListItem({
	userId,
	displayName,
	email,
	avatarUrl,
	role: initialRole,
	canManageMembers,
	currentUserId,
}: TeamMemberListItemProps) {
	const { toast } = useToasts();
	const [isLoading, setIsLoading] = useState(false);
	const [error, setError] = useState("");
	const [open, setOpen] = useState(false);
	const [role, setRole] = useState(initialRole);
	const user = userId;
	const currentUser = currentUserId;
	const isCurrentUser = user === currentUser;

	const canEditRole = canManageMembers && !isCurrentUser;
	const canRemove = isCurrentUser || canEditRole;
	const roleLabel = role.charAt(0).toUpperCase() + role.slice(1);

	const selectOptions = [
		...(canEditRole
			? [
					{ value: "admin" as const, label: "Admin" },
					{ value: "member" as const, label: "Member" },
				]
			: []),
		...(canRemove ? [{ value: "__remove__" as const, label: "Remove" }] : []),
	];

	const hasMenu = selectOptions.length > 0;
	const selectValue = canEditRole ? role : undefined;

	const handleRoleChange = (value: string) => {
		const nextRole = value as TeamRole;
		if (nextRole === role) {
			return;
		}
		void handleSaveRole(nextRole);
	};

	const handleSaveRole = async (nextRole: TeamRole) => {
		const previousRole = role;
		try {
			setIsLoading(true);
			setError("");
			setRole(nextRole);
			const formData = new FormData();
			formData.append("userId", user);
			formData.append("role", nextRole);
			const result = await updateTeamMemberRole(formData);
			if (result?.success) {
				toast(`Role updated: ${nextRole}`, { type: "success" });
			} else {
				const msg = result?.error || "Failed to update role";
				setError(msg);
				setRole(previousRole);
				toast(msg, { type: "error" });
			}
		} catch (e) {
			setRole(previousRole);
			if (e instanceof Error) {
				setError(e.message);
				toast(e.message, { type: "error" });
			}
			console.error("Error updating role:", e);
		} finally {
			setIsLoading(false);
		}
	};

	const handleDeleteMember = async () => {
		try {
			setIsLoading(true);
			const formData = new FormData();
			formData.append("userId", user);
			const result = await deleteTeamMember(formData);
			if (!result?.success) {
				const msg = result?.error || "Failed to delete member";
				setError(msg);
				toast(msg, { type: "error" });
			} else {
				toast("Member removed", { type: "success" });
			}
		} catch (e) {
			if (e instanceof Error) {
				setError(e.message);
				toast(e.message, { type: "error" });
			}
			console.error("Error deleting member:", e);
		} finally {
			setIsLoading(false);
			setOpen(false);
		}
	};

	return (
		<div className="group px-2 py-3 border-t-[0.5px] border-border first:border-t-0 font-sans">
			<div className="flex items-center justify-between gap-2">
				<div className="flex gap-x-2 items-center">
					<div className="flex-shrink-0">
						<AvatarImage
							avatarUrl={avatarUrl}
							width={36}
							height={36}
							alt={displayName || email || ""}
						/>
					</div>
					<div className="flex flex-col gap-y-1 font-medium">
						<div className="text-inverse text-[14px] leading-[20.4px]">
							{displayName || "No display name"}
						</div>
						<div className="text-text/60 text-[12px] leading-[16px]">
							{email || "No email"}
						</div>
					</div>
				</div>
				<div className="flex justify-between gap-2">
					<div className="flex items-center gap-[5px]">
						{hasMenu ? (
							<Select
								id={`${userId}-role`}
								options={selectOptions}
								placeholder={roleLabel}
								value={selectValue}
								onValueChange={(v) => {
									if (v === "__remove__") {
										setOpen(true);
										return;
									}
									if (canEditRole) handleRoleChange(v);
								}}
								renderOption={(opt) => (
									<span
										className={
											opt.value === "__remove__" ? "text-error-900" : undefined
										}
									>
										{opt.label}
									</span>
								)}
								itemClassNameForOption={(opt) =>
									opt.value === "__remove__"
										? "text-error-900 hover:bg-error-900/15 data-[highlighted]:bg-error-900/15 data-[highlighted]:text-error-900"
										: undefined
								}
								widthClassName="min-w-[140px]"
								triggerClassName="h-8"
							/>
						) : (
							<span className="capitalize text-text/60 font-medium text-[14px] leading-[16px] font-sans">
								{role}
							</span>
						)}
						<Dialog open={open} onOpenChange={setOpen}>
							<DialogContent variant="destructive">
								<DialogHeader>
									<DialogTitle className="font-sans text-[20px] font-medium tracking-tight text-error-900">
										Remove Member
									</DialogTitle>
									<DialogDescription className="text-error-900/50">
										This will permanently delete this member and remove their
										access to your team.
									</DialogDescription>
									<DialogClose className="text-inverse" />
								</DialogHeader>
								<DialogBody>{/* Content goes here if needed */}</DialogBody>
								<DialogFooter>
									<Button
										variant="link"
										onClick={() => setOpen(false)}
										disabled={isLoading}
									>
										Cancel
									</Button>
									<Button
										variant="destructive"
										onClick={handleDeleteMember}
										disabled={isLoading}
									>
										{isLoading ? "Processing..." : "Remove"}
									</Button>
								</DialogFooter>
							</DialogContent>
						</Dialog>
					</div>
				</div>
			</div>
			{error && (
				<div className="text-error-900 text-[12px] mt-1 ml-12">{error}</div>
			)}
		</div>
	);
}
