'use client';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/Avatar';
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from '@/components/ui/Popover';
import { ChevronUpIcon, HeartIcon, LogOut } from 'lucide-react';
import Social from '../social';
import { useEffect, useState } from 'react';
import api from '@/api';
import { useTranslation } from 'react-i18next';
import LanguageSelect from '@/components/language-select';
import i18n, { normalizeLanguage } from '@/i18n';
import { useUserStore } from '@/store';
import { useSystemStore } from '@/c-store/useSystemStore';

const UserProfileCard = () => {
  const { t } = useTranslation();
  const [language, setLanguage] = useState<string>(
    normalizeLanguage(i18n.language),
  );
  const { logout, userInfo, isInitialized } = useUserStore();

  // Use userInfo from store instead of making API call
  useEffect(() => {
    if (isInitialized && userInfo?.language) {
      const normalizedLang = normalizeLanguage(userInfo.language);
      setLanguage(normalizedLang);
    }
  }, [isInitialized, userInfo?.language]);

  useEffect(() => {
    if (language !== i18n.language) {
      i18n.changeLanguage(language);
    }
  }, [language]);

  // Keep local selection in sync if language changes elsewhere
  useEffect(() => {
    const current = normalizeLanguage(i18n.resolvedLanguage ?? i18n.language);
    if (language !== current) {
      setLanguage(current);
    }
  }, [i18n.language, i18n.resolvedLanguage]);

  if (!isInitialized || !userInfo) {
    return null;
  }

  const updateLanguage = async (language: string) => {
    const normalizedLang = normalizeLanguage(language);
    setLanguage(normalizedLang);
    try {
      await api.updateUserInfo({ language: normalizedLang });
    } catch (e) {
      // non-blocking
      console.warn('Failed to persist language preference', e);
    }
    // Update stores for immediate UI coherence
    useUserStore.getState().updateUserInfo({ language: normalizedLang });
    try {
      useSystemStore.getState().updateLanguage(normalizedLang);
    } catch {}
  };

  const userMenuItems: {
    icon: React.ReactNode;
    label: string;
    href: string;
    id?: string;
  }[] = [
    {
      icon: <HeartIcon className='w-4 h-4' />,
      id: 'follow',
      label: t('common.core.follow'),
      href: '#',
    },
  ];

  return (
    <Popover>
      <PopoverTrigger asChild>
        <div className='flex items-center space-x-2 p-2 rounded-lg hover:bg-gray-100 cursor-pointer transition-all duration-200 group'>
          <Avatar className='w-9 h-9'>
            <AvatarImage src='https://github.com/shadcn.png' />
            <AvatarFallback>CN</AvatarFallback>
          </Avatar>
          <div className='flex-1'>
            <div className='font-medium'>{userInfo.name}</div>
            <div className='text-sm text-gray-500'>{userInfo.email}</div>
          </div>
          <ChevronUpIcon className='w-4 h-4 text-gray-500 transition-transform duration-200 group-data-[state=open]:rotate-180' />
        </div>
      </PopoverTrigger>
      <PopoverContent
        side='top'
        align='start'
        className='w-64 p-2 border rounded-lg bg-background shadow-md animate-in slide-in-from-bottom-2 duration-200'
        sideOffset={5}
      >
        <div className='flex items-center space-x-2 p-2'>
          <Avatar className='w-9 h-9'>
            <AvatarImage src='https://github.com/shadcn.png' />
            <AvatarFallback>CN</AvatarFallback>
          </Avatar>
          <div>
            <div className='font-medium'>{userInfo.name}</div>
            <div className='text-sm text-gray-500'>{userInfo.email}</div>
          </div>
        </div>
        <hr />
        <div className='space-y-1'>
          {userMenuItems.map((item, index) => {
            if (item.id == 'follow') {
              return (
                <div
                  key={index}
                  className=' relative group'
                >
                  <a
                    key={index}
                    href={item.href}
                    className='flex items-center space-x-2 px-3 py-2 rounded-lg hover:bg-gray-100'
                  >
                    {item.icon}
                    <span>{item.label}</span>
                  </a>
                  {item.id == 'follow' && (
                    <div className=' absolute bottom-0 left-1/2 hidden  group-hover:block  group-hover:animate-in  group-hover:slide-in-from-bottom-2  group-hover:duration-200'>
                      <Social />
                    </div>
                  )}
                </div>
              );
            }
            return (
              <a
                key={index}
                href={item.href}
                className='flex items-center space-x-2 px-3 py-2 rounded-lg hover:bg-gray-100'
              >
                {item.icon}
                <span>{item.label}</span>
              </a>
            );
          })}
          <div className='flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-gray-100'>
            <LogOut className='w-4 h-4 opacity-0' />
            <span className='flex-1 text-left'>
              {t('component.menus.navigationMenus.language')}
            </span>
            <div className='w-36'>
              <LanguageSelect
                language={language}
                onSetLanguage={updateLanguage}
                variant='standard'
              />
            </div>
          </div>
        </div>
        <hr />
        <div
          onClick={() => {
            logout();
          }}
          className='flex items-center space-x-2 px-3 py-2 rounded-lg hover:bg-gray-100 cursor-pointer'
        >
          <LogOut className='w-4 h-4' />
          <span>{t('common.core.logout')}</span>
        </div>
      </PopoverContent>
    </Popover>
  );
};

export default UserProfileCard;
