'use client';
import clsx from 'clsx';
import Image from 'next/image';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Cookies from 'js-cookie';
import { useMutation } from '@tanstack/react-query';
import Icon from '@/components/Icon';
import { COOKIE_NAME } from '@/api/api';
import { AuthorizationService } from '@/services/AuthorizationService';
import { Skeleton } from '@/components/UI/Loaders/Skeleton';

export const SettingsDropdown = () => {
  const router = useRouter();
  const [isOpenDropdown, setIsOpenDropdown] = useState<boolean>(false);

  const { mutateAsync, isPending } = useMutation({
    mutationKey: ['logout'],
    mutationFn: () => AuthorizationService.logout(),
    onSuccess: () => {
      Cookies.remove(COOKIE_NAME);
      router.push('/login');
    },
  });

  return (
    <div className='flex items-center gap-[6px] relative'>
      <div className='w-11 h-11 rounded-[50%] relative bg-[#F5F6FA]'>
        <Image
          src='/images/avatar_empty.png'
          alt='avatar'
          width={44}
          height={44}
          aria-label='Аватар'
          title='Аватар'
        />
      </div>
      <button onClick={() => setIsOpenDropdown(!isOpenDropdown)}>
        <Icon
          src='/images/icons/icon-chevron-down.svg'
          className={clsx(
            'text-[#2981B3] w-[10px] h-[5px] transition-transform duration-300',
            isOpenDropdown ? 'rotate-180' : 'rotate-0',
          )}
        />
      </button>

      {isOpenDropdown && (
        <div className='absolute top-[120%] right-0 w-max px-4 bg-white shadow-2xl rounded-xl'>
          {isPending ? (
            <Skeleton className='w-[80px] h-6' />
          ) : (
            <div className='flex items-center gap-2' role='button' onClick={() => mutateAsync()}>
              <Icon src='/images/icons/icon-logout.svg' className='min-w-4 w-4 h-4 text-black' />
              <p className='text-base'>Выйти</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
};
