"use client";
import { Check, CheckCheck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { verifyUser } from "@/actions/user-actions";
import { Button } from "@/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogFooter,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "@/components/ui/dialog";
import type { UserProfile } from "@/lib/types/user";

export function UserVerifyDialog({ user }: { user: UserProfile }) {
	const userId = user.id;
	const [disabled, setDisabled] = useState(false);
	const [open, setOpen] = useState(false);
	return (
		<Dialog open={open} onOpenChange={setOpen}>
			<DialogTrigger asChild>
				<Button
					variant={user.verified ? "secondary" : "default"}
					disabled={disabled || user.verified}
				>
					{user.verified ? <CheckCheck size={16} /> : <Check size={16} />}
					{user.verified ? "Verified" : "Verify"}
				</Button>
			</DialogTrigger>
			<DialogContent>
				<DialogHeader>
					<DialogTitle className="text-muted-foreground">Verify User</DialogTitle>
					<DialogDescription>
						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>
					</DialogDescription>
				</DialogHeader>
				<DialogFooter>
					<Button
						disabled={disabled}
						onClick={async () => {
							setOpen(true);
							setDisabled(true);
							const res = await verifyUser(String(userId));
							if (res.ok) toast.success('User Verified!');
							else toast.warning(res.error, {
								description: <div>
									<p className="italic">The following fields do not match</p>
									<ul className="list-disc list-inside p-2">
										{res.mismatch_fields?.map((field) => (
											<li key={field}>{field}</li>
										))}
									</ul>
								</div>,
								closeButton: true,
								duration: 10000,
							});
							setDisabled(false);
						}}
					>
						{disabled ? "Verifying..." : "Verify"}
					</Button>
				</DialogFooter>
			</DialogContent>
		</Dialog>
	);
}
