'use client'

import Image from 'next/image'
import { Session } from 'next-auth'
import { signOut } from 'next-auth/react'

import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import { sync } from 'framer-motion'
import service, { UserDataStorageName } from '@/lib/http/service'
import React from 'react'
import toast from 'react-hot-toast'
import { useRouter } from 'next/navigation'

function getUserInitials(name: string) {
  const [firstName, lastName] = name.split(' ')
  return lastName ? `${firstName[0]}${lastName[0]}` : firstName.slice(0, firstName.length)
}

export interface UserData {
  auth_token: string;
  id: number;
  login_ip: string;
  login_time: number;
  role: string;
  first_name: string;
  user_name: string;
  version: string;
  image?: string;
}


export function UserMenu({ user }: { user: UserData }) {

  const [isLoading, setIsLoading] = React.useState(false);

  const router = useRouter()

  return (
    <div className="flex items-center justify-between">
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="px-2">
            {user?.image ? (
              <Image
                className="h-6 w-6 select-none rounded-full ring-1 ring-zinc-100/10 transition-opacity duration-300 hover:opacity-80"
                src={`${user.image}&s=60`}
                alt='User profile image'
                width={24}
                height={24}
              />
            ) : (
              <div className="flex h-7 w-7 shrink-0 select-none items-center justify-center rounded-full bg-muted/50 text-xs font-medium uppercase text-muted-foreground">
                {user?.user_name ? getUserInitials(user?.user_name.slice(0, 2)) : null}
              </div>
            )}
            <span className="ml-2 hidden lg:flex">{user?.user_name && getUserInitials(user?.user_name)}</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent sideOffset={8} align="start" className="w-[180px]">
          {/* <DropdownMenuItem className="flex-col items-start">
            <div className="text-xs font-medium">{user?.user_name}</div>
            <div className="text-xs text-zinc-500">{user?.user_name}</div>
          </DropdownMenuItem> */}
          <DropdownMenuItem
            onClick={async () => {

              console.log('logout')

              if (isLoading) return

              setIsLoading(true);
              await service.post('/api/v1/customer/logout', {
              }, {
                headers: {
                  'Authorization': user.auth_token
                }
              }).then(function (result: any) {
                setIsLoading(false);
                console.log("result:", result)

                if (result && result.header.code != 0) {

                  toast.error(result.header.message)
                  return
                }

                localStorage.removeItem(UserDataStorageName);

                // router.refresh()
                // router.push('/')

                window.location.href = `/`
                // location.reload();

              }).catch((err) => {
                setIsLoading(false);
                localStorage.removeItem(UserDataStorageName);
                // location.reload();
                window.location.href = `/`
                console.log(err);
                // if (err.errors[0].code === "form_identifier_not_found") {
                //   props.setAccountNotFound(true);
                //   props.email(email);
                // } else {
                //   props.setError("Sorry, We couldn't sign you in. Please try again later");
                // }
              });


              // signOut({
              //   callbackUrl: '/'
              // })
            }

            }
            className="text-xs"
          >
            Log Out
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}
