"use client";

import React from "react";

import Link from "next/link";

import { toast } from "sonner";

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

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

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button, buttonVariants } from "@/components/ui/button";
import { Icons } from "@/components/icons";
import { MobileDrawer } from "@/components/mobile-drawer";

import { Skeleton } from "./ui/skeleton";
import { Avatar, AvatarFallback } from "./ui/avatar";
import { ChevronsUpDown, Copy, LogOut } from "lucide-react";
import Image from "next/image";

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

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

  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="sticky top-0 h-[var(--header-height)] z-50 p-0 pb-16 bg-background/60 backdrop-blur">
      <div className="flex justify-between items-center layout mx-auto py-2 px-3 sm:px-6 border-x">
        <Link
          href="/"
          title="brand-logo"
          className="relative mr-6 flex items-center space-x-2"
        >
          {/* <Icons.logo className="w-auto" /> */}
          <Image src="/logo.png" height={40} width={36} alt="logo" />
          <span className="font-bold text-xl">{siteConfig.name}</span>
        </Link>
        <nav className="hidden lg:block">
          <ul className="flex gap-4">
            <li>
              <Link
                href={"/#features"}
                className={cn(
                  "transition-all hover:font-bold hover:border-b hover:pb-1"
                )}
              >
                Features
              </Link>
            </li>
            <li>
              <Link
                href={"/#tokenomics"}
                className={cn(
                  "transition-all hover:font-bold hover:border-b hover:pb-1"
                )}
              >
                Tokenomics
              </Link>
            </li>
            <li>
              <Link
                href={"https://soviro.gitbook.io/soviro"}
                target="_blank"
                className={cn(
                  "transition-all hover:font-bold hover:border-b hover:pb-1"
                )}
              >
                Docs
              </Link>
            </li>
          </ul>
        </nav>
        <div className="hidden lg:block">
          {!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 className="mt-2 cursor-pointer block lg:hidden">
          <MobileDrawer />
        </div>
      </div>
      <hr
        className={cn(
          "absolute w-full bottom-0 transition-opacity duration-300 ease-in-out"
        )}
      />
    </header>
  );
}
