"use client"

import axios from "axios";
import * as React from 'react';
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { cn } from "@/lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Button } from "@/components/ui/button";
import { Check, ChevronsUpDown } from "lucide-react";
import { User } from "@prisma/client";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from "@/components/ui/command";


const AdminProfile = () => {
    const session = useSession();
    const [impersonation, setImpersonation] = useState<string | null>(null)
    const [open, setOpen] = useState(false)
    const [users, setUsers] = useState<User[]>([])

    useEffect(() => {
        const fetch = async (userId: string | undefined) => {
            if (!userId) return

            await axios.get("/api/users?id=" + userId)
                .then(u => setImpersonation(u.data?.name))
        }

        const fetchUsers = async () => {
            await axios.get<User[]>("/api/users")
                .then((u) => {
                    setUsers(u.data.filter(x => x.id != session.data?.user.id))
                })
        }

        fetch(session?.data?.user?.impersonation?.id)
        fetchUsers()
    }, [])

    const onImpersonationChange = async (userId: string, name: string) => {
        console.log("IMPERSONATION", impersonation)
        if (impersonation) {
            if (impersonation == name) {
                await axios.delete("/api/account/impersonate")
                    .then(() => {
                        setImpersonation(null)
                        window.location.reload()
                    })
            } else {
                await axios.put("/api/account/impersonate", { targetId: userId })
                    .then(() => {
                        setImpersonation(name)
                        window.location.reload()
                    })
            }
        } else {
            await axios.post("/api/account/impersonate", { targetId: userId })
                .then(() => {
                    setImpersonation(name)
                    window.location.reload()
                })
        }
    }

    return (
        <div className={"px-5 py-3 rounded-md bg-red-300 overflow-hidden wrap my-[10px] flex flex-grow flex-col gap-y-3"}>
            <div>
                <p className="text-xs text-gray-200">Role:</p>
                <p>{session?.data?.user?.role}</p>
            </div>
            <div>
                <p className="text-xs text-gray-200">Impersonation:</p>
                <Popover open={open} onOpenChange={setOpen}>
                    <PopoverTrigger asChild>
                        <Button
                            variant="outline"
                            role="combobox"
                            aria-expanded={open}
                            className="flex flex-grow justify-between text-xs">
                            {impersonation ? impersonation : "Select a user"}
                            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[200px] p-0">
                        <Command>
                            <CommandInput placeholder="Search users by name" />
                            <CommandEmpty>No voices found.</CommandEmpty>
                            <CommandGroup>
                                {users.map((user) => (
                                    <CommandItem
                                        key={user.id}
                                        value={user.name ?? undefined}
                                        onSelect={(currentValue) => {
                                            onImpersonationChange(user.id, user.name ?? "")
                                            setOpen(false)
                                        }}
                                    >
                                        <Check
                                            className={cn(
                                                "mr-2 h-4 w-4",
                                                user.name == impersonation ? "opacity-100" : "opacity-0"
                                            )}
                                        />
                                        {user.name}
                                    </CommandItem>
                                ))}
                            </CommandGroup>
                        </Command>
                    </PopoverContent>
                </Popover>
            </div>
        </div>
    );
}

export default AdminProfile;