"use client";

import {
	Dialog,
	DialogBody,
	DialogClose,
	DialogContent,
	DialogDescription,
	DialogFooter,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "@giselle-internal/ui/dialog";
import { useToasts } from "@giselle-internal/ui/toast";
import { Copy, Ellipsis, RefreshCw, Trash2 } from "lucide-react";
import { useState, useTransition } from "react";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { TeamRole } from "@/db";
import { Button } from "../components/button";
import { resendInvitationAction, revokeInvitationAction } from "./actions";
import { LocalDateTime } from "./components/local-date-time";

type InvitationListItemProps = {
	token: string;
	email: string;
	role: TeamRole;
	expiredAt: Date;
	canManageMembers: boolean;
};

export function InvitationListItem({
	token,
	email,
	role,
	expiredAt,
	canManageMembers,
}: InvitationListItemProps) {
	const { toast, info } = useToasts();
	const [error, setError] = useState("");
	const [dialogOpen, setDialogOpen] = useState(false);
	const [dropdownOpen, setDropdownOpen] = useState(false);
	const [isResendPending, startResendTransition] = useTransition();
	const [isRevokePending, startRevokeTransition] = useTransition();

	const expired = expiredAt.getTime() < Date.now();

	const handleCopy = async () => {
		try {
			const baseUrl =
				process.env.NEXT_PUBLIC_SITE_URL || window.location.origin;
			const link = `${baseUrl}/join/${token}`;
			await navigator.clipboard.writeText(link);
			info("Invite link copied!");
			setDropdownOpen(false);
		} catch (e) {
			console.error("Failed to copy link:", e);
			toast("Failed to copy link", { type: "error" });
		}
	};

	const handleResend = () => {
		startResendTransition(async () => {
			const formData = new FormData();
			formData.append("token", token);
			const res = await resendInvitationAction(undefined, formData);
			if (res.success) {
				toast("Invitation resent!", { type: "success" });
				setDropdownOpen(false);
			} else {
				toast(res.error, { type: "error" });
			}
		});
	};

	const handleConfirmRevoke = () => {
		startRevokeTransition(async () => {
			const formData = new FormData();
			formData.append("token", token);
			const res = await revokeInvitationAction(undefined, formData);
			if (res.success) {
				toast("Invitation revoked!", { type: "success" });
				setDialogOpen(false);
				setDropdownOpen(false);
			} else {
				const err = res.error;
				toast(err, { type: "error" });
				setError(err);
			}
		});
	};

	return (
		<div className="px-2 py-4 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 opacity-50">
						<div className="w-9 h-9 rounded-full border border-dashed border-border flex items-center justify-center">
							{/* Empty circle with dashed border */}
						</div>
					</div>
					<div className="flex flex-col gap-y-1 font-medium">
						<div className="text-inverse/50 text-[14px] leading-[20.4px] flex items-center">
							{email}
							<span className="ml-2 text-text-muted text-[12px] leading-[16px]">
								(Invitation pending)
							</span>
						</div>
						{expired && (
							<div className="text-error-900 text-[12px] leading-[16px]">
								Expired on <LocalDateTime date={expiredAt} />
							</div>
						)}
					</div>
				</div>
				<div className="flex items-center gap-2">
					<span className="capitalize text-inverse font-medium text-[14px] leading-[16px] text-end font-sans">
						{role}
					</span>
					{canManageMembers && (
						<DropdownMenu
							modal={false}
							open={dropdownOpen}
							onOpenChange={setDropdownOpen}
						>
							<DropdownMenuTrigger className="cursor-pointer">
								<Ellipsis className="text-inverse/70" />
							</DropdownMenuTrigger>
							<DropdownMenuContent
								align="end"
								className="p-1 border-[0.5px] border-white/10 rounded-[8px] min-w-[165px] bg-white/[0.02] backdrop-blur-md shadow-[inset_0_1px_1px_rgba(255,255,255,0.1),inset_0_-1px_1px_rgba(255,255,255,0.05)] relative overflow-hidden before:content-[''] before:absolute before:inset-0 before:bg-white before:opacity-[0.02] before:rounded-[inherit] before:pointer-events-none"
							>
								<DropdownMenuItem
									onSelect={(e) => {
										e.preventDefault();
										handleCopy();
									}}
									className="flex items-center px-4 py-3 font-medium text-[14px] leading-[16px] text-inverse hover:bg-white/5 rounded-md focus:outline-none"
									title="Copy invite link"
								>
									<Copy className="h-4 w-4 mr-2" /> Copy invite link
								</DropdownMenuItem>
								<DropdownMenuItem
									onSelect={(e) => {
										e.preventDefault();
										handleResend();
									}}
									disabled={isResendPending}
									className="flex items-center px-4 py-3 font-medium text-[14px] leading-[16px] text-inverse hover:bg-white/5 rounded-md"
									title="Resend invitation"
								>
									{isResendPending ? (
										<>
											<RefreshCw className="h-4 w-4 animate-spin mr-2" />{" "}
											Processing...
										</>
									) : (
										<>
											<RefreshCw className="h-4 w-4 mr-2" /> Resend invitation
										</>
									)}
								</DropdownMenuItem>
								<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
									<DialogTrigger asChild>
										<DropdownMenuItem
											onSelect={(e) => e.preventDefault()}
											disabled={isRevokePending}
											className="flex items-center w-full px-4 py-3 font-medium text-[14px] leading-[16px] text-error-900 hover:bg-error-900/20 rounded-md"
											title="Revoke invitation"
										>
											{isRevokePending ? (
												<>
													<RefreshCw className="h-4 w-4 animate-spin mr-2" />{" "}
													Processing...
												</>
											) : (
												<>
													<Trash2 className="h-4 w-4 mr-2" /> Revoke invitation
												</>
											)}
										</DropdownMenuItem>
									</DialogTrigger>
									<DialogContent variant="destructive">
										<DialogHeader>
											<DialogTitle className="font-sans text-[20px] font-medium tracking-tight text-error-900">
												Revoke Invitation
											</DialogTitle>
											<DialogDescription className="text-error-900/50">
												This will permanently revoke this invitation and prevent
												the user from joining your team.
											</DialogDescription>
											<DialogClose className="text-inverse" />
										</DialogHeader>
										<DialogBody>{/* Content goes here if needed */}</DialogBody>
										<DialogFooter>
											<Button
												variant="link"
												onClick={() => setDialogOpen(false)}
												disabled={isRevokePending}
											>
												Cancel
											</Button>
											<Button
												variant="destructive"
												onClick={handleConfirmRevoke}
												disabled={isRevokePending}
											>
												{isRevokePending ? "Processing..." : "Revoke"}
											</Button>
										</DialogFooter>
									</DialogContent>
								</Dialog>
							</DropdownMenuContent>
						</DropdownMenu>
					)}
				</div>
			</div>
			{error && (
				<div className="text-error-900 text-[12px] mt-1 ml-12">{error}</div>
			)}
		</div>
	);
}
