"use client";

import React from "react";

import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";

import { ChevronsUpDown, Copy, LogOut } from "lucide-react";

import { useLogin, usePrivy } from "@privy-io/react-auth";

import { cn, getInitials } from "@/lib/utils";
import { siteConfig } from "@/lib/config";

import { toast } from "sonner";

import Drawer from "@/components/drawer";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button, buttonVariants } from "@/components/ui/button";
import Menu from "@/components/menu";
import Spinner from "../spinner";
import { Skeleton } from "../ui/skeleton";

export default function Header() {
  const [addBorder, setAddBorder] = React.useState(false);

  const { ready, authenticated, logout, user } = usePrivy();
  const router = useRouter();

  const { login } = useLogin({
    onComplete: ({ user, isNewUser, wasAlreadyAuthenticated, loginMethod }) => {
      if (!wasAlreadyAuthenticated) toast.success("Login success");

      // router.replace("/");
    },
    onError: (error) => {
      console.log(error);
      toast.error(error);
    },
  });

  React.useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 20) {
        setAddBorder(true);
      } else {
        setAddBorder(false);
      }
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <header
      className={"h-16 sticky top-0 z-50 py-2 bg-background/60 backdrop-blur"}
    >
      <div className="flex items-center layout">
        <Link
          href="/"
          title="brand-logo"
          className="grow relative flex items-center space-x-2"
        >
          <Image
            src="/logo.png"
            height={44}
            width={44}
            alt="logo"
            className="rounded-md shadow"
          />
          <span className="font-bold text-xl">{siteConfig.name}</span>
        </Link>

        <div className="hidden lg:block">
          <div className="flex items-center ">
            <nav className="mr-10">
              <Menu />
            </nav>
            <div className="gap-2 flex">
              {!ready ? (
                <Skeleton className="h-10 w-32" />
              ) : (
                <>
                  {authenticated && user ? (
                    <DropdownMenu>
                      <DropdownMenuTrigger className="max-w-48 flex items-center gap-2 border p-2 rounded-md">
                        <Avatar className="h-8 w-8 rounded-lg">
                          <AvatarFallback className="rounded-lg">
                            {user.email ? getInitials(user.email.address) : "U"}
                          </AvatarFallback>
                        </Avatar>
                        <div className="grid flex-1 text-left text-sm leading-tight">
                          <span className="truncate font-semibold">
                            {user.email && user.email.address}
                            {user.wallet && user.wallet.address}
                          </span>
                          <span className="truncate text-xs">{user.id}</span>
                        </div>
                        <ChevronsUpDown className="ml-auto size-4" />
                      </DropdownMenuTrigger>
                      <DropdownMenuContent
                        className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
                        side={"bottom"}
                        align="end"
                        sideOffset={4}
                      >
                        <DropdownMenuLabel className="p-0 font-normal">
                          <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                            <Avatar className="h-8 w-8 rounded-lg">
                              <AvatarFallback className="rounded-lg">
                                {user.email
                                  ? getInitials(user.email.address)
                                  : "U"}
                              </AvatarFallback>
                            </Avatar>
                            <div className="grid flex-1 text-left text-sm leading-tight">
                              <span className="truncate font-semibold">
                                {user.email?.address}
                              </span>
                              <span className="truncate text-xs">
                                {user.id}
                              </span>
                            </div>
                          </div>
                        </DropdownMenuLabel>
                        <DropdownMenuSeparator />
                        {user.wallet !== undefined && (
                          <DropdownMenuItem
                            asChild
                            className="focus:bg-accent focus:text-primary"
                          >
                            <Button
                              variant={"ghost"}
                              className="flex-start w-full"
                              onClick={() => {
                                navigator.clipboard.writeText(
                                  user.wallet!.address
                                );
                                toast.info("Copied to clipboard!");
                              }}
                            >
                              <Copy />
                              Copy wallet code
                            </Button>
                          </DropdownMenuItem>
                        )}
                        <DropdownMenuItem
                          onClick={() => {
                            logout();
                            toast.success("You have been signed out");
                          }}
                          asChild
                          className="focus:bg-accent focus:text-primary"
                        >
                          <Button
                            variant={"ghost"}
                            className="flex-start w-full"
                          >
                            <LogOut />
                            Sign out
                          </Button>
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  ) : (
                    <Button
                      onClick={login}
                      className={buttonVariants({ variant: "default" })}
                    >
                      Connect Wallet
                    </Button>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
        <div className="ml-1 mt-2 cursor-pointer block lg:hidden">
          {authenticated && user ? (
            <DropdownMenu>
              <DropdownMenuTrigger className="max-w-48 flex items-center gap-2 border p-2 rounded-md">
                <Avatar className="hidden sm:block h-8 w-8 rounded-lg">
                  <AvatarFallback className="rounded-lg">
                    {user.email ? getInitials(user.email.address) : "U"}
                  </AvatarFallback>
                </Avatar>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-semibold">
                    {user.email && user.email.address}
                    {user.wallet && user.wallet.address}
                  </span>
                  <span className="truncate text-xs">{user.id}</span>
                </div>
                <ChevronsUpDown className="ml-auto size-4" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
                side={"bottom"}
                align="end"
                sideOffset={4}
              >
                <DropdownMenuLabel className="p-0 font-normal">
                  <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                    <Avatar className="h-8 w-8 rounded-lg">
                      <AvatarFallback className="rounded-lg">
                        {user.email ? getInitials(user.email.address) : "U"}
                      </AvatarFallback>
                    </Avatar>
                    <div className="grid flex-1 text-left text-sm leading-tight">
                      <span className="truncate font-semibold">
                        {user.email?.address}
                      </span>
                      <span className="truncate text-xs">{user.id}</span>
                    </div>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                {user.wallet !== undefined && (
                  <DropdownMenuItem
                    asChild
                    className="focus:bg-accent focus:text-primary"
                  >
                    <Button
                      variant={"ghost"}
                      className="flex-start w-full"
                      onClick={() => {
                        navigator.clipboard.writeText(user.wallet!.address);
                        toast.info("Copied to clipboard!");
                      }}
                    >
                      <Copy />
                      Copy wallet code
                    </Button>
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem
                  onClick={() => {
                    logout();
                    toast.success("You have been signed out");
                  }}
                  asChild
                  className="focus:bg-accent focus:text-primary"
                >
                  <Button variant={"ghost"} className="flex-start w-full">
                    <LogOut />
                    Sign out
                  </Button>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          ) : (
            <Button
              onClick={login}
              className={buttonVariants({ variant: "default" })}
            >
              Connect Wallet
            </Button>
          )}
        </div>
        <div className="ml-1 mt-2 cursor-pointer block lg:hidden">
          <Drawer login={login} />
        </div>
      </div>
      <hr
        className={cn(
          "absolute w-full bottom-0 transition-opacity duration-300 ease-in-out",
          addBorder ? "opacity-100" : "opacity-0"
        )}
      />
    </header>
  );
}
