"use client";
import { Check, CheckCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { VerifyUser } from "@/actions/user-actions";
import {
	AlertDialog,
	AlertDialogAction,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
	AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import type { UserProfile } from "@/lib/types/user";

export function UserVerifyDialog({ user }: { user: UserProfile }) {
	const userId = user.id;
	const [disabled, setDisabled] = useState(false);
	return (
		<AlertDialog>
			<AlertDialogTrigger asChild>
				<Button
					variant={user.verified ? "secondary" : "default"}
					disabled={disabled || user.verified}
				>
					{user.verified ? <CheckCheck size={16} /> : <Check size={16} />}
					{user.verified ? "Verified" : "Verify"}
				</Button>
			</AlertDialogTrigger>
			<AlertDialogContent>
				<AlertDialogHeader>
					<AlertDialogTitle className="text-muted-foreground">Verify User</AlertDialogTitle>
					<AlertDialogDescription>
						Are you sure you want to verify the following user?
						<span className="inline-block my-4">
							<li>
								Name: {user.first_name} {user.last_name}
							</li>
							<li>ID Card: {user.id_card}</li>
							<li>Address: {user.address}</li>
							<li>
								DOB:{" "}
								{new Date(user.dob ?? "").toLocaleDateString("en-US", {
									month: "short",
									day: "2-digit",
									year: "numeric",
								})}
							</li>
							<li>Phone Number: {user.mobile}</li>
						</span>
					</AlertDialogDescription>
				</AlertDialogHeader>
				<AlertDialogFooter>
					<AlertDialogCancel>Cancel</AlertDialogCancel>
					<AlertDialogAction
						disabled={disabled}
						onClick={() => {
							setDisabled(true);
							toast.promise(VerifyUser(String(userId)), {
								loading: "Verifying...",
								success: () => {
									setDisabled(false);
									return "User Verified!";
								},
								error: (error: Error) => {
									setDisabled(false);
									return error.message || "Something went wrong";
								},
							});
						}}
					>
						{disabled ? "Verifying..." : "Verify"}
					</AlertDialogAction>
				</AlertDialogFooter>
			</AlertDialogContent>
		</AlertDialog>
	);
}
