'use client';

import React, { useEffect, useState, useRef } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { User, Settings, LogOut, CreditCard, LogIn, Camera, X, Shield } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Progress } from '@/components/ui/progress';
import { useAuthStore } from '@/store/authStore';
import { getAccessToken } from '@/lib/auth/tokenManager';
import { useUpload } from '@/hooks/useUpload';
import { getAvatarUploadUrl } from '@/lib/api/urls';
import { toast } from 'sonner';
import { logger } from '@/lib/utils/logger';
import { useUIStore } from '@/store/uiStore';

export function UserAvatar() {
  const router = useRouter();
  const { user, isAuthenticated, isLoading, logout, fetchSession, updateAvatar } = useAuthStore();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [showProgress, setShowProgress] = useState(false);

  const { progress, isUploading, upload, cancel } = useUpload({
    onSuccess: (data: unknown) => {
      const payload = data && typeof data === 'object' && 'data' in data && data.data && typeof data.data === 'object' && 'avatarUrl' in data.data
        ? (data.data as { avatarUrl?: string })
        : null;
      if (payload?.avatarUrl) updateAvatar(payload.avatarUrl);
      toast.success('头像更新成功');
      setShowProgress(false);
    },
    onError: (error) => {
      toast.error('头像上传失败');
      logger.error('Avatar upload error:', error);
      setShowProgress(false);
    },
    onCancel: () => {
      toast.info('上传已取消');
      setShowProgress(false);
    },
  });

  // Fetch user info on mount if authenticated
  useEffect(() => {
    if (isAuthenticated && !user) {
      fetchSession();
    }
  }, [isAuthenticated, user, fetchSession]);

  const handleLogout = async () => {
    await logout();
    router.push('/login');
  };

  // Get user initials for avatar
  const getInitials = () => {
    if (user?.username) {
      return user.username.charAt(0).toUpperCase();
    }
    return 'U';
  };

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件');
      return;
    }

    // Validate file size (5MB)
    if (file.size > 5 * 1024 * 1024) {
      toast.error('文件大小不能超过 5MB');
      return;
    }

    setShowProgress(true);
    const token = getAccessToken();
    if (!user?.id) {
      toast.error('用户未登录');
      return;
    }
    await upload(file, {
      endpoint: getAvatarUploadUrl(user.id),
      onProgress: (p) => console.log('[Upload]', p + '%'),
    });

    // Reset file input
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleCancelUpload = () => {
    cancel();
    setShowProgress(false);
  };

  // Not authenticated - show login button
  if (!isAuthenticated) {
    return (
      <Link
        href="/login"
        className="relative w-9 h-9 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 border border-white/10 shadow-lg flex items-center justify-center overflow-hidden hover:ring-2 hover:ring-white/20 transition-all outline-none group"
      >
        <LogIn className="h-4 w-4 text-white group-hover:scale-110 transition-transform" />
      </Link>
    );
  }

  return (
    <>
      <input
        type="file"
        ref={fileInputRef}
        className="hidden"
        accept="image/jpeg,image/png,image/jpg"
        onChange={handleFileChange}
      />
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <button className="relative w-9 h-9 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 border border-white/10 shadow-lg flex items-center justify-center overflow-hidden hover:ring-2 hover:ring-white/20 transition-all outline-none group">
            {user?.avatarUrl ? (
              <img
                src={user.avatarUrl}
                alt={user.username}
                className="w-full h-full object-cover"
              />
            ) : (
              <span className="text-sm font-bold text-white group-hover:scale-110 transition-transform">
                {getInitials()}
              </span>
            )}
          </button>
        </DropdownMenuTrigger>
        <DropdownMenuContent className="w-56 bg-black/90 border-white/10 text-white backdrop-blur-xl" align="end" forceMount>
          <DropdownMenuLabel className="font-normal">
            <div className="flex flex-col space-y-1">
              <p className="text-sm font-medium leading-none text-white">
                {user?.username || 'User'}
              </p>
              <p className="text-xs leading-none text-muted-foreground">
                {user?.email || ''}
              </p>
            </div>
          </DropdownMenuLabel>
          <DropdownMenuSeparator className="bg-white/10" />
          <DropdownMenuGroup>
            {showProgress ? (
              <div className="px-2 py-1.5">
                <div className="flex items-center justify-between mb-1.5">
                  <span className="text-xs text-gray-400">上传中...</span>
                  <button
                    onClick={handleCancelUpload}
                    className="text-xs text-red-400 hover:text-red-300 flex items-center gap-0.5"
                  >
                    <X className="h-3 w-3" />
                    取消
                  </button>
                </div>
                <Progress value={progress} size="sm" showLabel />
              </div>
            ) : (
              <DropdownMenuItem
                className="focus:bg-white/10 focus:text-white cursor-pointer"
                onClick={handleAvatarClick}
                disabled={isUploading}
              >
                <Camera className="mr-2 h-4 w-4" />
                <span>更换头像</span>
              </DropdownMenuItem>
            )}
            <DropdownMenuItem className="focus:bg-white/10 focus:text-white cursor-pointer" disabled>
              <User className="mr-2 h-4 w-4" />
              <span>个人资料</span>
            </DropdownMenuItem>
            <DropdownMenuItem className="focus:bg-white/10 focus:text-white cursor-pointer" disabled>
              <CreditCard className="mr-2 h-4 w-4" />
              <span>计费</span>
            </DropdownMenuItem>
            <DropdownMenuItem
              className="focus:bg-white/10 focus:text-white cursor-pointer"
              onClick={() => useUIStore.getState().openSettings()}
            >
              <Settings className="mr-2 h-4 w-4" />
              <span>设置</span>
            </DropdownMenuItem>
            {user?.isSuperuser && (
              <DropdownMenuItem
                className="focus:bg-white/10 focus:text-white cursor-pointer"
                onClick={() => router.push('/admin')}
              >
                <Shield className="mr-2 h-4 w-4" />
                <span>管理后台</span>
              </DropdownMenuItem>
            )}
          </DropdownMenuGroup>
          <DropdownMenuSeparator className="bg-white/10" />
          <DropdownMenuItem
            className="focus:bg-white/10 focus:text-white cursor-pointer text-red-400 focus:text-red-400"
            onClick={handleLogout}
            disabled={isLoading}
          >
            <LogOut className="mr-2 h-4 w-4" />
            <span>{isLoading ? '退出中...' : '退出登录'}</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
