'use client';
import { Link } from '@/shared/config/i18n/navigation';
import { Button } from '@/shared/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/shared/ui/dropdown-menu';
import { ChangeLang } from './ChangeLang';
import { useLoginModal, useRegisterModal } from '@/shared/zustand/auth';
import { useTranslations } from 'next-intl';
import { useUserPlagiatStore } from '@/shared/zustand/user';
import { ChevronDown, LogOut } from 'lucide-react';
import { useEffect, useState } from 'react';

function AuthButtons() {
  const t = useTranslations('Navbar');
  const [localUser, setLocalUser] = useState<{
    id: number;
    name: string;
    surname: string;
  } | null>(null);
  const [open, setOpen] = useState(false);

  const toggleLoginModal = useLoginModal((state) => state.toggleLoginModal);
  const toggleRegisterModal = useRegisterModal(
    (state) => state.toggleRegisterModal,
  );
  const user = useUserPlagiatStore((state) => state.user);
  const clearUser = useUserPlagiatStore((state) => state.clearUser);

  const clearTokens = () => {
    localStorage.removeItem('access');
    localStorage.removeItem('refresh');
    localStorage.removeItem('user');
    clearUser();
  };

  useEffect(() => {
    const data = localStorage.getItem('user');
    if (data) {
      setLocalUser(JSON.parse(data));
    } else {
      setLocalUser(null);
    }
  }, [user]);

  if (localUser) {
    return (
      <div className="flex flex-row max-sm:items-center max-sm:justify-around gap-3 items-center">
        <div className="sm:flex hidden">
          <ChangeLang />
        </div>
        <DropdownMenu open={open} onOpenChange={setOpen}>
          <DropdownMenuTrigger className="inline-flex items-center gap-1 text-lg font-medium outline-none">
            {localUser.name}
            <ChevronDown className="size-4" />
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            <DropdownMenuItem
              onClick={() => {
                clearTokens();
                setOpen(false);
              }}
            >
              <Link
                className="flex flex-row gap-4 rounded-md p-3 cursor-pointer"
                href={'/'}
              >
                <LogOut className="size-5 shrink-0 text-foreground" />
                <span className="text-sm font-semibold">{t('logout')}</span>
              </Link>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    );
  }

  return (
    <div className="flex flex-row max-sm:items-center max-sm:justify-around gap-3 items-center">
      <div className="sm:flex hidden">
        <ChangeLang />
      </div>
      <Button variant="outline" onClick={() => toggleLoginModal()}>
        {t('login')}
      </Button>
      <Button onClick={() => toggleRegisterModal()}>{t('signup')}</Button>
    </div>
  );
}

export { AuthButtons };
